From 76401657039ccd1cd7a34156c1b4d5a8101009c3 Mon Sep 17 00:00:00 2001 From: David Schroeder Date: Sat, 15 Nov 2025 18:57:58 -0600 Subject: [PATCH] Update vCenter-SSL.ps1 --- inc/vCenter-SSL.ps1 | 176 +++++++++++++++----------------------------- 1 file changed, 59 insertions(+), 117 deletions(-) diff --git a/inc/vCenter-SSL.ps1 b/inc/vCenter-SSL.ps1 index 039ccad6..245522be 100644 --- a/inc/vCenter-SSL.ps1 +++ b/inc/vCenter-SSL.ps1 @@ -1,9 +1,10 @@ #!/usr/bin/env pwsh # ----------------------------------------------------------------------------------- -# Linux-safe vCenter + Posh-ACME Script (Production Hardened) -# - Uses HttpClient with AutomaticDecompression disabled -# - Fault-tolerant ACME certificate request and upload -# - Handles PowerDNS plugin, vCenter session, certificate apply, service restart +# Linux-safe vCenter + Posh-ACME Script (Fully Fixed) +# - SSL validation bypass (Linux-compatible) +# - Proper ErrorRecord handling +# - PowerDNS plugin works (plain string API key) +# - Fault-tolerant certificate handling # ----------------------------------------------------------------------------------- . /opt/idssys/nodemgmt/conf/powerwall/settings.ps1 @@ -15,7 +16,7 @@ $global:helpme = $null $global:responseBody = $null # ---------------------------- -# Error handler (robust across platforms) +# Error handler # ---------------------------- function Show-Failure { param([System.Management.Automation.ErrorRecord]$ErrorRecord) @@ -24,38 +25,15 @@ function Show-Failure { try { $ex = $ErrorRecord.Exception - if ($ex.Response -is [System.Net.Http.HttpResponseMessage]) { - $resp = $ex.Response - try { - $global:responseBody = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() - } - catch { - $global:responseBody = "" - } - } - elseif ($ex.Response -is [System.Net.WebResponse]) { + try { $global:responseBody = $ex.Response.Content.ReadAsStringAsync().GetAwaiter().GetResult() } catch { $global:responseBody = "" } + } elseif ($ex.Response -is [System.Net.WebResponse]) { try { $stream = $ex.Response.GetResponseStream() - if ($stream) { - $reader = [System.IO.StreamReader]::new($stream) - $global:responseBody = $reader.ReadToEnd() - } - else { - $global:responseBody = "" - } - } - catch { - $global:responseBody = "" - } - } - else { - $global:responseBody = $ex.Message - } - } - catch { - $global:responseBody = "" - } + if ($stream) { $global:responseBody = [System.IO.StreamReader]::new($stream).ReadToEnd() } + } catch { $global:responseBody = "" } + } else { $global:responseBody = $ex.Message } + } catch { $global:responseBody = "" } $global:helpme = $global:responseBody @@ -64,6 +42,8 @@ function Show-Failure { Write-Host $global:responseBody -ForegroundColor Red Write-Host "The request/response body has been saved to `$global:helpme" -ForegroundColor Red Write-Host "----------------------------------------" -ForegroundColor Red + + exit 1 } # ---------------------------- @@ -82,8 +62,8 @@ function Invoke-SafeRestMethod { try { $handler = [System.Net.Http.HttpClientHandler]::new() $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::None - $handler.ServerCertificateCustomValidationCallback = { param($sender, $cert, $chain, $errors) return $true } - + # Proper SSL bypass + $handler.ServerCertificateCustomValidationCallback = { param($sender, $cert, $chain, $sslPolicyErrors) return $true } $client = [System.Net.Http.HttpClient]::new($handler) $client.Timeout = [System.TimeSpan]::FromSeconds($TimeoutSec) @@ -97,39 +77,28 @@ function Invoke-SafeRestMethod { if ($AsJson) { $jsonBody = $Body | ConvertTo-Json -Depth 12 -Compress $content = [System.Net.Http.StringContent]::new($jsonBody, [System.Text.Encoding]::UTF8, 'application/json') - } - else { + } else { $content = [System.Net.Http.StringContent]::new($Body) } - } - else { $content = $null } + } else { $content = $null } - $method = [System.Net.Http.HttpMethod]::$Method - $request = [System.Net.Http.HttpRequestMessage]::new($method, $Uri) + $methodObj = [System.Net.Http.HttpMethod]::$Method + $request = [System.Net.Http.HttpRequestMessage]::new($methodObj, $Uri) if ($content) { $request.Content = $content } $response = $client.SendAsync($request).GetAwaiter().GetResult() - $respBody = $null - if ($response.Content -ne $null) { - $respBody = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() - } + $respBody = if ($response.Content) { $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() } else { $null } if ($response.IsSuccessStatusCode) { if ($respBody -and $respBody.Trim().Length -gt 0) { - try { return $respBody | ConvertFrom-Json } - catch { return $respBody } - } - else { return $respBody } - } - else { + try { return $respBody | ConvertFrom-Json } catch { return $respBody } + } else { return $respBody } + } else { throw [System.Net.Http.HttpRequestException]::new("HTTP $($response.StatusCode): $($response.ReasonPhrase)", $null, $response) } - } - catch { + } catch { Show-Failure -ErrorRecord $_ - return $null - } - finally { + } finally { $client.Dispose() $handler.Dispose() } @@ -144,12 +113,13 @@ $EmailContact = $ACMEEMAIL [PSCredential]$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $VCENTERUSER, (ConvertTo-SecureString $VCENTERPASS -AsPlainText -Force) +# PowerDNS plugin args (plain string API key!) $pArgs = @{ - PowerDNSApiHost = $WDNSHOST - PowerDNSApiKey = $PDNSAPI - PowerDNSUseTLS = $true - PowerDNSPort = 443 - PowerDNSServerName = 'localhost' + PowerDNSApiHost = $WDNSHOST + PowerDNSApiKey = $PDNSAPI + PowerDNSUseTLS = $true + PowerDNSPort = 443 + PowerDNSServerName = 'localhost' } # ---------------------------- @@ -161,7 +131,7 @@ if (-not (Get-Module -ListAvailable -Name Posh-ACME)) { Import-Module Posh-ACME -ErrorAction Stop # ---------------------------- -# vCenter API Session +# Connect to vCenter API # ---------------------------- $loginUri = "https://$vCenterURL/rest/com/vmware/cis/session" Write-Host "Connecting to vCenter at $vCenterURL ..." -ForegroundColor Cyan @@ -170,38 +140,22 @@ try { $sessionResponse = Invoke-SafeRestMethod -Uri $loginUri -Method Post -Headers @{} $sessionToken = $sessionResponse.value if (-not $sessionToken) { - # fallback: session token may be in header - $httpClient = [System.Net.Http.HttpClient]::new() - $req = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $loginUri) - $resp = $httpClient.SendAsync($req).GetAwaiter().GetResult() - if ($resp.Headers.Contains("vmware-api-session-id")) { - $sessionToken = $resp.Headers.GetValues("vmware-api-session-id") | Select-Object -First 1 - } - $httpClient.Dispose() + throw [System.Exception] "Unable to obtain vCenter session token" } -} -catch { +} catch { Show-Failure -ErrorRecord $_ } -if (-not $sessionToken) { Show-Failure -ErrorRecord ([pscustomobject]@{ Exception = [System.Exception] "Unable to obtain vCenter session token" }) } +$headers = @{ 'vmware-api-session-id' = $sessionToken } Write-Host "Connected to vCenter API. Session established." -ForegroundColor Green -$headers = @{ 'vmware-api-session-id' = $sessionToken } - # ---------------------------- -# Retrieve VM List (optional) +# Retrieve VM list (optional) # ---------------------------- try { $vmList = Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/vm" -Headers $headers - if ($vmList.value) { - Write-Host "Retrieved VM list:" -ForegroundColor Cyan - $vmList.value | ForEach-Object { Write-Host " - $($_.name)" } - } -} -catch { - Write-Host "Unable to retrieve VM list, continuing..." -ForegroundColor Yellow -} + if ($vmList.value) { $vmList.value | ForEach-Object { Write-Host " - $($_.name)" } } +} catch { Write-Host "Unable to retrieve VM list, continuing..." -ForegroundColor Yellow } # ---------------------------- # Fault-tolerant ACME certificate request @@ -212,8 +166,7 @@ try { Write-Host "Requesting certificate via Posh-ACME..." -ForegroundColor Cyan New-PACertificate -Domain $CommonName -DnsPlugin PowerDNS -PluginArgs $pArgs -Contact $EmailContact -AcceptTOS -Verbose -Force $certSuccess = $true -} -catch { +} catch { Write-Host "ACME certificate request failed: $($_.Exception.Message)" -ForegroundColor Yellow $global:helpme = $_.Exception.Message } @@ -221,60 +174,49 @@ catch { # ---------------------------- # Collect certificate paths # ---------------------------- -$paAccount = Get-PAAccount -$certFolder = $paAccount.CertFolder -$certPath = Join-Path $certFolder "$certName\cert.pem" -$keyPath = Join-Path $certFolder "$certName\privkey.pem" -$chainPath = Join-Path $certFolder "$certName\chain.pem" +if ($certSuccess) { + $paAccount = Get-PAAccount + $certFolder = $paAccount.CertFolder + $certPath = Join-Path $certFolder "$certName\cert.pem" + $keyPath = Join-Path $certFolder "$certName\privkey.pem" + $chainPath = Join-Path $certFolder "$certName\chain.pem" -foreach ($f in @($certPath, $keyPath, $chainPath)) { - if (-not (Test-Path $f)) { - Write-Host "Certificate file missing: $f" -ForegroundColor Yellow - $certSuccess = $false + foreach ($f in @($certPath, $keyPath, $chainPath)) { + if (-not (Test-Path $f)) { + Write-Host "Certificate file missing: $f" -ForegroundColor Yellow + $certSuccess = $false + } } } # ---------------------------- -# Upload certificate to vCenter (if ACME succeeded) +# Upload and apply certificate # ---------------------------- if ($certSuccess) { try { - Write-Host "Uploading certificate to vCenter..." -ForegroundColor Cyan - $body = @{ + Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls" -Method Post -Headers $headers -Body @{ cert = Get-Content -Path $certPath -Raw key = Get-Content -Path $keyPath -Raw chain = Get-Content -Path $chainPath -Raw - } - Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls" -Method Post -Headers $headers -Body $body -AsJson + } -AsJson Write-Host "Certificate uploaded successfully." -ForegroundColor Green - } - catch { - Write-Host "Certificate upload failed: $($_.Exception.Message)" -ForegroundColor Yellow - $global:helpme = $_.Exception.Message - } - - # Apply certificate - try { Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls?action=apply" -Method Post -Headers $headers Write-Host "TLS certificate applied." -ForegroundColor Green - } - catch { - Write-Host "Failed to apply certificate: $($_.Exception.Message)" -ForegroundColor Yellow + } catch { + Write-Host "Certificate upload/apply failed: $($_.Exception.Message)" -ForegroundColor Yellow $global:helpme = $_.Exception.Message } -} -else { +} else { Write-Host "Skipping certificate upload/apply due to previous errors." -ForegroundColor Yellow } # ---------------------------- -# Restart vCenter vpxd service +# Restart vpxd service # ---------------------------- try { Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/appliance/system/services/vpxd?action=restart" -Method Post -Headers $headers Write-Host "vCenter vpxd service restart requested." -ForegroundColor Yellow -} -catch { +} catch { Write-Host "Failed to restart vpxd service: $($_.Exception.Message)" -ForegroundColor Yellow $global:helpme = $_.Exception.Message }