Files
mtusi2026lab7/scripts/rotate-pki-leaf.ps1
T

137 lines
5.6 KiB
PowerShell

[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$Leaf,
[Parameter(Mandatory=$true)][string]$CaName,
[string[]]$UriSan = @(),
[string[]]$DnsName = @(),
[string[]]$IpAddress = @(),
[switch]$ServerAuth,
[switch]$RevokeOld,
[string]$Image = 'nginx:1.27.4-bookworm'
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if (-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
}
$pki = Join-Path $projectRoot 'secrets\pki'
$leafDir = Join-Path $pki $Leaf
$caCertificate = Join-Path $pki "$CaName\ca.crt"
$caKey = Join-Path $pki "$CaName\ca.key"
foreach ($path in @($leafDir, $caCertificate, $caKey)) {
if (-not (Test-Path $path)) { throw "Missing PKI input: $path" }
}
$sanLines = @()
$index = 1
foreach ($value in $UriSan) { $sanLines += "URI.$index = $value"; $index++ }
$index = 1
foreach ($value in $DnsName) { $sanLines += "DNS.$index = $value"; $index++ }
$index = 1
foreach ($value in $IpAddress) { $sanLines += "IP.$index = $value"; $index++ }
if ($sanLines.Count -eq 0) { throw 'At least one SAN value is required for a rotated leaf.' }
$eku = if ($ServerAuth) { 'serverAuth' } else { 'clientAuth' }
$config = @"
[req]
distinguished_name = dn
prompt = no
[dn]
CN = $Leaf
[v3_leaf]
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature,keyEncipherment
extendedKeyUsage = $eku
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
subjectAltName = @san
[san]
$($sanLines -join "`n")
"@
$configDir = Join-Path ([System.IO.Path]::GetTempPath()) ("pki-rotate-" + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $configDir -Force | Out-Null
[System.IO.File]::WriteAllText((Join-Path $configDir 'leaf.cnf'), $config, [System.Text.Encoding]::ASCII)
function Invoke-Docker([string[]]$Arguments, [switch]$Capture) {
# Windows PowerShell 5 wraps native stderr as terminating errors when
# ErrorActionPreference is Stop; openssl writes progress there.
$previous = $ErrorActionPreference
try {
$ErrorActionPreference = 'Continue'
if ($Capture) {
$output = (& docker @Arguments 2>&1 | Out-String)
} else {
& docker @Arguments 2>&1 | Out-Null
$output = ''
}
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if ($code -ne 0) { throw "Docker command failed with exit code $code" }
return $output
}
function Get-CertificateFingerprint([string]$CertificatePath) {
$relative = $CertificatePath.Substring($pki.Length).TrimStart('\','/').Replace('\','/')
$output = Invoke-Docker @('run','--rm', `
"--mount=type=bind,source=$pki,target=/pki,readonly", `
'--entrypoint','sh',$Image,'-c', `
"openssl x509 -in /pki/$relative -outform DER | sha256sum | cut -d' ' -f1") -Capture
return ($output.Trim() -split "`n")[-1].Trim().ToLowerInvariant()
}
try {
$revokedDir = Join-Path $pki "revoked\$Leaf"
New-Item -ItemType Directory -Path $revokedDir -Force | Out-Null
Copy-Item (Join-Path $leafDir 'tls.crt') (Join-Path $revokedDir 'tls.crt') -Force
Copy-Item (Join-Path $leafDir 'tls.key') (Join-Path $revokedDir 'tls.key') -Force
Copy-Item (Join-Path $leafDir 'ca.crt') (Join-Path $revokedDir 'ca.crt') -Force
Invoke-Docker @('run','--rm', `
"--mount=type=bind,source=$pki,target=/pki", `
'--entrypoint','chmod',$Image,'0644', `
"/pki/revoked/$Leaf/tls.crt","/pki/revoked/$Leaf/tls.key","/pki/revoked/$Leaf/ca.crt") | Out-Null
$oldFingerprint = Get-CertificateFingerprint (Join-Path $revokedDir 'tls.crt')
$script = @"
openssl req -new -newkey rsa:3072 -nodes -keyout /pki/$Leaf/tls.key.next -out /pki/$Leaf/tls.csr -config /config/leaf.cnf &&
openssl x509 -req -in /pki/$Leaf/tls.csr -CA /pki/$CaName/ca.crt -CAkey /pki/$CaName/ca.key -CAserial /config/ca.srl -CAcreateserial -out /pki/$Leaf/tls.crt.next -days 30 -sha256 -extfile /config/leaf.cnf -extensions v3_leaf &&
chmod 0644 /pki/$Leaf/tls.key.next /pki/$Leaf/tls.crt.next &&
rm -f /pki/$Leaf/tls.csr
"@
Invoke-Docker @('run','--rm', `
"--mount=type=bind,source=$pki,target=/pki", `
"--mount=type=bind,source=$configDir,target=/config", `
'--entrypoint','sh',$Image,'-c',$script) | Out-Null
foreach ($name in 'tls.key.next', 'tls.crt.next') {
if (-not (Test-Path (Join-Path $leafDir $name))) { throw "OpenSSL did not produce $name" }
}
Move-Item -Force (Join-Path $leafDir 'tls.key.next') (Join-Path $leafDir 'tls.key')
Move-Item -Force (Join-Path $leafDir 'tls.crt.next') (Join-Path $leafDir 'tls.crt')
$newFingerprint = Get-CertificateFingerprint (Join-Path $leafDir 'tls.crt')
if ($newFingerprint -eq $oldFingerprint) { throw 'Rotation did not change the leaf certificate' }
if ($RevokeOld) {
$revocationFile = Join-Path $pki 'revoked-client-sha256.txt'
$lines = if (Test-Path $revocationFile) {
@([System.IO.File]::ReadAllLines($revocationFile))
} else { @() }
if ($lines -notcontains $oldFingerprint) {
Add-Content -Path $revocationFile -Value $oldFingerprint -Encoding ASCII
}
}
Write-Host "ROTATED $Leaf (CA $CaName) without rebuilding images."
Write-Host "old_leaf_sha256=$oldFingerprint"
Write-Host "new_leaf_sha256=$newFingerprint"
if ($RevokeOld) { Write-Host "revoked_old_leaf=$oldFingerprint" }
}
finally {
Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue
}