Files
mtusi2026lab7/scripts/check-security-lifecycle.ps1

112 lines
5.4 KiB
PowerShell

[CmdletBinding()]
param(
[string]$PkiDirectory,
[int]$MinimumRemainingDays = 7,
[int]$MaximumLeafValidityDays = 31,
[int]$MaximumSecretIdAgeHours = 24
)
$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."
}
function Get-OpenSslPath {
$command = Get-Command openssl -ErrorAction SilentlyContinue
if($command){ return $command.Source }
$git = Get-Command git -ErrorAction SilentlyContinue
if($git){
$gitRoot = Split-Path (Split-Path $git.Source -Parent) -Parent
foreach($relative in 'usr\bin\openssl.exe','mingw64\bin\openssl.exe'){
$candidate = Join-Path $gitRoot $relative
if(Test-Path -LiteralPath $candidate){ return $candidate }
}
}
return $null
}
if([string]::IsNullOrWhiteSpace($PkiDirectory)){ $PkiDirectory = 'secrets\pki' }
$pki = (Resolve-Path -LiteralPath $PkiDirectory).Path
$now = [DateTimeOffset]::UtcNow
$leafCount = 0
foreach($certificateFile in Get-ChildItem -LiteralPath $pki -Recurse -Filter tls.crt) {
$keyFile = Join-Path $certificateFile.DirectoryName 'tls.key'
$caFile = Join-Path $certificateFile.DirectoryName 'ca.crt'
if(-not (Test-Path -LiteralPath $keyFile) -or -not (Test-Path -LiteralPath $caFile)){
throw "Incomplete certificate bundle: $($certificateFile.Directory.Name)"
}
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificateFile.FullName)
if([DateTimeOffset]$certificate.NotBefore -gt $now.AddMinutes(1)){ throw "$($certificateFile.Directory.Name) certificate is not valid yet" }
if([DateTimeOffset]$certificate.NotAfter -le $now.AddDays($MinimumRemainingDays)){ throw "$($certificateFile.Directory.Name) certificate expires too soon" }
if(($certificate.NotAfter.ToUniversalTime() - $certificate.NotBefore.ToUniversalTime()).TotalDays -gt ($MaximumLeafValidityDays + 1)){
throw "$($certificateFile.Directory.Name) leaf validity exceeds the contract"
}
if(-not ($certificate.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.17' })){
throw "$($certificateFile.Directory.Name) certificate has no SAN"
}
if($PSVersionTable.PSVersion.Major -ge 6) {
$privateKey = [System.Security.Cryptography.RSA]::Create()
$publicKey = $null
try {
$privateKey.ImportFromPem([System.IO.File]::ReadAllText($keyFile))
$privatePublic = [Convert]::ToBase64String($privateKey.ExportSubjectPublicKeyInfo())
$publicKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($certificate)
$certificatePublic = [Convert]::ToBase64String($publicKey.ExportSubjectPublicKeyInfo())
if($privatePublic -ne $certificatePublic){ throw "$($certificateFile.Directory.Name) private key does not match certificate" }
} finally {
if($null -ne $publicKey){ $publicKey.Dispose() }
$privateKey.Dispose()
}
} else {
# Windows PowerShell 5.1 has no ImportFromPem; compare public keys via OpenSSL.
$openssl = Get-OpenSslPath
if($null -eq $openssl){
throw "Cannot verify key pair for $($certificateFile.Directory.Name): install PowerShell 7+ or OpenSSL."
}
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$keyPublic = ((& $openssl pkey -in $keyFile -pubout 2>&1 | Out-String).Trim()) -replace "`r",''
$keyExit = $LASTEXITCODE
$certPublic = ((& $openssl x509 -in $certificateFile.FullName -pubkey -noout 2>&1 | Out-String).Trim()) -replace "`r",''
$certExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($keyExit -ne 0 -or $certExit -ne 0){
throw "OpenSSL could not read key/certificate for $($certificateFile.Directory.Name)"
}
if($keyPublic -ne $certPublic){
throw "$($certificateFile.Directory.Name) private key does not match certificate"
}
}
$certificate.Dispose()
$leafCount++
}
if($leafCount -eq 0){ throw 'No leaf certificates found' }
$trackedPrivate = & git ls-files -- .env secrets '*.key' '*.p12' '*.pfx' '*.jks' '*.pem'
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
if($trackedPrivate){ throw 'Private material is tracked by Git' }
foreach($path in '.env','secrets/pki/openbao/tls.key'){
& git check-ignore --quiet -- $path
if($LASTEXITCODE -ne 0){ throw "$path is not ignored by Git" }
}
$operatorArtifacts = Get-ChildItem -LiteralPath secrets -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '(?i)unseal|root[-_.]?token|\.vault-token' }
if($operatorArtifacts){ throw 'Root token or unseal-named operator artifact exists inside the project secrets directory' }
foreach($role in 'api','worker'){
$secretId = Join-Path "secrets\openbao\$role" 'secret-id'
if(Test-Path -LiteralPath $secretId){
$age = $now - [DateTimeOffset](Get-Item -LiteralPath $secretId).LastWriteTimeUtc
if($age.TotalHours -ge $MaximumSecretIdAgeHours){ throw "$role AppRole SecretID reached its rotation deadline" }
}
}
Write-Host "PASS: $leafCount certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL."