From 45b36941dbd1757201e378112b9d1369d52cefa8 Mon Sep 17 00:00:00 2001 From: David Schroeder Date: Sat, 15 Nov 2025 18:50:34 -0600 Subject: [PATCH] Update vCenter-SSL.ps1 --- inc/vCenter-SSL.ps1 | 229 ++++++++++++++++++++++---------------------- 1 file changed, 114 insertions(+), 115 deletions(-) diff --git a/inc/vCenter-SSL.ps1 b/inc/vCenter-SSL.ps1 index 46268133..a42ceac7 100644 --- a/inc/vCenter-SSL.ps1 +++ b/inc/vCenter-SSL.ps1 @@ -1,87 +1,75 @@ #!/usr/bin/env pwsh -# Integrated, Linux-safe vCenter + Posh-ACME script -# - Uses Accept-Encoding: identity to avoid GZipDecompressedContent disposal bugs -# - Safe Show-Failure that won't try to read disposed streams -# - Option A: vCenter session POST with NO body -# - Defensive file/content reads and clearer logging - . /opt/idssys/nodemgmt/conf/powerwall/settings.ps1 # ---------------------------- -# Global variables for troubleshooting -# ---------------------------- -$global:helpme = $null -$global:responseBody = $null - -# ---------------------------- -# Error handler (robust across platforms) +# Safe Failure Handler (cross-platform) # ---------------------------- function Show-Failure { param([System.Management.Automation.ErrorRecord]$ErrorRecord) - $global:responseBody = "" - + $global:helpme = "" try { $ex = $ErrorRecord.Exception - # If the exception contains an HttpResponseMessage (PowerShell Core) + # HttpResponseMessage path (PowerShell Core) if ($ex.Response -is [System.Net.Http.HttpResponseMessage]) { $resp = $ex.Response if ($resp -and $resp.Content) { try { - # Safe synchronous read of async task - $global:responseBody = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() + # Defensive read; won't deadlock and will catch disposed stream + $global:helpme = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() + if ([string]::IsNullOrWhiteSpace($global:helpme)) { + $global:helpme = "" + } } catch { - # If content was disposed or unreadable, capture the message - $global:responseBody = "" + $global:helpme = "" } } else { - $global:responseBody = "" + $global:helpme = "" } } - # Legacy WebResponse (rare with pwsh, but handle anyway) + + # Legacy WebResponse path elseif ($ex.Response -is [System.Net.WebResponse]) { try { $stream = $ex.Response.GetResponseStream() if ($stream) { $reader = [System.IO.StreamReader]::new($stream) - $global:responseBody = $reader.ReadToEnd() + $global:helpme = $reader.ReadToEnd() + if ([string]::IsNullOrWhiteSpace($global:helpme)) { + $global:helpme = "" + } } else { - $global:responseBody = "" + $global:helpme = "" } } catch { - $global:responseBody = "" + $global:helpme = "" } } + + # Fallback to exception message else { - # default to exception message if no response object present - $global:responseBody = $ex.Message + $global:helpme = $ex.Message } } catch { - $global:responseBody = "" + # In case the extraction itself fails + $global:helpme = "" } - # Save for later inspection - $global:helpme = $global:responseBody - - Write-Host "----------------------------------------" -ForegroundColor Red - Write-Host "Status: A system exception was caught." -ForegroundColor Red - Write-Host $global:responseBody -ForegroundColor Red - Write-Host "The request/response body has been saved to `$global:helpme" -ForegroundColor Red - Write-Host "----------------------------------------" -ForegroundColor Red - - # Terminate script (consistent and explicit) + Write-Host -ForegroundColor Red "Status: A system exception was caught." + Write-Host -ForegroundColor Red $global:helpme + Write-Host -ForegroundColor Red "The request body has been saved to `$global:helpme" exit 1 } # ---------------------------- -# Unified REST wrapper (TLS 1.2 + skip cert check + gzip-safe) +# Unified REST wrapper (TLS 1.2 + disable gzip + skip cert check) # ---------------------------- function Invoke-SafeRestMethod { param( @@ -90,31 +78,39 @@ function Invoke-SafeRestMethod { [hashtable]$Headers, $Body, [switch]$AsJson, - [int]$TimeoutSec = 60 + [int]$TimeoutSeconds = 60 ) try { + # Ensure headers object if (-not $Headers) { $Headers = @{} } - # Force identity encoding to avoid GZip decompression disposal bugs on pwsh - if (-not $Headers.ContainsKey('Accept-Encoding')) { - $Headers['Accept-Encoding'] = 'identity' + # Avoid gzip → prevents GZipDecompressedContent disposal bugs + if (-not $Headers.ContainsKey("Accept-Encoding")) { + $Headers["Accept-Encoding"] = "identity" + } + + # Ensure TLS1.2 (covers Windows & Pwsh where ServicePointManager is relevant) + try { + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + } + catch { + # If not applicable on this platform, ignore } $params = @{ Uri = $Uri Method = $Method Headers = $Headers - SslProtocol = 'Tls12' SkipCertificateCheck = $true ErrorAction = 'Stop' - TimeoutSec = $TimeoutSec + TimeoutSec = $TimeoutSeconds } - if ($PSBoundParameters.ContainsKey('Body') -and $Body -ne $null) { + if ($PSBoundParameters.ContainsKey('Body') -and $Body) { if ($AsJson) { - # Convert to JSON with reasonable depth for certificates etc. - $params.Body = $Body | ConvertTo-Json -Depth 12 -Compress + # ConvertTo-Json can produce arrays/objects -- use moderate depth + $params.Body = $Body | ConvertTo-Json -Depth 12 -Compress $params.ContentType = 'application/json' } else { @@ -125,13 +121,14 @@ function Invoke-SafeRestMethod { return Invoke-RestMethod @params } catch { - # Provide the full ErrorRecord to Show-Failure Show-Failure -ErrorRecord $_ + # Show-Failure calls exit 1, so code here shouldn't run, but keep for safety + throw } } # ---------------------------- -# Variables (pulled from settings.ps1) +# Variables (from settings.ps1) # ---------------------------- $vCenterURL = $VCENTERHOST $CommonName = $VCENTERHOST @@ -139,61 +136,72 @@ $EmailContact = $ACMEEMAIL [PSCredential]$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $VCENTERUSER, (ConvertTo-SecureString $VCENTERPASS -AsPlainText -Force) +# Posh-ACME / PowerDNS plugin args (PowerDNSApiKey as plain string) $pArgs = @{ PowerDNSApiHost = $WDNSHOST - PowerDNSApiKey = $PDNSAPI # keep as plain string for plugin + PowerDNSApiKey = $PDNSAPI PowerDNSUseTLS = $true PowerDNSPort = 443 PowerDNSServerName = 'localhost' } # ---------------------------- -# Ensure Posh-ACME Module (install if missing, then import) +# Ensure Posh-ACME Module # ---------------------------- Write-Host "Checking for Required Module Posh-ACME" -ForegroundColor Green - if (Get-Module -ListAvailable -Name Posh-ACME) { Write-Host "Posh-ACME Module Already Installed" -ForegroundColor Green -} else { +} +else { Write-Host "Posh-ACME Module Not Found, Installing..." -ForegroundColor Yellow - Install-Module -Name Posh-ACME -Force -Confirm:$false -Scope AllUsers - Write-Host "Posh-ACME installed. Continuing..." -ForegroundColor Green + Install-Module -Name Posh-ACME -Force -Confirm:$false + Write-Host "Please restart this script after module install." -ForegroundColor Yellow + exit 0 } -# Try to import module (loop until available) -$importAttempts = 0 -do { - try { - Import-Module Posh-ACME -ErrorAction Stop - } - catch { - $importAttempts++ - if ($importAttempts -ge 6) { - Write-Host "Unable to import Posh-ACME after multiple attempts." -ForegroundColor Red - Show-Failure -ErrorRecord $_ - } - Write-Host "Waiting for Posh-ACME module to become available..." -ForegroundColor Cyan - Start-Sleep -Seconds 5 - } -} while (-not (Get-Module -Name Posh-ACME)) +# Try to import the module (force) and wait until available +Import-Module -Name Posh-ACME -Force -ErrorAction Stop -Write-Host "Posh-ACME module loaded." -ForegroundColor Green +$maxWaitSec = 30 +$waited = 0 +Do { + $PoshACME = Get-Module -Name Posh-ACME -ListAvailable + if (-not $PoshACME) { + Write-Host "Waiting for Posh-ACME Module to load..." -ForegroundColor Cyan + Start-Sleep -Seconds 2 + $waited += 2 + } else { + break + } +} +While ($waited -lt $maxWaitSec) + +if (-not $PoshACME) { + Write-Host "Posh-ACME failed to load within $maxWaitSec seconds." -ForegroundColor Red + exit 1 +} # ---------------------------- # vCenter API Session (Option A: POST with NO body) # ---------------------------- $loginUri = "https://$vCenterURL/rest/com/vmware/cis/session" -Write-Host "Connecting to vCenter at $vCenterURL ..." -ForegroundColor Cyan -$sessionResponse = Invoke-SafeRestMethod -Uri $loginUri -Method Post -Headers @{} -if (-not $sessionResponse) { - Write-Error "Unable to get Session Token, Terminating Script" +try { + $session = Invoke-SafeRestMethod -Uri $loginUri -Method Post -Headers @{ } # <-- no body (Option A) +} +catch { + # Invoke-SafeRestMethod will call Show-Failure and exit on error exit 1 } -$sessionToken = $sessionResponse.value +# Extract session token +$sessionToken = $null +if ($session -and $session.value) { + $sessionToken = $session.value +} + if (-not $sessionToken) { - Write-Error "Unable to get Session Token value, Terminating Script" + Write-Error "Unable to get Session Token, Terminating Script" exit 1 } Write-Host "Connected to vCenter API. Session established." -ForegroundColor Green @@ -202,18 +210,20 @@ Write-Host "Connected to vCenter API. Session established." -ForegroundColor Gre # Example: Retrieve VMs # ---------------------------- $headers = @{ 'vmware-api-session-id' = $sessionToken } -$vmList = Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/vm" -Headers $headers +$vmList = Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/vm" -Method Get -Headers $headers +Write-Host "Retrieved VM list from vCenter:" -ForegroundColor Cyan if ($vmList -and $vmList.value) { - Write-Host "Retrieved VM list from vCenter:" -ForegroundColor Cyan $vmList.value | ForEach-Object { Write-Host " - $($_.name)" } -} else { - Write-Host "No VMs returned or unable to retrieve VM list." -ForegroundColor Yellow +} +else { + Write-Host "No VMs returned (empty result)" -ForegroundColor Yellow } # ---------------------------- # PowerDNS Integration (via Posh-ACME plugin args) # ---------------------------- -Write-Host "Configuring PowerDNS plugin args for Posh-ACME" -ForegroundColor Green +Write-Host "Configuring PowerDNS with Posh-ACME" -ForegroundColor Green +# Ensure plugin args are plain strings where required $pArgs = @{ PowerDNSApiHost = $WDNSHOST PowerDNSApiKey = $PDNSAPI @@ -226,91 +236,80 @@ $pArgs = @{ # Example ACME order with DNS plugin # ---------------------------- $certName = "vcenter-cert" -Write-Host "Requesting certificate for $CommonName using PowerDNS plugin..." -ForegroundColor Cyan -# Wrap in try/catch to present friendly errors try { - New-PACertificate -Domain $CommonName -DnsPlugin PowerDNS -PluginArgs $pArgs -Contact $EmailContact -AcceptTOS -Verbose -Force - Write-Host "ACME certificate request completed (or is present)." -ForegroundColor Green + Write-Host "Requesting certificate for $CommonName via Posh-ACME (PowerDNS plugin)" -ForegroundColor Cyan + # This will create the order, perform DNS challenge via plugin args, and fetch certs + New-PACertificate -Domain $CommonName -DnsPlugin PowerDNS -PluginArgs $pArgs -Contact $EmailContact -AcceptTOS -Verbose } catch { Show-Failure -ErrorRecord $_ + exit 1 } # ---------------------------- -# Collect certificate paths from current Posh-ACME account +# Push certificate back to vCenter # ---------------------------- try { - $paAccount = Get-PAAccount - if (-not $paAccount) { - throw "Get-PAAccount returned no account information." - } - + $paAccount = Get-PAAccount -ErrorAction Stop $certFolder = $paAccount.CertFolder $certPath = Join-Path -Path $certFolder -ChildPath "$certName\cert.pem" $keyPath = Join-Path -Path $certFolder -ChildPath "$certName\privkey.pem" $chainPath = Join-Path -Path $certFolder -ChildPath "$certName\chain.pem" - foreach ($f in @($certPath, $keyPath, $chainPath)) { - if (-not (Test-Path $f)) { - throw "Required certificate file not found: $f" + foreach ($p in @($certPath, $keyPath, $chainPath)) { + if (-not (Test-Path -Path $p)) { + Write-Host "Expected certificate file not found: $p" -ForegroundColor Red + throw "Certificate file missing: $p" } } -} -catch { - Show-Failure -ErrorRecord $_ -} - -# ---------------------------- -# Push certificate back to vCenter (REST API expects JSON) -# ---------------------------- -Write-Host "Uploading certificate to vCenter..." -ForegroundColor Cyan -try { - $uploadUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls" - $headers = @{ 'vmware-api-session-id' = $sessionToken } $body = @{ - cert = (Get-Content -Path $certPath -Raw) - key = (Get-Content -Path $keyPath -Raw) + cert = (Get-Content -Path $certPath -Raw) + key = (Get-Content -Path $keyPath -Raw) chain = (Get-Content -Path $chainPath -Raw) } + $uploadUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls" + $headers = @{ 'vmware-api-session-id' = $sessionToken } + Invoke-SafeRestMethod -Uri $uploadUri -Method Post -Headers $headers -Body $body -AsJson Write-Host "New TLS certificate uploaded to vCenter" -ForegroundColor Green } catch { Show-Failure -ErrorRecord $_ + exit 1 } # ---------------------------- # Apply certificate to vCenter # ---------------------------- try { - Write-Host "Applying new TLS certificate to vCenter..." -ForegroundColor Cyan $applyUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls?action=apply" $headers = @{ 'vmware-api-session-id' = $sessionToken } Invoke-SafeRestMethod -Uri $applyUri -Method Post -Headers $headers - Write-Host "New TLS certificate applied to vCenter (action requested)." -ForegroundColor Green + Write-Host "New TLS certificate applied to vCenter" -ForegroundColor Green } catch { Show-Failure -ErrorRecord $_ + exit 1 } # ---------------------------- # Restart vCenter Services (optional) # ---------------------------- try { - Write-Host "Restarting vCenter service (vpxd)..." -ForegroundColor Yellow $restartUri = "https://$vCenterURL/rest/appliance/system/services/vpxd?action=restart" $headers = @{ 'vmware-api-session-id' = $sessionToken } Invoke-SafeRestMethod -Uri $restartUri -Method Post -Headers $headers - Write-Host "vCenter service restart initiated (vpxd)." -ForegroundColor Yellow + Write-Host "vCenter service restart initiated (vpxd)" -ForegroundColor Yellow Write-Host "Note: UI/API may briefly be unavailable while services restart." -ForegroundColor Yellow } catch { Show-Failure -ErrorRecord $_ + exit 1 } Write-Host "Script completed." -ForegroundColor Green