Контейнерный hardening и dependency/image scan

This commit is contained in:
EgorAnti
2026-11-27 13:36:34 +03:00
parent dd3427aa4c
commit 415edbf722
9 changed files with 379 additions and 11 deletions
+34 -4
View File
@@ -8,7 +8,17 @@ $json = & docker compose --profile verification --env-file $EnvFile config --for
if($LASTEXITCODE -ne 0){ throw 'docker compose config failed' }
$config = $json | ConvertFrom-Json
$allowedPublished = @{ nginx = 8443; openbao = 8200; grafana = 3000 }
$statefulWritableRoots = @('postgres','redis','rabbitmq','minio')
# The only four services with a writable root filesystem. Their stock entrypoints
# prepare a persistent named volume before dropping privileges, so read_only would
# break startup. They still drop the six capabilities listed below.
$statefulWritableRoots = @{
postgres = @{ reason = 'entrypoint chown/chmod of /var/lib/postgresql/data before dropping to the postgres user'; data = '/var/lib/postgresql/data' }
redis = @{ reason = 'entrypoint writes /tmp/users.acl and persists RDB snapshots to the /data volume'; data = '/data' }
rabbitmq = @{ reason = 'entrypoint prepares /var/lib/rabbitmq and the Erlang cookie'; data = '/var/lib/rabbitmq' }
minio = @{ reason = 'Bitnami entrypoint prepares /bitnami/minio/data and the /certs links'; data = '/bitnami/minio/data' }
}
$statefulDroppedCapabilities = @('AUDIT_WRITE','MKNOD','NET_RAW','SETFCAP','SETPCAP','SYS_CHROOT')
foreach($property in $config.services.PSObject.Properties) {
$name = $property.Name
@@ -22,9 +32,25 @@ foreach($property in $config.services.PSObject.Properties) {
throw "$name is missing no-new-privileges"
}
if(-not $service.cap_drop -or $service.cap_drop.Count -eq 0){ throw "$name has no capability drop policy" }
if($name -notin $statefulWritableRoots -and $service.read_only -ne $true){
throw "$name must use a read-only root filesystem"
if(-not @($service.tmpfs) -or @($service.tmpfs).Count -eq 0){
throw "$name has no private tmpfs for runtime scratch data"
}
if($name -in $statefulWritableRoots.Keys) {
if($service.read_only -eq $true){ throw "$name is declared as a stateful writable-root exception but is read_only" }
foreach($capability in $statefulDroppedCapabilities) {
if($service.cap_drop -notcontains $capability){
throw "$name does not drop $capability from its stateful exception profile"
}
}
$expectedData = $statefulWritableRoots[$name].data
$dataVolume = @($service.volumes) | Where-Object { $_.target -eq $expectedData }
if(-not $dataVolume){ throw "$name has no $expectedData persistent volume justifying the writable root" }
} else {
if($service.cap_drop -notcontains 'ALL'){ throw "$name must drop ALL capabilities" }
if($service.read_only -ne $true){ throw "$name must use a read-only root filesystem" }
}
foreach($volume in @($service.volumes) | Where-Object { $null -ne $_ }) {
if($volume.source -match 'docker\.sock' -or $volume.target -match 'docker\.sock'){
throw "$name mounts the Docker socket"
@@ -41,4 +67,8 @@ foreach($property in $config.services.PSObject.Properties) {
foreach($expected in $allowedPublished.Keys){
if(-not $config.services.$expected.ports){ throw "$expected operator/public port is missing" }
}
Write-Host 'PASS: ports, privileges, capabilities, filesystems and resource limits satisfy the local hardening contract.'
Write-Host 'PASS: every service has no-new-privileges, a capability drop policy, private tmpfs and resource limits.'
Write-Host 'PASS: non-stateful services use a read-only root and drop ALL capabilities.'
foreach($name in ($statefulWritableRoots.Keys | Sort-Object)){
Write-Host "EXCEPTION $name writable root: $($statefulWritableRoots[$name].reason)"
}
+123
View File
@@ -0,0 +1,123 @@
[CmdletBinding()]
param(
[string]$Gradlew = '.\gradlew.bat',
[string]$Configuration = 'runtimeClasspath',
[string]$OsvEndpoint = 'https://api.osv.dev/v1/querybatch',
[string]$JsonPath = '',
[switch]$FailOnHigh
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if (-not (Test-Path -LiteralPath $Gradlew)) { throw "Missing Gradle wrapper: $Gradlew" }
function Get-ResolvedCoordinates([string]$Text) {
$resolved = @{}
foreach ($line in ($Text -split "`r?`n")) {
if ($line -match '^\s*[|+\\ -]*[+\\]---\s+([A-Za-z0-9_.-]+):([A-Za-z0-9_.-]+)(?::([0-9][A-Za-z0-9_.+-]*))?') {
$group = $Matches[1]
$artifact = $Matches[2]
$version = $Matches[3]
$remainder = $line.Substring($Matches[0].Length)
if ($remainder -match '->\s*([A-Za-z0-9_.+-]+)') { $version = $Matches[1] }
if ($version) { $resolved["$group`:$artifact"] = $version }
}
}
return $resolved
}
function Invoke-OsvBatch([array]$Queries) {
$body = @{ queries = $Queries } | ConvertTo-Json -Depth 8 -Compress
$response = Invoke-RestMethod -Method Post -Uri $OsvEndpoint -Body $body `
-ContentType 'application/json' -TimeoutSec 90
if ($null -eq $response.results) { throw 'OSV batch response has no results' }
return $response.results
}
function Get-Severity($Vulnerability) {
if ($Vulnerability.database_specific -and $Vulnerability.database_specific.severity) {
return ([string]$Vulnerability.database_specific.severity).ToUpperInvariant()
}
return 'UNKNOWN'
}
function Get-FixedVersions($Vulnerability) {
$fixed = @()
foreach ($affected in @($Vulnerability.affected)) {
foreach ($range in @($affected.ranges)) {
foreach ($event in @($range.events)) {
if ($event.fixed) { $fixed += [string]$event.fixed }
}
}
}
return @($fixed | Sort-Object -Unique)
}
$dependencyOutput = & $Gradlew dependencies "--configuration=$Configuration" --no-daemon --console=plain 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { throw 'Gradle dependency resolution failed' }
$coordinates = Get-ResolvedCoordinates $dependencyOutput
$names = @($coordinates.Keys | Sort-Object)
if ($names.Count -eq 0) { throw 'No resolved dependencies were found' }
$queries = @($names | ForEach-Object {
@{ package = @{ name = $_; ecosystem = 'Maven' }; version = $coordinates[$_] }
})
$results = @()
for ($offset = 0; $offset -lt $queries.Count; $offset += 100) {
$slice = @($queries | Select-Object -Skip $offset -First 100)
$results += @(Invoke-OsvBatch $slice)
}
if ($results.Count -ne $queries.Count) { throw 'OSV returned an incomplete batch result' }
# querybatch returns only IDs; fetch each advisory once for severity/fix metadata.
$vulnerabilityIds = @()
foreach ($result in $results) {
if ($result.vulns) { $vulnerabilityIds += @($result.vulns | ForEach-Object { $_.id }) }
}
$vulnerabilityIds = @($vulnerabilityIds | Sort-Object -Unique)
$advisories = @{}
foreach ($id in $vulnerabilityIds) {
$advisories[$id] = Invoke-RestMethod -Uri "https://api.osv.dev/v1/vulns/$id" -TimeoutSec 60
}
$findings = @()
for ($index = 0; $index -lt $results.Count; $index++) {
if (-not $results[$index].vulns) { continue }
foreach ($reference in $results[$index].vulns) {
$vulnerability = $advisories[$reference.id]
if (-not $vulnerability) { throw "OSV advisory detail is missing for $($reference.id)" }
$aliases = @($vulnerability.aliases | Where-Object { $_ -like 'CVE-*' })
$findings += [pscustomobject]@{
package = $names[$index]
version = $coordinates[$names[$index]]
id = $vulnerability.id
cve = if ($aliases.Count) { $aliases[0] } else { '' }
severity = Get-Severity $vulnerability
fixed = @(Get-FixedVersions $vulnerability) -join ','
summary = [string]$vulnerability.summary
}
}
}
if ($JsonPath) {
[System.IO.File]::WriteAllText($JsonPath, ($findings | ConvertTo-Json -Depth 6),
[System.Text.UTF8Encoding]::new($false))
}
$severityCounts = @{}
foreach ($finding in $findings) {
$key = $finding.severity
if (-not $severityCounts.ContainsKey($key)) { $severityCounts[$key] = 0 }
$severityCounts[$key]++
}
Write-Host "Resolved OSV Maven dependencies: $($names.Count)"
Write-Host "Packages with findings: $(@($findings | Select-Object -ExpandProperty package -Unique).Count)"
Write-Host "Findings by severity: $(($severityCounts.GetEnumerator() | Sort-Object Name | ForEach-Object { "$($_.Name)=$($_.Value)" }) -join ' ')"
foreach ($finding in @($findings | Where-Object { $_.severity -in @('HIGH','CRITICAL') } | Sort-Object package, id)) {
Write-Host "HIGH_OR_CRITICAL $($finding.id) $($finding.cve) $($finding.package)@$($finding.version) fixed=$($finding.fixed)"
Write-Host " $($finding.summary)"
}
if ($FailOnHigh -and @($findings | Where-Object { $_.severity -in @('HIGH','CRITICAL') }).Count -gt 0) {
throw 'High or critical dependency findings require triage before this check can pass'
}