forked from mtusi2026/mtusi2026lab7
Защита внутренних соединений и сервисных прав
This commit is contained in:
@@ -7,7 +7,26 @@ param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
$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
|
||||
@@ -29,19 +48,43 @@ foreach($certificateFile in Get-ChildItem -LiteralPath $pki -Recurse -Filter tls
|
||||
throw "$($certificateFile.Directory.Name) certificate has no SAN"
|
||||
}
|
||||
|
||||
$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()
|
||||
$certificate.Dispose()
|
||||
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' }
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
|
||||
# Expected denials write to stderr; keep them from becoming terminating errors
|
||||
# under $ErrorActionPreference = 'Stop'.
|
||||
function Invoke-InContainer {
|
||||
param([string]$Service, [string]$Script)
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$output = @($Script | & docker compose --env-file $EnvFile exec -T $Service sh -s 2>&1) -join "`n"
|
||||
$exitCode = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
[pscustomobject]@{ ExitCode = $exitCode; Output = $output }
|
||||
}
|
||||
|
||||
$probe = @'
|
||||
set -eu
|
||||
ca=/run/pki/service-ca/ca.crt
|
||||
|
||||
probe_ok() {
|
||||
label=$1; target=$2; name=$3; shift 3
|
||||
if ! openssl s_client -brief -verify_return_error -verify_hostname "$name" \
|
||||
-connect "$target" -servername "$name" -CAfile "$ca" "$@" \
|
||||
</dev/null >/tmp/tls-probe.log 2>&1; then
|
||||
echo "FAIL: $label did not pass CA/hostname verification" >&2
|
||||
sed -n '1,12p' /tmp/tls-probe.log >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
probe_rejected() {
|
||||
label=$1; target=$2; name=$3
|
||||
set +e
|
||||
printf '\n' | openssl s_client -tls1_2 -brief -verify_return_error -verify_hostname "$name" \
|
||||
-connect "$target" -servername "$name" -CAfile "$ca" \
|
||||
>/tmp/tls-probe.log 2>&1
|
||||
status=$?
|
||||
set -e
|
||||
if [ "$status" -eq 0 ] || ! grep -Eq 'certificate required|handshake failure|certificate unknown|bad certificate' /tmp/tls-probe.log; then
|
||||
echo "FAIL: $label accepted a connection without its required client certificate" >&2
|
||||
sed -n '1,12p' /tmp/tls-probe.log >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
probe_ok postgres postgres:5432 postgres -starttls postgres
|
||||
probe_ok minio minio:9000 minio
|
||||
probe_ok openbao openbao:8200 openbao
|
||||
|
||||
probe_ok redis redis:6379 redis \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
|
||||
probe_rejected redis redis:6379 redis
|
||||
|
||||
probe_ok rabbitmq rabbitmq:5671 rabbitmq \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
|
||||
probe_rejected rabbitmq rabbitmq:5671 rabbitmq
|
||||
|
||||
probe_ok otel-ingest-api otel-collector:4318 otel-collector \
|
||||
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
|
||||
probe_ok otel-ingest-worker otel-collector:4318 otel-collector \
|
||||
-cert /run/pki/worker-client/tls.crt -key /run/pki/worker-client/tls.key
|
||||
probe_rejected otel-ingest otel-collector:4318 otel-collector
|
||||
|
||||
probe_ok otel-metrics otel-collector:8889 otel-collector \
|
||||
-cert /run/pki/prometheus-client/tls.crt -key /run/pki/prometheus-client/tls.key
|
||||
probe_rejected otel-metrics otel-collector:8889 otel-collector
|
||||
|
||||
probe_ok loki loki:3100 loki \
|
||||
-cert /run/pki/collector-client/tls.crt -key /run/pki/collector-client/tls.key
|
||||
probe_rejected loki loki:3100 loki
|
||||
|
||||
probe_ok tempo-ingest tempo:4318 tempo \
|
||||
-cert /run/pki/collector-client/tls.crt -key /run/pki/collector-client/tls.key
|
||||
probe_rejected tempo-ingest tempo:4318 tempo
|
||||
|
||||
probe_ok tempo-query tempo:3200 tempo \
|
||||
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
|
||||
probe_rejected tempo-query tempo:3200 tempo
|
||||
|
||||
probe_ok prometheus prometheus:9090 prometheus \
|
||||
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
|
||||
probe_rejected prometheus prometheus:9090 prometheus
|
||||
|
||||
echo 'PASS: DB, S3, broker, Redis, Collector, telemetry backends and OpenBao verify server CA/hostname; all declared mTLS endpoints reject no-cert clients.'
|
||||
'@
|
||||
|
||||
$probe | & docker compose --env-file $EnvFile run --rm -T --no-deps --entrypoint /bin/sh nginx -s
|
||||
if($LASTEXITCODE -ne 0){ throw 'Internal TLS verification failed' }
|
||||
|
||||
# Database probes use distinct runtime credentials and verify the server over TLS.
|
||||
$apiDdl = 'PGPASSWORD="$DATABASE_API_PASSWORD" PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/service-ca/ca.crt psql -h postgres -U messenger_api -d messenger -v ON_ERROR_STOP=1 -c "CREATE TABLE forbidden_api_probe(id integer)"'
|
||||
$apiDdlResult = Invoke-InContainer postgres $apiDdl
|
||||
if($apiDdlResult.ExitCode -eq 0 -or $apiDdlResult.Output -notmatch 'permission denied'){
|
||||
throw 'Database ACL failure: API role DDL was not denied with a permission error'
|
||||
}
|
||||
|
||||
$workerUsers = 'PGPASSWORD="$DATABASE_WORKER_PASSWORD" PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/service-ca/ca.crt psql -h postgres -U messenger_worker -d messenger -v ON_ERROR_STOP=1 -c "SELECT password_hash FROM users LIMIT 1"'
|
||||
$workerUsersResult = Invoke-InContainer postgres $workerUsers
|
||||
if($workerUsersResult.ExitCode -eq 0 -or $workerUsersResult.Output -notmatch 'permission denied'){
|
||||
throw 'Database ACL failure: worker password-hash read was not denied with a permission error'
|
||||
}
|
||||
|
||||
# Redis identities have disjoint command/key permissions in addition to mTLS.
|
||||
$apiOutsideKey = 'redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/api-client/tls.crt --key /run/pki/api-client/tls.key --user messenger-api --pass "$REDIS_API_PASSWORD" --no-auth-warning SET forbidden:probe value'
|
||||
$apiOutsideResult = (Invoke-InContainer redis $apiOutsideKey).Output
|
||||
if($apiOutsideResult -notmatch 'NOPERM'){ throw 'Redis ACL failure: API wrote outside messenger:*' }
|
||||
|
||||
$workerRead = 'redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/worker-client/tls.crt --key /run/pki/worker-client/tls.key --user messenger-worker --pass "$REDIS_WORKER_PASSWORD" --no-auth-warning GET messenger:user:probe'
|
||||
$workerReadResult = (Invoke-InContainer redis $workerRead).Output
|
||||
if($workerReadResult -notmatch 'NOPERM'){ throw 'Redis ACL failure: worker read an API cache key' }
|
||||
|
||||
$apiAdmin = 'redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/api-client/tls.crt --key /run/pki/api-client/tls.key --user messenger-api --pass "$REDIS_API_PASSWORD" --no-auth-warning CONFIG GET "*"'
|
||||
$apiAdminResult = (Invoke-InContainer redis $apiAdmin).Output
|
||||
if($apiAdminResult -notmatch 'NOPERM'){ throw 'Redis ACL failure: API executed an administrative command' }
|
||||
|
||||
$permissions = (& docker compose --env-file $EnvFile exec -T rabbitmq rabbitmqctl list_permissions --formatter table) -join "`n"
|
||||
if($permissions -notmatch 'messenger-api' -or $permissions -notmatch 'messenger-worker'){
|
||||
throw 'RabbitMQ ACL failure: separate application identities are missing'
|
||||
}
|
||||
if($permissions -match 'messenger-(api|worker)\s+\.\*\s+\.\*\s+\.\*'){
|
||||
throw 'RabbitMQ ACL failure: an application identity has unrestricted permissions'
|
||||
}
|
||||
|
||||
Write-Host 'PASS: PostgreSQL, Redis and RabbitMQ runtime identities are separate and forbidden operations are denied.'
|
||||
+29
-9
@@ -2,17 +2,37 @@
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
|
||||
function Invoke-Probe([string]$Target, [string]$TlsArguments) {
|
||||
$script = "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 $TlsArguments 2>&1"
|
||||
$output = (& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script 2>&1)
|
||||
return ($output -join "`n")
|
||||
$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."
|
||||
}
|
||||
|
||||
$published = (& docker compose --env-file $EnvFile port api 8443 2>$null) -join "`n"
|
||||
if (-not [string]::IsNullOrWhiteSpace($published)) {
|
||||
throw "mTLS bypass: API port is published directly at $published"
|
||||
function Invoke-Probe([string]$Target, [string]$TlsArguments) {
|
||||
$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 $TlsArguments 2>&1"
|
||||
# Rejected handshakes write to stderr; keep them from becoming terminating errors.
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$output = @(& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $probeScript 2>&1) -join "`n"
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
return $output
|
||||
}
|
||||
|
||||
# A missing published port is expected: compose returns nonzero and writes
|
||||
# "no port 8443/tcp ..." to stderr.
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$published = @(& docker compose --env-file $EnvFile port api 8443 2>&1) -join "`n"
|
||||
$portExit = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if ($portExit -eq 0 -and $published.Trim() -and $published -notmatch 'no port') {
|
||||
throw "mTLS bypass: API port is published directly at $($published.Trim())"
|
||||
}
|
||||
|
||||
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
|
||||
|
||||
@@ -2,21 +2,46 @@
|
||||
param([string]$EnvFile = '.env')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
$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-AppRoleToken([string]$Role) {
|
||||
$dir = Join-Path 'secrets\openbao' $Role
|
||||
$dir = Join-Path $projectRoot (Join-Path 'secrets\openbao' $Role)
|
||||
foreach($name in 'role-id','secret-id') {
|
||||
$path = Join-Path $dir $name
|
||||
if(-not (Test-Path -LiteralPath $path)) {
|
||||
throw "Missing $path. Run .\scripts\bootstrap-openbao.ps1 with BAO_TOKEN first."
|
||||
}
|
||||
}
|
||||
$roleId = [System.IO.File]::ReadAllText((Join-Path $dir 'role-id')).Trim()
|
||||
$secretId = [System.IO.File]::ReadAllText((Join-Path $dir 'secret-id')).Trim()
|
||||
$body = @{ role_id = $roleId; secret_id = $secretId } | ConvertTo-Json -Compress
|
||||
$token = ($body | & docker compose --env-file $EnvFile exec -T openbao bao write -field=token auth/approle/login - | Out-String).Trim()
|
||||
if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) { throw "AppRole login failed for $Role" }
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$token = ($body | & docker compose --env-file $EnvFile exec -T openbao bao write -field=token auth/approle/login - 2>&1 | Out-String).Trim()
|
||||
$loginExit = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if($loginExit -ne 0 -or [string]::IsNullOrWhiteSpace($token)) { throw "AppRole login failed for $Role" }
|
||||
return $token
|
||||
}
|
||||
|
||||
function Bao-WithToken([string]$Token,[Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) {
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$Token" openbao bao @Arguments 2>$null | Out-Null
|
||||
return $LASTEXITCODE
|
||||
# Expected denials write to stderr; do not let them become terminating errors.
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$Token" openbao bao @Arguments 2>&1 | Out-Null
|
||||
$exitCode = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
return $exitCode
|
||||
}
|
||||
|
||||
foreach($role in 'api','worker') {
|
||||
|
||||
@@ -6,7 +6,11 @@ param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Join-Path $PSScriptRoot '..')
|
||||
$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."
|
||||
}
|
||||
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
|
||||
|
||||
& "$PSScriptRoot\check-compose-hardening.ps1" -EnvFile $EnvFile
|
||||
@@ -30,8 +34,16 @@ with urllib.request.urlopen(sys.argv[1].rstrip('/') + '/health/ready', context=c
|
||||
'@
|
||||
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
|
||||
do {
|
||||
& $Python -c $probe $BaseUrl $ca 2>$null
|
||||
if($LASTEXITCODE -eq 0){ return }
|
||||
# Not ready yet is expected during recovery; do not turn it into a terminating error.
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
& $Python -c $probe $BaseUrl $ca 2>&1 | Out-Null
|
||||
$probeExit = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if($probeExit -eq 0){ return }
|
||||
Start-Sleep -Milliseconds 500
|
||||
} while((Get-Date) -lt $deadline)
|
||||
throw "HTTPS readiness did not recover within $TimeoutSeconds seconds"
|
||||
@@ -43,6 +55,13 @@ Run-Test @('tests/smoke.py','--base-url',$BaseUrl,'--ca-file',$ca)
|
||||
Run-Test @('tests/resilience.py','--mode','persistence','--action-script',(Resolve-Path 'scripts/restart.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
|
||||
Run-Test @('tests/resilience.py','--mode','failover','--action-script',(Resolve-Path 'scripts/stop-one.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
|
||||
|
||||
& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api
|
||||
if($LASTEXITCODE -ne 0){ throw 'Failed to restore the stopped API replica' }
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api 2>&1 | Out-Null
|
||||
$restoreExit = $LASTEXITCODE
|
||||
} finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
if($restoreExit -ne 0){ throw 'Failed to restore the stopped API replica' }
|
||||
Write-Host 'PASS: HTTPS smoke, persistence restart and one-replica failure completed with CA and hostname verification enabled.'
|
||||
|
||||
Reference in New Issue
Block a user