Проверка изоляции контейнеров и секретов

This commit is contained in:
EgorAnti
2026-11-27 09:36:47 +03:00
parent 68f14d6563
commit 87a3f9d8e5
5 changed files with 198 additions and 0 deletions
+11
View File
@@ -111,6 +111,17 @@ docker compose --env-file .env up -d --build
read-only. Stateful entrypoints сохраняют только минимальный набор capabilities,
нужный для смены UID и подготовки named volume.
После запуска стенда отдельная runtime-проверка подтверждает фактический non-root
UID API/worker, отсутствие privileged/host network/Docker socket, реальные
лимиты и port bindings. Она также сравнивает значения secret-переменных из
локального `.env` с Git-файлами, metadata образа и последними логами, не печатая
сами значения, и проверяет обязательный redaction processor во всех telemetry
pipelines:
```powershell
.\scripts\test-container-secret-boundaries.ps1
```
Полный повторяемый сценарий после запуска и unseal стенда:
```powershell
+1
View File
@@ -23,6 +23,7 @@ TODO: схема процессов/хранилищ, источник исти
| OpenBao AppRole и policies | `scripts/test-openbao-policies.ps1` | PASS: API и worker читают только свой KV path; чужой path и запись policy отклонены | `evidence/openbao-policies.txt`, `contracts/trust-matrix.md` |
| OpenBao runtime boundaries | `scripts/test-openbao-runtime-boundaries.ps1` | PASS: server mode + persistent Raft volume; отдельные AppRole/bootstrap/rendered volumes; API/worker получают только allowlisted keys через read-only file и не имеют root token/unseal material | `evidence/openbao-runtime-boundaries.txt`, `contracts/trust-matrix.md` |
| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта |
| Runtime isolation и утечки secrets | `scripts/test-container-secret-boundaries.ps1` | PASS: API/worker фактически non-root; privileged/host network/Docker socket отсутствуют; runtime limits и только разрешённые loopback bindings подтверждены; локальные secret values не найдены в Git, image metadata/filesystem и логах; redaction включён для traces/metrics/logs | `evidence/container-secret-boundaries.txt` |
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | `evidence/security-lifecycle.txt` |
| Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | `evidence/verify-https-resilience.txt` |
| Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | `evidence/verify-https-resilience.txt` |
+2
View File
@@ -63,6 +63,8 @@
## Bootstrap и владение
- В Git находятся только открытые configs, policy templates, scripts и при необходимости public CA. Private keys/secrets создаются в `secrets/` с ограниченными ACL и исключены из build context.
- `scripts/test-container-secret-boundaries.ps1` проверяет rendered Compose и runtime: нет privileged/host network/Docker socket, API/worker имеют UID != 0, `cap_drop: ALL`, read-only rootfs и CPU/RAM/PID limits. Единственные host bindings — TLS ingress и loopback OpenBao/Grafana.
- Та же проверка без печати значений сопоставляет локальные secret values с tracked text, metadata/filesystem application image и последними container logs. Collector удаляет Authorization, bodies, query и DB parameters во всех трёх pipelines; HTTP header capture у API/worker выключен.
- Владелец root CA, OpenBao init/root token и unseal shares — оператор. Ручной unseal допустим; shares не лежат рядом со storage volume.
- API, worker, migration, Collector, Grafana datasource и operator имеют разные identities. Общий credential между ролями — дефект даже при TLS.
- OpenBao работает с persistent storage не в dev-mode. Root token не передаётся приложению. Service token ограничен named policy/TTL/max TTL.
+21
View File
@@ -0,0 +1,21 @@
Container and secret boundary verification
Date: 2026-11-27 (Europe/Moscow)
Command:
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-container-secret-boundaries.ps1
Observed:
PASS: runtime isolation, non-root app/worker, resource and port boundaries,
Git/image/log secret isolation, and telemetry redaction are enforced.
Checked 14 local secret values without printing them.
Scope:
- rendered Compose and all running project containers;
- actual UID of API and worker;
- privileged, host network, Docker socket, capabilities, read-only rootfs,
CPU, memory and PID limits;
- runtime host port bindings;
- tracked text, application image metadata/filesystem and last 2000 log lines;
- OpenTelemetry redaction in traces, metrics and logs pipelines.
No secret value, private key, root token or unseal key is included in this file.
@@ -0,0 +1,163 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$ApplicationImage = 'hla-lab7-app:local'
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
function Invoke-CheckedDocker {
param([Parameter(Mandatory=$true)][string[]]$Arguments, [string]$Failure = 'Docker command failed')
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = & docker @Arguments 2>&1
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($exitCode -ne 0){ throw "$Failure (exit $exitCode)" }
return $output
}
function Get-ComposeArguments {
param([string[]]$Tail)
return @('compose','--env-file',$EnvFile) + $Tail
}
function Get-SecretCandidates {
if(-not (Test-Path -LiteralPath $EnvFile)){ return @() }
$result = @()
foreach($line in Get-Content -LiteralPath $EnvFile) {
if($line -notmatch '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$'){ continue }
$name = $Matches[1]
$value = $Matches[2].Trim()
if($value.Length -ge 8 -and $name -match '(?i)(PASSWORD|TOKEN|SECRET|PRIVATE_KEY|UNSEAL|CREDENTIAL)') {
$result += [pscustomobject]@{ Name = $name; Value = $value }
}
}
return $result
}
$configText = Invoke-CheckedDocker (Get-ComposeArguments @('--profile','verification','config','--format','json')) 'docker compose config failed'
$config = ($configText -join "`n") | ConvertFrom-Json
$allowedPorts = @{
nginx = @{ ContainerPort = '8443/tcp'; PublishedPort = '8443' }
openbao = @{ ContainerPort = '8200/tcp'; PublishedPort = '8200' }
grafana = @{ ContainerPort = '3000/tcp'; PublishedPort = '3000' }
}
foreach($property in $config.services.PSObject.Properties) {
$name = $property.Name
$service = $property.Value
if($service.privileged -eq $true){ throw "$name is privileged" }
if($service.network_mode -eq 'host'){ throw "$name uses host networking" }
foreach($volume in @($service.volumes) | Where-Object { $null -ne $_ }) {
if("$($volume.source) $($volume.target)" -match '(?i)docker\.sock') { throw "$name mounts the Docker socket" }
}
}
foreach($serviceName in 'api','worker') {
$service = $config.services.$serviceName
if(-not ($service.cap_drop -contains 'ALL')){ throw "$serviceName does not drop all capabilities" }
if(@($service.cap_add | Where-Object { $null -ne $_ }).Count -gt 0){ throw "$serviceName adds capabilities" }
if(-not $service.cpus -or -not $service.mem_limit -or -not $service.pids_limit){ throw "$serviceName has incomplete resource limits" }
if($service.read_only -ne $true){ throw "$serviceName root filesystem is writable" }
if(-not ($service.security_opt -contains 'no-new-privileges:true')){ throw "$serviceName lacks no-new-privileges" }
}
$runningServices = @(Invoke-CheckedDocker (Get-ComposeArguments @('ps','--services','--status','running')) 'Cannot list running services')
foreach($required in 'api','worker') {
if($runningServices -notcontains $required){ throw "$required must be running for the runtime boundary check" }
$uid = ((Invoke-CheckedDocker (Get-ComposeArguments @('exec','-T',$required,'id','-u')) "Cannot read $required runtime UID") -join '').Trim()
if($uid -notmatch '^\d+$' -or [int]$uid -eq 0){ throw "$required runs as root" }
}
$containerIds = @(Invoke-CheckedDocker (Get-ComposeArguments @('ps','-q')) 'Cannot list Compose containers') | Where-Object { $_ }
if($containerIds.Count -eq 0){ throw 'No running Compose containers found' }
foreach($containerId in $containerIds) {
$inspect = ((Invoke-CheckedDocker @('inspect',$containerId) 'Container inspect failed') -join "`n") | ConvertFrom-Json
$container = $inspect[0]
$serviceName = $container.Config.Labels.'com.docker.compose.service'
if($container.HostConfig.Privileged){ throw "$serviceName runtime container is privileged" }
if($container.HostConfig.NetworkMode -eq 'host'){ throw "$serviceName runtime container uses host networking" }
if(-not $container.HostConfig.PidsLimit -or -not $container.HostConfig.Memory -or -not $container.HostConfig.NanoCpus){
throw "$serviceName runtime container is missing resource limits"
}
if($serviceName -in @('api','worker')) {
if(-not ($container.HostConfig.CapDrop -contains 'ALL')){ throw "$serviceName runtime container does not drop all capabilities" }
if(@($container.HostConfig.CapAdd | Where-Object { $null -ne $_ }).Count -gt 0){ throw "$serviceName runtime container adds capabilities" }
if(-not $container.HostConfig.ReadonlyRootfs){ throw "$serviceName runtime root filesystem is writable" }
if(-not ($container.HostConfig.SecurityOpt -contains 'no-new-privileges:true')){ throw "$serviceName runtime container lacks no-new-privileges" }
}
foreach($mount in @($container.Mounts)) {
if("$($mount.Source) $($mount.Destination)" -match '(?i)docker\.sock'){ throw "$serviceName runtime container mounts the Docker socket" }
}
foreach($portProperty in $container.NetworkSettings.Ports.PSObject.Properties) {
foreach($binding in @($portProperty.Value) | Where-Object { $null -ne $_ }) {
if(-not $allowedPorts.ContainsKey($serviceName)){ throw "$serviceName publishes unexpected port $($portProperty.Name)" }
$expected = $allowedPorts[$serviceName]
if($portProperty.Name -ne $expected.ContainerPort -or $binding.HostPort -ne $expected.PublishedPort){
throw "$serviceName publishes unexpected binding $($binding.HostPort):$($portProperty.Name)"
}
if($binding.HostIp -notin @('127.0.0.1','::1')){ throw "$serviceName is not loopback-bound" }
}
}
}
$trackedPrivate = @(& git ls-files -- .env 'secrets/*' '*.key' '*.pem' '*.p12' '*.pfx' '*.jks')
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
if($trackedPrivate.Count -gt 0){ throw 'Git tracks private material' }
$dockerIgnore = Get-Content -LiteralPath '.dockerignore' -Raw
foreach($requiredRule in '(?m)^\.env\r?$','(?m)^secrets\r?$','(?m)^\*\.key\r?$') {
if($dockerIgnore -notmatch $requiredRule){ throw ".dockerignore is missing required rule $requiredRule" }
}
$secretCandidates = @(Get-SecretCandidates)
$trackedFiles = @(& git ls-files)
if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' }
$textExtensions = @('.md','.txt','.yaml','.yml','.json','.xml','.properties','.conf','.hcl','.ps1','.sh','.java','.gradle','.example')
foreach($path in $trackedFiles) {
if(-not (Test-Path -LiteralPath $path -PathType Leaf)){ continue }
$item = Get-Item -LiteralPath $path
if($item.Length -gt 5MB -or $textExtensions -notcontains $item.Extension){ continue }
$content = [System.IO.File]::ReadAllText($item.FullName)
foreach($candidate in $secretCandidates) {
if($content.Contains($candidate.Value)){ throw "Git-tracked file contains value from $($candidate.Name)" }
}
}
$imageInspectText = Invoke-CheckedDocker @('image','inspect',$ApplicationImage) "Application image $ApplicationImage is unavailable"
$imageInspect = (($imageInspectText -join "`n") | ConvertFrom-Json)[0]
$imageMetadata = (($imageInspect.Config.Env -join "`n") + "`n" + ((Invoke-CheckedDocker @('history','--no-trunc','--format','{{.CreatedBy}}',$ApplicationImage) 'Image history failed') -join "`n"))
foreach($candidate in $secretCandidates) {
if($imageMetadata.Contains($candidate.Value)){ throw "Application image metadata contains value from $($candidate.Name)" }
}
Invoke-CheckedDocker @('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 .') 'Application image contains a forbidden secret artifact' | Out-Null
$composeLogs = (Invoke-CheckedDocker (Get-ComposeArguments @('logs','--no-color','--tail','2000')) 'Cannot read Compose logs') -join "`n"
foreach($candidate in $secretCandidates) {
if($composeLogs.Contains($candidate.Value)){ throw "Container logs contain value from $($candidate.Name)" }
}
$collector = Get-Content -LiteralPath 'infra/otel/collector.yaml' -Raw
foreach($attribute in 'http.request.header.authorization','http.request.body','http.response.body','messaging.message.body','db.statement.parameters','url.query') {
if($collector -notmatch "(?m)^\s*- key: $([regex]::Escape($attribute))\s*$"){ throw "Telemetry redaction is missing $attribute" }
}
foreach($pipeline in 'traces','metrics','logs') {
if($collector -notmatch "(?ms)^\s{4}${pipeline}:\s+.*?processors:\s*\[[^\]]*attributes/redact[^\]]*\]"){
throw "Telemetry $pipeline pipeline does not use attributes/redact"
}
}
foreach($serviceName in 'api','worker') {
$environment = $config.services.$serviceName.environment
if($environment.OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_REQUEST_HEADERS -ne '' -or
$environment.OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_RESPONSE_HEADERS -ne '') {
throw "$serviceName enables HTTP header capture"
}
}
Write-Host "PASS: runtime isolation, non-root app/worker, resource and port boundaries, Git/image/log secret isolation, and telemetry redaction are enforced. Checked $($secretCandidates.Count) local secret values without printing them."