Ротация secret и leaf certificate, отзыв identity и границы OpenBao

This commit is contained in:
EgorAnti
2026-11-27 12:57:33 +03:00
parent 0fa4b66df6
commit dd3427aa4c
14 changed files with 614 additions and 11 deletions
+132
View File
@@ -0,0 +1,132 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[int]$Port = 3000
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
$envPath = Join-Path $projectRoot $EnvFile
$caCertificate = Join-Path $projectRoot 'secrets\pki\service-ca\ca.crt'
if (-not (Test-Path -LiteralPath $envPath)) { throw "Missing env file: $EnvFile" }
if (-not (Test-Path -LiteralPath $caCertificate)) { throw "Missing service CA: $caCertificate" }
function Get-EnvValue([string]$Name) {
foreach ($line in [System.IO.File]::ReadAllLines($envPath)) {
if ($line -match "^\s*$([regex]::Escape($Name))=(.*)$") {
return $Matches[1].Trim().Trim('"')
}
}
return $null
}
function Set-EnvValue([string]$Name, [string]$Value) {
$lines = [System.IO.File]::ReadAllLines($envPath)
$updated = $false
for ($index = 0; $index -lt $lines.Count; $index++) {
if ($lines[$index] -match "^\s*$([regex]::Escape($Name))=") {
$lines[$index] = "$Name=$Value"
$updated = $true
break
}
}
if (-not $updated) { throw "$Name is missing from $EnvFile" }
[System.IO.File]::WriteAllLines($envPath, $lines, [System.Text.UTF8Encoding]::new($false))
}
function Invoke-Grafana([string]$User, [string]$Password, [string]$Path,
[string]$Method = 'GET', [string]$Body = '') {
$arguments = @('-sS','-o','NUL','-w','%{http_code}','--cacert',$caCertificate,
'--ssl-no-revoke','--connect-timeout','5','--max-time','15','-u',"$User`:$Password")
if ($Method -ne 'GET') { $arguments += @('-X',$Method) }
$bodyFile = $null
if ($Body) {
# curl.exe on Windows must receive JSON from a file: inline arguments
# are quote-stripped, and PowerShell's default UTF-8 writer adds a BOM.
$bodyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("grafana-rotation-" + [guid]::NewGuid().ToString('N') + '.json')
[System.IO.File]::WriteAllText($bodyFile, $Body, [System.Text.UTF8Encoding]::new($false))
$arguments += @('-H','Content-Type: application/json','--data-binary',"@$bodyFile")
}
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$code = (& curl.exe @arguments "https://localhost:$Port$Path" 2>$null | Out-String).Trim()
} finally {
$ErrorActionPreference = $previous
if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -Force -ErrorAction SilentlyContinue }
}
return $code
}
function Invoke-ComposeQuiet([string[]]$Arguments) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& docker compose @Arguments 2>&1 | Out-Null
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if ($code -ne 0) { throw "docker compose failed with exit code $code" }
}
function New-RotationPassword {
$bytes = New-Object byte[] 24
$generator = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try { $generator.GetBytes($bytes) } finally { $generator.Dispose() }
return [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=')
}
$user = Get-EnvValue 'GRAFANA_ADMIN_USER'
if ([string]::IsNullOrWhiteSpace($user)) { $user = 'admin' }
$oldPassword = Get-EnvValue 'GRAFANA_ADMIN_PASSWORD'
if ([string]::IsNullOrWhiteSpace($oldPassword)) { throw 'GRAFANA_ADMIN_PASSWORD is missing from the env file' }
$newPassword = New-RotationPassword
$imageBefore = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim()
if ((Invoke-Grafana $user $oldPassword '/api/user') -ne '200') {
throw 'Current Grafana admin credentials were not accepted before rotation'
}
$body = @{
oldPassword = $oldPassword
newPassword = $newPassword
confirmNew = $newPassword
} | ConvertTo-Json -Compress
$rotationStatus = Invoke-Grafana $user $oldPassword '/api/user/password' 'PUT' $body
if ($rotationStatus -ne '200' -and $rotationStatus -ne '204') {
throw "Grafana password API returned an unexpected status: $rotationStatus"
}
$envBackup = [System.IO.File]::ReadAllBytes($envPath)
try {
Set-EnvValue 'GRAFANA_ADMIN_PASSWORD' $newPassword
Invoke-ComposeQuiet @('--env-file',$EnvFile,'up','-d','--no-deps','--force-recreate','grafana')
$ready = $false
for ($attempt = 0; $attempt -lt 30; $attempt++) {
if ((Invoke-Grafana $user $newPassword '/api/user') -eq '200') { $ready = $true; break }
Start-Sleep -Seconds 2
}
if (-not $ready) { throw 'Rotated Grafana credentials were not accepted after container recreate' }
if ((Invoke-Grafana $user $oldPassword '/api/user') -eq '200') {
throw 'Old Grafana password is still accepted after rotation'
}
} catch {
[System.IO.File]::WriteAllBytes($envPath, $envBackup)
$rollbackBody = @{
oldPassword = $newPassword
newPassword = $oldPassword
confirmNew = $oldPassword
} | ConvertTo-Json -Compress
Invoke-Grafana $user $newPassword '/api/user/password' 'PUT' $rollbackBody | Out-Null
throw
}
$imageAfter = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim()
if ($imageBefore -ne $imageAfter) { throw 'Grafana image changed during rotation' }
Write-Host 'PASS: Grafana admin password rotated through the API and .env without rebuilding images.'
Write-Host "old_password_accepted_after=false"
Write-Host "new_password_accepted_after=true"
Write-Host "grafana_image=$imageAfter"
+136
View File
@@ -0,0 +1,136 @@
[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
}
@@ -0,0 +1,80 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$ApplicationImage = 'hla-lab7-app:local',
[int]$Port = 8443
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
$publicCa = Join-Path $projectRoot 'secrets\pki\public-ca\ca.crt'
if (-not (Test-Path -LiteralPath $publicCa)) { throw "Missing public CA: $publicCa" }
function Invoke-Quiet([scriptblock]$Command) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = & $Command 2>&1 | Out-String
$code = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
return [pscustomobject]@{ Code = $code; Output = $output }
}
foreach ($name in 'agent-api.hcl','agent-worker.hcl') {
$config = [System.IO.File]::ReadAllText((Join-Path $projectRoot "infra\openbao\$name"))
if ($config -notmatch 'static_secret_render_interval\s*=\s*"5m"') { throw "$name does not renew rendered secrets every 5 minutes" }
if ($config -notmatch 'exit_on_retry_failure\s*=\s*false') { throw "$name exits when OpenBao retries fail" }
}
$serverConfig = [System.IO.File]::ReadAllText((Join-Path $projectRoot 'infra\openbao\openbao.hcl'))
if ($serverConfig -notmatch 'default_lease_ttl\s*=\s*"15m"' -or
$serverConfig -notmatch 'max_lease_ttl\s*=\s*"1h"') {
throw 'OpenBao lease TTLs are not bounded'
}
$imageConfig = (Invoke-Quiet { docker image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' $ApplicationImage }).Output
if ($imageConfig -match '(?i)BAO_TOKEN|UNSEAL|ROOT_TOKEN|SECRET_ID') {
throw 'Application image environment contains an operator credential name'
}
Invoke-Quiet { docker run --rm --entrypoint sh $ApplicationImage -c 'test ! -e /app/.env && test ! -e /app/secrets && test ! -e /app/runtime.env && ! find /app -type f \( -name "*.key" -o -name "*.p12" -o -name "*.jks" \) -print -quit | grep -q .' } | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Application image contains forbidden secret artifacts' }
# The operator seals OpenBao (or stops the server) with the unseal shares held
# offline. This script verifies the resulting boundary; it never handles the
# shares itself and never tries to unseal.
$statusDuringSeal = (Invoke-Quiet { docker compose --env-file $EnvFile exec -T openbao bao status }).Output
if ($statusDuringSeal -notmatch 'Sealed\s+true') {
throw 'Run this check while OpenBao is sealed so the boundary is actually exercised'
}
foreach ($service in 'openbao-agent-api','openbao-agent-worker') {
$running = (Invoke-Quiet { docker inspect --format '{{.State.Running}}' "hla-lab7-$($service)-1" }).Output.Trim()
if ($running -ne 'true') { throw "$service stopped while OpenBao was unavailable" }
}
$agentId = (Invoke-Quiet { docker compose --env-file $EnvFile ps -q openbao-agent-api }).Output.Trim()
$keys = (Invoke-Quiet { docker exec $agentId sh -c 'test -s /run/rendered/runtime.env && cut -d= -f1 /run/rendered/runtime.env | sort | tr "\n" ","' }).Output.Trim()
if ($keys -notmatch 'DATABASE_PASSWORD' -or $keys -notmatch 'REDIS_PASSWORD') {
throw 'Cached rendered runtime secrets are unavailable during the seal test'
}
$health = Invoke-Quiet { curl.exe -sS -o NUL -w '%{http_code}' --cacert $publicCa --ssl-no-revoke --connect-timeout 5 --max-time 10 "https://localhost:$Port/health/ready" }
if ($health.Output.Trim() -ne '200') { throw 'Application readiness failed while OpenBao was unavailable' }
$watch = [Diagnostics.Stopwatch]::StartNew()
$fresh = Invoke-Quiet {
docker run --rm --entrypoint messenger-entrypoint `
-e OPENBAO_RENDERED_ENV=/run/missing/runtime.env `
-e OPENBAO_STARTUP_TIMEOUT_SECONDS=2 $ApplicationImage
}
$watch.Stop()
if ($fresh.Code -eq 0 -or $fresh.Output -notmatch 'did not render runtime credentials') {
throw 'Fresh startup did not fail closed on a missing rendered secret file'
}
if ($watch.Elapsed.TotalSeconds -gt 10) { throw 'Fresh startup exceeded the bounded fail-closed deadline' }
$elapsed = [math]::Round($watch.Elapsed.TotalSeconds, 1)
Write-Host 'PASS: OpenBao seal/unavailability does not stop agents or running API; cached runtime secrets keep readiness at 200.'
Write-Host "PASS: fresh startup with no rendered env failed closed in ${elapsed}s (configured deadline 2s)."
Write-Host 'PASS: AppRole token TTL is 15m/1h, templates renew every 5m, and no permanent operator secret is embedded in the image.'
+56
View File
@@ -0,0 +1,56 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$OldCertificate = 'secrets/pki/revoked/lb/tls.crt',
[string]$OldKey = 'secrets/pki/revoked/lb/tls.key',
[string]$NewCertificate = 'secrets/pki/lb/tls.crt',
[string]$NewKey = 'secrets/pki/lb/tls.key'
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
foreach ($path in @($OldCertificate, $OldKey, $NewCertificate, $NewKey)) {
if (-not (Test-Path -LiteralPath $path)) { throw "Missing certificate material: $path" }
}
function Convert-ToContainerPath([string]$Path) {
if ($Path -match '^(secrets[\\/])pki[\\/](.+)$') { return '/run/pki/' + $Matches[2].Replace('\','/') }
return $Path.Replace('\','/')
}
$OldCertificate = Convert-ToContainerPath $OldCertificate
$OldKey = Convert-ToContainerPath $OldKey
$NewCertificate = Convert-ToContainerPath $NewCertificate
$NewKey = Convert-ToContainerPath $NewKey
foreach ($path in @($OldCertificate, $OldKey, $NewCertificate, $NewKey)) {
if ($path -notlike '/run/pki/*') { throw "Certificate path must be under secrets/pki: $path" }
}
function Invoke-Probe([string]$Target, [string]$Certificate, [string]$Key) {
$probeScript = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -quiet -connect ${Target}:8443 -servername api -CAfile /run/pki/service-ca/ca.crt -cert ${Certificate} -key ${Key} 2>&1"
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
return @(& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $probeScript 2>&1) -join "`n"
} finally {
$ErrorActionPreference = $previous
}
}
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
if ($replicas.Count -lt 2) { throw 'At least two running API replicas are required for rotation evidence' }
foreach ($replica in $replicas) {
$target = (& docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $replica).Trim()
if ([string]::IsNullOrWhiteSpace($target)) { throw "No internal address found for API replica $replica" }
$oldResult = Invoke-Probe $target $OldCertificate $OldKey
if ($oldResult -notmatch 'HTTP/1.1 403') {
throw "Revoked leaf was accepted by API replica $replica"
}
$newResult = Invoke-Probe $target $NewCertificate $NewKey
if ($newResult -notmatch 'HTTP/1.1 200') {
throw "Rotated leaf was rejected by API replica $replica"
}
}
Write-Host "PASS: $($replicas.Count) API replicas reject the revoked LB leaf with 403 and accept the rotated LB leaf with 200."