310 lines
10 KiB
PowerShell
310 lines
10 KiB
PowerShell
#!/usr/bin/env pwsh
|
|
# -----------------------------------------------------------------------------------
|
|
# vCenter + Posh-ACME SSL Automation Script
|
|
# Fully idempotent, rate-limit safe, fingerprint matching, full logging
|
|
# Compatible with: Posh-ACME 4.30.0
|
|
# -----------------------------------------------------------------------------------
|
|
|
|
. /opt/idssys/nodemgmt/conf/powerwall/settings.ps1
|
|
|
|
# ----------------------------
|
|
# LOGGING
|
|
# ----------------------------
|
|
$LogFile = "/opt/idssys/nodemgmt/logs/vc-ssl.log"
|
|
$logDir = Split-Path -Path $LogFile -Parent
|
|
if (-not (Test-Path $logDir)) {
|
|
New-Item -Path $logDir -ItemType Directory -Force | Out-Null
|
|
}
|
|
|
|
function Write-Log {
|
|
param([string]$Level,[string]$Message,[string]$Color="White")
|
|
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
|
$line = "[{0}] {1}: {2}" -f $ts,$Level.ToUpper(),$Message
|
|
Write-Host $line -ForegroundColor $Color
|
|
Add-Content -Path $LogFile -Value $line
|
|
}
|
|
|
|
function Show-Banner {
|
|
param([string]$Text,[string]$Type="INFO")
|
|
switch ($Type.ToUpper()) {
|
|
"SUCCESS" { $color="Green"; $level="SUCCESS" }
|
|
"ERROR" { $color="Red"; $level="ERROR" }
|
|
"WARN" { $color="Yellow"; $level="WARN" }
|
|
default { $color="Cyan"; $level="INFO" }
|
|
}
|
|
$line = "=" * [math]::Max($Text.Length,40)
|
|
Write-Host $line -ForegroundColor $color
|
|
Write-Host "${level}: $Text" -ForegroundColor $color
|
|
Write-Host $line -ForegroundColor $color
|
|
Add-Content -Path $LogFile -Value ("[{0}] {1}: {2}" -f (Get-Date),$level,$Text)
|
|
}
|
|
|
|
# ----------------------------
|
|
# ERROR HANDLING
|
|
# ----------------------------
|
|
$global:helpme = $null
|
|
function Show-Failure {
|
|
param([System.Management.Automation.ErrorRecord]$ErrorRecord)
|
|
$global:helpme = $ErrorRecord.Exception.Message
|
|
Show-Banner -Text $ErrorRecord.Exception.Message -Type "ERROR"
|
|
Write-Log -Level "ERROR" -Message $ErrorRecord | Out-Null
|
|
exit 1
|
|
}
|
|
|
|
# ----------------------------
|
|
# SHA-256 CERT FINGERPRINT
|
|
# ----------------------------
|
|
function Get-CertFingerprintFromPem {
|
|
param([string]$PemString)
|
|
|
|
try {
|
|
$pemBody = $PemString -replace "`r","" -split "`n" |
|
|
Where-Object {$_ -notmatch "^-----"} |
|
|
Where-Object {$_ -ne ""}
|
|
$pemBody = ($pemBody -join "")
|
|
$bytes = [Convert]::FromBase64String($pemBody)
|
|
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes)
|
|
$sha256 = [System.Security.Cryptography.SHA256]::Create()
|
|
$hash = $sha256.ComputeHash($cert.RawData)
|
|
return ($hash | ForEach-Object { $_.ToString("X2") }) -join ""
|
|
} catch {
|
|
Write-Log -Level "WARN" -Message "Fingerprint calc error: $($_.Exception.Message)" -Color Yellow
|
|
return $null
|
|
}
|
|
}
|
|
|
|
# ----------------------------
|
|
# LOAD POWERCLI
|
|
# ----------------------------
|
|
if (-not (Get-Module -ListAvailable VMware.PowerCLI)) {
|
|
Install-Module VMware.PowerCLI -Force -Scope AllUsers
|
|
}
|
|
Import-Module VMware.PowerCLI -ErrorAction Stop
|
|
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null
|
|
|
|
# ----------------------------
|
|
# CONNECT TO VCENTER
|
|
# ----------------------------
|
|
try {
|
|
Write-Log -Level "INFO" -Message "Connecting to vCenter $VCENTERHOST..." -Color Cyan
|
|
$vCenterConn = Connect-VIServer -Server $VCENTERHOST -User $VCENTERUSER -Password $VCENTERPASS -Force
|
|
Show-Banner -Text "Connected to vCenter." -Type SUCCESS
|
|
} catch { Show-Failure $_ }
|
|
|
|
# ----------------------------
|
|
# LOAD POSH-ACME
|
|
# ----------------------------
|
|
if (-not (Get-Module -ListAvailable Posh-ACME)) {
|
|
Install-Module Posh-ACME -Force -Scope AllUsers
|
|
}
|
|
Import-Module Posh-ACME -ErrorAction Stop
|
|
|
|
# ----------------------------
|
|
# ACME CERTIFICATE LOGIC (Posh-ACME 4.30)
|
|
# ----------------------------
|
|
$certSuccess = $false
|
|
$certPath = $keyPath = $chainPath = $null
|
|
|
|
# Log all certs first
|
|
$allPACerts = Get-PACertificate -ErrorAction SilentlyContinue
|
|
if ($allPACerts) {
|
|
Write-Log INFO "Found $($allPACerts.Count) Posh-ACME certs." Gray
|
|
foreach ($c in $allPACerts) {
|
|
Write-Log INFO (" Cert: MainDomain={0} SANs={1} Exp={2}" -f $c.MainDomain, ($c.AllSANs -join ","), $c.NotAfter) Gray
|
|
}
|
|
} else {
|
|
Write-Log INFO "No Posh-ACME certs found." Yellow
|
|
}
|
|
|
|
# Find cert matching VCENTERHOST
|
|
$existingPACert = $allPACerts |
|
|
Where-Object {$_.MainDomain -eq $VCENTERHOST -or ($_.AllSANs -contains $VCENTERHOST)} |
|
|
Sort-Object NotAfter -Descending |
|
|
Select-Object -First 1
|
|
|
|
$renewCert = $true
|
|
$skipReason = ""
|
|
|
|
# RULE 1: Existing cert valid >30 days → skip
|
|
if ($existingPACert) {
|
|
$daysLeft = ($existingPACert.NotAfter - (Get-Date)).TotalDays
|
|
Write-Log INFO "Existing cert expires $($existingPACert.NotAfter) (~$([math]::Round($daysLeft)) days)." Gray
|
|
if ($daysLeft -gt 30) {
|
|
$renewCert = $false
|
|
$skipReason = "Existing certificate still valid >30 days."
|
|
}
|
|
}
|
|
|
|
# RULE 2: LE rate-limit safety (168h)
|
|
if ($renewCert -and $existingPACert) {
|
|
$hoursSinceIssued = ((Get-Date) - $existingPACert.Created).TotalHours
|
|
if ($hoursSinceIssued -lt 168) {
|
|
$renewCert = $false
|
|
$skipReason = "LE rate-limit safety: last cert was $([math]::Round($hoursSinceIssued)) hours ago."
|
|
}
|
|
}
|
|
|
|
# If skipping ACME issuance
|
|
if (-not $renewCert -and $existingPACert) {
|
|
Write-Log INFO "Skipping new ACME issuance: $skipReason" Yellow
|
|
$certPath = $existingPACert.CertificatePath
|
|
$keyPath = $existingPACert.PrivateKeyPath
|
|
$chainPath = $existingPACert.ChainPath
|
|
$certSuccess = $true
|
|
}
|
|
else {
|
|
# NEED NEW CERTIFICATE
|
|
Write-Log INFO "Requesting new ACME certificate..." Cyan
|
|
|
|
$securePDNSAPI = if ($PDNSAPI -is [string]) {
|
|
ConvertTo-SecureString $PDNSAPI -AsPlainText -Force
|
|
} else { $PDNSAPI }
|
|
|
|
$pArgs = @{
|
|
PowerDNSApiHost = $WDNSHOST
|
|
PowerDNSApiKey = $securePDNSAPI
|
|
PowerDNSUseTLS = $true
|
|
PowerDNSPort = 443
|
|
PowerDNSServerName = 'localhost'
|
|
}
|
|
|
|
try {
|
|
New-PACertificate -Domain $VCENTERHOST -DnsPlugin PowerDNS -PluginArgs $pArgs `
|
|
-Contact $ACMEEMAIL -AcceptTOS -DnsSleep 15 -Force -Verbose
|
|
|
|
$newCert = Get-PACertificate |
|
|
Where-Object {$_.MainDomain -eq $VCENTERHOST -or ($_.AllSANs -contains $VCENTERHOST)} |
|
|
Sort-Object NotAfter -Descending |
|
|
Select-Object -First 1
|
|
|
|
if ($newCert) {
|
|
$certPath = $newCert.CertificatePath
|
|
$keyPath = $newCert.PrivateKeyPath
|
|
$chainPath = $newCert.ChainPath
|
|
$certSuccess = $true
|
|
Show-Banner "New ACME certificate created." SUCCESS
|
|
} else {
|
|
Write-Log ERROR "ACME succeeded but no certificate found." Red
|
|
$certSuccess = $false
|
|
}
|
|
}
|
|
catch {
|
|
$msg = $_.Exception.Message
|
|
Write-Log ERROR "ACME request failed: $msg" Red
|
|
$global:helpme = $msg
|
|
|
|
if ($msg -like "*too many certificates*") {
|
|
Show-Banner "Rate-limit hit. Trying fallback..." WARN
|
|
|
|
if ($existingPACert) {
|
|
$certPath = $existingPACert.CertificatePath
|
|
$keyPath = $existingPACert.PrivateKeyPath
|
|
$chainPath = $existingPACert.ChainPath
|
|
$certSuccess = $true
|
|
}
|
|
else {
|
|
Show-Banner "No fallback cert exists. Aborting." ERROR
|
|
exit 1
|
|
}
|
|
}
|
|
else { exit 1 }
|
|
}
|
|
}
|
|
|
|
# Validate final cert files
|
|
foreach ($f in @($certPath,$keyPath,$chainPath)) {
|
|
if (-not (Test-Path $f)) {
|
|
Write-Log ERROR "Missing certificate file: $f" Red
|
|
exit 1
|
|
}
|
|
}
|
|
|
|
# ----------------------------
|
|
# CHECK VCENTER CERT & FINGERPRINT MATCH
|
|
# ----------------------------
|
|
$sessionHeaders = @{
|
|
'vmware-api-session-id' = $vCenterConn.ExtensionData.Content.SessionManager.SessionId
|
|
}
|
|
|
|
$vcenterCertUri = "https://$VCENTERHOST/rest/vcenter/certificate-management/vcenter/tls"
|
|
$updateNeeded = $true
|
|
|
|
try {
|
|
$vcResp = Invoke-RestMethod -Uri $vcenterCertUri -Method Get -Headers $sessionHeaders -SkipCertificateCheck
|
|
$currentPem = $vcResp.value.cert
|
|
|
|
$currentFp = Get-CertFingerprintFromPem -PemString $currentPem
|
|
$newPem = Get-Content -Raw $certPath
|
|
$newFp = Get-CertFingerprintFromPem -PemString $newPem
|
|
|
|
if ($currentFp -and $newFp -and ($currentFp -eq $newFp)) {
|
|
Show-Banner "vCenter certificate already up-to-date." SUCCESS
|
|
$updateNeeded = $false
|
|
} else {
|
|
Write-Log INFO "Certificate fingerprints differ. Update required." Yellow
|
|
}
|
|
}
|
|
catch {
|
|
Write-Log WARN "Cannot read vCenter cert, assuming update needed." Yellow
|
|
$updateNeeded = $true
|
|
}
|
|
|
|
# ----------------------------
|
|
# UPLOAD + APPLY NEW CERT
|
|
# ----------------------------
|
|
$restartNeeded = $false
|
|
|
|
if ($updateNeeded) {
|
|
try {
|
|
$body = @{
|
|
cert = Get-Content -Raw $certPath
|
|
key = Get-Content -Raw $keyPath
|
|
chain = Get-Content -Raw $chainPath
|
|
}
|
|
|
|
Write-Log INFO "Uploading new TLS cert to vCenter..." Cyan
|
|
Invoke-RestMethod -Uri $vcenterCertUri -Method Post `
|
|
-Headers $sessionHeaders -ContentType "application/json" `
|
|
-Body ($body | ConvertTo-Json -Compress) -SkipCertificateCheck
|
|
|
|
Write-Log INFO "Applying new TLS cert..." Cyan
|
|
Invoke-RestMethod -Uri "$vcenterCertUri?action=apply" `
|
|
-Method Post -Headers $sessionHeaders -SkipCertificateCheck
|
|
|
|
Show-Banner "Certificate applied to vCenter." SUCCESS
|
|
$restartNeeded = $true
|
|
}
|
|
catch {
|
|
Show-Banner "Failed to upload/apply certificate: $($_.Exception.Message)" ERROR
|
|
exit 1
|
|
}
|
|
}
|
|
else {
|
|
Write-Log INFO "Skipping cert upload/apply." Green
|
|
}
|
|
|
|
# ----------------------------
|
|
# RESTART VPXD IF NEEDED
|
|
# ----------------------------
|
|
if ($restartNeeded) {
|
|
$maxRetries = 20
|
|
for ($i=1; $i -le $maxRetries; $i++) {
|
|
try {
|
|
Invoke-RestMethod -Uri "https://$VCENTERHOST/rest/appliance/health/system" `
|
|
-Method Get -SkipCertificateCheck -ErrorAction Stop
|
|
|
|
Invoke-RestMethod -Uri "https://$VCENTERHOST/rest/appliance/system/services/vpxd?action=restart" `
|
|
-Method Post -SkipCertificateCheck -ErrorAction Stop
|
|
|
|
Show-Banner "vpxd restarted successfully." SUCCESS
|
|
break
|
|
}
|
|
catch {
|
|
Write-Log WARN "vpxd REST not ready, retry $i/$maxRetries..." Yellow
|
|
Start-Sleep -Seconds 15
|
|
}
|
|
}
|
|
}
|
|
|
|
Show-Banner "Script complete. Log: $LogFile" INFO
|