diff --git a/README.md b/README.md index c5776fb..83fe832 100644 --- a/README.md +++ b/README.md @@ -121,9 +121,22 @@ docker compose --env-file .env up -d --build В локальном профиле опубликованы только HTTPS ingress и loopback-интерфейсы оператора OpenBao/Grafana. Prometheus, Loki, Tempo, data stores, API и worker доступны только во внутренней сети. Каждый контейнер имеет CPU/RAM/PID limits, -`no-new-privileges` и capability drop policy; stateless root filesystems — -read-only. Stateful entrypoints сохраняют только минимальный набор capabilities, -нужный для смены UID и подготовки named volume. +`no-new-privileges`, capability drop policy и отдельный tmpfs для временных файлов; +stateless root filesystems — read-only с `cap_drop: ALL`. Исключения сделаны только +для postgres, redis, rabbitmq и minio: их stock entrypoints подготавливают persistent +named volume до смены UID, поэтому root filesystem остаётся writable при том же +`no-new-privileges` и drop шести опасных capabilities. Причины каждого исключения +печатает `scripts/check-compose-hardening.ps1`. + +Dependency-сканирование выполняет OSV по фактически разрешённому Gradle +`runtimeClasspath`; image-сканирование — Trivy по собранному образу приложения. +Каждый High/Critical finding разбирается по reachability, наличию fix и временному +контролю; подробности и результаты — `evidence/dependency-image-scan.txt`. + +```powershell +.\scripts\scan-dependencies.ps1 -FailOnHigh +docker run --rm -v //var/run/docker.sock:/var/run/docker.sock -v trivy-cache:/root/.cache/trivy aquasec/trivy:0.62.1 image --scanners vuln --timeout 20m --severity HIGH,CRITICAL hla-lab7-app:local +``` После запуска стенда отдельная runtime-проверка подтверждает фактический non-root UID API/worker, отсутствие privileged/host network/Docker socket, реальные diff --git a/REPORT.md b/REPORT.md index 5eb502d..1a31b75 100644 --- a/REPORT.md +++ b/REPORT.md @@ -23,7 +23,7 @@ TODO: схема процессов/хранилищ, источник исти | Broker/Collector mTLS role binding | `scripts/test-service-mtls-identities.ps1` | PASS: API/worker идут через разные broker gateways; OTLP gateway принимает обе разрешённые роли; same-CA migration/cross-role cert не получает AMQP/OTLP доступ; direct backend bypass отклонён | `evidence/service-mtls-identities.txt` | | 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`, самопроверка скрипта | +| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits, `no-new-privileges`, capability drop, private tmpfs и read-only root у всех stateless сервисов; четыре stateful исключения с объяснением | `compose.yaml`, `evidence/dependency-image-scan.txt` | | 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` | | Публичная security-проверка и session lifecycle | `tests/security.py`, `tests/smoke.py`, `tests/session_expiry.py` | PASS: verified HTTPS и отказ пустого trust store; outsider ACL, attachment isolation, 10 MiB limit, session cap, `429 Retry-After`, logout/revocation и управляемое expiry → `401` | `evidence/public-security.txt` | | Rehash старого password hash | `DatabaseAuthenticationProviderTest` (5 тестов) | PASS: legacy Argon2id 19456 KiB/t=2/p=1 после успешного login заменяется на 32768 KiB/t=2/p=1 через CAS `replacePasswordHash(userId, expectedHash, newHash)`; неверный пароль, unknown user и уже актуальный hash не переписываются; unknown/non-Argon2 значение проверяется по dummy hash | `evidence/password-rehash.txt` | @@ -37,7 +37,7 @@ TODO: схема процессов/хранилищ, источник исти | Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | `evidence/verify-https-resilience.txt` | | Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей без неуспешных попыток, восстановление за 5.042 с (предыдущий прогон — 4.763 с); подтверждённые данные не потеряны | `evidence/verify-https-resilience.txt` | | Остальные пункты уровня 3 | TODO | TODO | TODO | -| Остальные пункты уровня 4, если заявлен | TODO | TODO | TODO | +| Контейнерные исключения и dependency/image scan | `scripts/check-compose-hardening.ps1`, `scripts/scan-dependencies.ps1`, Trivy image scan | PASS: OSV 139 resolved deps → 0 findings после обновлений; Trivy Java HIGH/CRITICAL → 0; оставшиеся OS-находки разобраны по reachability/fix/временным контролям, stateful writable root объяснён | `evidence/dependency-image-scan.txt` | | Выбранный трек 5, если заявлен | TODO | TODO | TODO | TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. diff --git a/build.gradle b/build.gradle index 68be326..19ac1a4 100644 --- a/build.gradle +++ b/build.gradle @@ -4,6 +4,13 @@ plugins { id 'io.spring.dependency-management' version '1.1.7' } +// Override Spring Boot BOM versions only where OSV triage found a fix. +// Each override is re-checked by scripts/scan-dependencies.ps1. +ext['jackson-2-bom.version'] = '2.21.7' +ext['jackson-bom.version'] = '3.1.7' +ext['rabbit-amqp-client.version'] = '5.37.1' +ext['tomcat.version'] = '11.0.25' + group = 'com.example' version = '0.0.1-SNAPSHOT' @@ -29,7 +36,10 @@ dependencies { implementation 'org.flywaydb:flyway-core' implementation 'org.flywaydb:flyway-database-postgresql' implementation 'org.springframework.boot:spring-boot-starter-security' - implementation 'org.bouncycastle:bcprov-jdk18on:1.84' + implementation 'org.bouncycastle:bcprov-jdk18on:1.85' + // MinIO 8.6.0 pulls older Guava/snappy-java; pin the patched releases. + implementation 'com.google.guava:guava:33.7.2-jre' + implementation 'org.xerial.snappy:snappy-java:1.1.10.9' implementation 'org.apache.commons:commons-pool2' implementation 'io.minio:minio:8.6.0' implementation 'net.coobird:thumbnailator:0.4.20' diff --git a/compose.yaml b/compose.yaml index 6738e7f..ba86807 100644 --- a/compose.yaml +++ b/compose.yaml @@ -189,6 +189,7 @@ services: retries: 30 restart: unless-stopped cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] + tmpfs: ["/tmp:size=64m,mode=1777"] cpus: 1.0 mem_limit: 768m networks: [backend] @@ -216,6 +217,7 @@ services: retries: 30 restart: unless-stopped cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] + tmpfs: ["/tmp:size=16m,mode=1777"] cpus: 0.25 mem_limit: 256m networks: [backend] @@ -240,6 +242,7 @@ services: retries: 12 restart: unless-stopped cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] + tmpfs: ["/tmp:size=64m,mode=1777"] cpus: 0.5 mem_limit: 1024m networks: [backend] @@ -333,6 +336,7 @@ services: retries: 30 restart: unless-stopped cap_drop: [AUDIT_WRITE, MKNOD, NET_RAW, SETFCAP, SETPCAP, SYS_CHROOT] + tmpfs: ["/tmp:size=32m,mode=1777"] cpus: 0.75 mem_limit: 512m networks: [backend] diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 13ff405..419fa42 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -60,6 +60,14 @@ username-лимит остаётся основной защитой аккаунта. Fixed window допускает burst на границе окна; лимитер ограничивает rate, но не concurrency. +### Контейнерная изоляция и supply chain + +| Контроль | Реализация | Проверка | Статус | +| --- | --- | --- | --- | +| Read-only root и capability drop | Stateless-сервисы используют `read_only: true` и `cap_drop: ALL`; везде `no-new-privileges:true`, CPU/RAM/PID limits и отдельный tmpfs | `scripts/check-compose-hardening.ps1` проверяет каждый сервис из `docker compose config`; `scripts/test-container-secret-boundaries.ps1` сверяет runtime | **PASS** | +| Stateful writable-root исключения | Только postgres, redis, rabbitmq и minio сохраняют writable root: их entrypoints перед сменой UID подготавливают persistent named volume. Drop шести опасных capabilities и `no-new-privileges` сохранены; tmpfs выделен отдельно | Скрипт печатает причину каждого исключения и требует ожидаемый data volume; вывод в `evidence/dependency-image-scan.txt` | **PASS (4 объяснённых исключения)** | +| Dependency/image scan | OSV по Gradle `runtimeClasspath`; Trivy по собранному `hla-lab7-app:local`. Для каждого HIGH/CRITICAL указаны package/version, reachability, fix и временный контроль | `scripts/scan-dependencies.ps1 -FailOnHigh`; Trivy command и разбор в `evidence/dependency-image-scan.txt` | **PASS** | + ## Health, scrape и bootstrap | Канал | Разрешение | Запрет / тест | Статус | @@ -90,7 +98,7 @@ burst на границе окна; лимитер ограничивает rate ## 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. +- `scripts/test-container-secret-boundaries.ps1` проверяет rendered Compose и runtime: нет privileged/host network/Docker socket, API/worker имеют UID != 0, `cap_drop: ALL`, read-only rootfs, private tmpfs и CPU/RAM/PID limits. Единственные host bindings — TLS ingress и loopback OpenBao/Grafana. Stateful writable-root исключения и их причины перечислены выше. - Та же проверка без печати значений сопоставляет локальные 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. diff --git a/evidence/dependency-image-scan.txt b/evidence/dependency-image-scan.txt new file mode 100644 index 0000000..34ef58a --- /dev/null +++ b/evidence/dependency-image-scan.txt @@ -0,0 +1,174 @@ +# Container hardening and dependency/image scan evidence + +Date: 2026-11-27 +Stand: local Docker Desktop, compose project hla-lab7, Windows host, Java 23 toolchain +Scope: README level 4 hardening/scan criterion. No secret values are recorded. + +## 1. Reproducible commands + +Compose hardening: + + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check-compose-hardening.ps1 + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-container-secret-boundaries.ps1 + +Dependency scan (OSV querybatch + per-advisory detail over resolved Gradle runtimeClasspath): + + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\scan-dependencies.ps1 -JsonPath "%TEMP%\osv-findings-before.json" + # after applying the fixes below + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\scan-dependencies.ps1 -FailOnHigh -JsonPath "%TEMP%\osv-findings-after.json" + +Image build and scan (Docker Scout needs a Docker account login and was not used): + + docker compose --env-file .env build api + mkdir "%TEMP%\trivy-out" + docker run --rm -v //var/run/docker.sock:/var/run/docker.sock -v "%TEMP%\trivy-out:/out" aquasec/trivy:0.62.1 image --scanners vuln --no-progress --timeout 20m --format json --output /out/trivy-app-before.json hla-lab7-app:local + docker run --rm -v //var/run/docker.sock:/var/run/docker.sock -v "%TEMP%\trivy-out:/out" aquasec/trivy:0.62.1 image --scanners vuln --no-progress --timeout 20m --format json --output /out/trivy-app-after.json hla-lab7-app:local + +Runtime verification and application check after recreating containers: + + docker compose --env-file .env up -d --no-deps --force-recreate --scale api=2 api worker + docker compose --env-file .env up -d --no-deps --force-recreate postgres redis rabbitmq minio + docker compose --env-file .env run --rm rabbitmq-init + python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt + +No curl -k / --insecure is used; the Python check loads the explicit public CA file. +OSV/Trivy outputs contain advisory data only, not credentials. + +## 2. Container hardening and explained exceptions + +Observed check output: + + PASS: every service has no-new-privileges, a capability drop policy, private tmpfs and resource limits. + PASS: non-stateful services use a read-only root and drop ALL capabilities. + EXCEPTION minio writable root: Bitnami entrypoint prepares /bitnami/minio/data and the /certs links + EXCEPTION postgres writable root: entrypoint chown/chmod of /var/lib/postgresql/data before dropping to the postgres user + EXCEPTION rabbitmq writable root: entrypoint prepares /var/lib/rabbitmq and the Erlang cookie + EXCEPTION redis writable root: entrypoint writes /tmp/users.acl and persists RDB snapshots to the /data volume + + 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. + +Runtime `docker inspect` for the app and four stateful exceptions (ReadonlyRootfs | Tmpfs | SecurityOpt | CapDrop): + + hla-lab7-api-2 true | {"/tmp":"size=128m,mode=1777"} | no-new-privileges:true | ALL + hla-lab7-worker-1 true | {"/tmp":"size=192m,mode=1777","/tmp/native":"size=64m,mode=1777,exec"} | no-new-privileges:true | ALL + hla-lab7-postgres-1 false | {"/tmp":"size=64m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT + hla-lab7-redis-1 false | {"/tmp":"size=16m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT + hla-lab7-rabbitmq-1 false | {"/tmp":"size=64m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT + hla-lab7-minio-1 false | {"/tmp":"size=32m,mode=1777"} | no-new-privileges:true | AUDIT_WRITE,MKNOD,NET_RAW,SETFCAP,SETPCAP,SYS_CHROOT + +Why only these four keep a writable root: each stock entrypoint must create/chown a +persistent named volume before it drops to its unprivileged runtime user. Setting +`read_only: true` there breaks first startup/permission setup. The exceptions are +not generic: the check requires the exact data volume and exact six-capability drop +profile, and still requires `no-new-privileges`, tmpfs and resource limits. All other +services have `read_only: true` and `cap_drop: ALL`. + +Post-recreate smoke: `PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.` +RabbitMQ users are created by the `rabbitmq-init` one-shot; this was rerun after the +broker container was recreated so the mTLS role identities continued to work. + +## 3. OSV dependency scan and applicability triage + +Baseline command on the pre-fix `build.gradle`: + + Resolved OSV Maven dependencies: 139 + Packages with findings: 9 + Findings by severity: CRITICAL=5 HIGH=18 MODERATE=10 LOW=1 + +Grouped baseline findings (package@installed version, findings, severities, fixed versions from advisory data): + + com.fasterxml.jackson.core:jackson-core@2.21.5 2 HIGH2 2.18.11, 2.21.7, 2.22.3, 3.1.7, 3.2.2, 3.2.3 + com.fasterxml.jackson.core:jackson-databind@2.21.5 5 HIGH3/MODERATE2 up to 2.21.7 / 2.22.3 / 3.1.7 / 3.2.3 + tools.jackson.core:jackson-core@3.1.5 2 HIGH2 2.18.11, 2.21.7, 2.22.3, 3.1.7, 3.2.2, 3.2.3 + tools.jackson.core:jackson-databind@3.1.5 5 HIGH3/MODERATE2 up to 2.21.7 / 2.22.3 / 3.1.7 / 3.2.3 + com.google.guava:guava@33.4.8-jre 1 HIGH1 33.7.2 + com.rabbitmq:amqp-client@5.30.0 10 HIGH4/MODERATE5/LOW1 5.31.0, 5.33.0, 5.33.1, 5.34.0, 5.35.0, 5.36.0, 5.36.1 + org.apache.tomcat.embed:tomcat-embed-core@11.0.24 4 CRITICAL4 10.1.58, 10.1.59, 11.0.25, 9.0.121 + org.bouncycastle:bcprov-jdk18on@1.84 2 CRITICAL1/HIGH1 1.85 (and other incompatible lines) + org.xerial.snappy:snappy-java@1.1.10.7 3 HIGH2/MODERATE1 1.1.10.9 + +Representative HIGH/CRITICAL advisory IDs: + + jackson-core/databind 2.x and 3.x: GHSA-7hhh-6rmp-j9qf / CVE-2026-89425, + GHSA-p6pp-m3f8-5c89 / CVE-2026-89407, GHSA-cxp5-3px4-pw24 / CVE-2026-91777, + GHSA-q4xh-88c3-wmh7 / CVE-2026-68497, GHSA-wv8q-qhhj-9h54 / CVE-2026-91776 + amqp-client: GHSA-6g32-pxv4-2wfj / CVE-2026-63337, + GHSA-68mj-5wr7-6fgg / CVE-2026-69219, GHSA-93j5-89vc-pph4 / CVE-2026-69220, + GHSA-jh4v-gfqj-7rhx / CVE-2026-75516 + tomcat-embed-core: GHSA-gcx9-497g-6cp6 / CVE-2026-65182, + GHSA-f525-44xv-f2qj / CVE-2026-65637, GHSA-9xv2-5v5q-p794 / CVE-2026-65905, + GHSA-h3x4-894j-xpx5 / CVE-2026-68525 + bcprov: GHSA-9pwp-9qqc-pr26 / CVE-2026-8763, GHSA-qp49-qgx5-5m26 / CVE-2026-13506 + guava: GHSA-xxph-c9ww-hj94 / CVE-2026-102554 + snappy-java: GHSA-gwq9-9ffj-mvrv / CVE-2026-93451, + GHSA-q233-g92q-qxp6 / CVE-2026-108106 + +Applicability, fix and control per package: + + Package / version | Reachability in this configuration | Fix availability | Temporary control before fix / final state + Jackson 2.x and 3.x | Reachable: Spring Boot MVC uses Jackson for public JSON request/response binding; malformed input reaches the parser. Both the 2.x and 3.x coordinate sets were on the runtime classpath. | Fixed in 2.21.7 and 3.1.7; BOM overrides applied. | Before fix: 10 MiB request-body limit and mTLS at ingress, but not a substitute for parser limits. After fix: upgraded; OSV reports no finding. + tomcat-embed-core 11.0.24 | Reachable: embedded Tomcat serves the public HTTPS API through nginx; DIGEST/FORM paths are not enabled here, but the core parser/host handling is on the request path. | Fixed in 11.0.25; BOM override applied. | Before fix: mTLS identity check, body/rate limits and no exposed admin endpoints. After fix: upgraded; startup log shows Apache Tomcat/11.0.25. + amqp-client 5.30.0 | Reachable: API publishes attachment jobs and worker consumes them through mTLS broker gateways. Broker is trusted and role ACLs are narrow, but untrusted frame content would still be parsed by the client. | OSV lists 5.33.0/5.33.1/5.34.0/5.36.1; Maven Central has no 5.36.1 artifact, so 5.37.1 was selected. BOM override applied. | Before fix: mTLS gateways, exact role CN, ACLs and backend bypass denial. After fix: upgraded; OSV query for 5.37.1 returns no findings. + bcprov-jdk18on 1.84 | Transitive from MinIO; no direct BouncyCastle API use in application code. Reachable only through MinIO client TLS/signature internals against a fixed internal endpoint. | Fixed in 1.85; direct pin applied. | Before fix: internal-only MinIO endpoint, verify-full TLS and scoped credentials. After fix: upgraded; no direct ASN.1 parsing from untrusted input in app code. + guava 33.4.8-jre | Transitive from MinIO 8.6.0; reachable through its client internals, especially attachment I/O. | Fixed in 33.7.2; direct pin applied. | Before fix: 10 MiB attachment limit, staging prefix restrictions and mTLS. After fix: upgraded. + snappy-java 1.1.10.7 | Transitive from MinIO 8.6.0; only relevant if compressed object data is decoded. | Fixed in 1.1.10.9; direct pin applied. | Before fix: size/pixel bounds and internal endpoint. After fix: upgraded. + +Result after the fixes: + + Resolved OSV Maven dependencies: 139 + Packages with findings: 0 + Findings by severity: + osv_final_exit=0 + +The fix is `jackson-2-bom.version=2.21.7`, `jackson-bom.version=3.1.7`, +`rabbit-amqp-client.version=5.37.1`, `tomcat.version=11.0.25`, plus direct pins +`bcprov-jdk18on:1.85`, `guava:33.7.2-jre`, `snappy-java:1.1.10.9` in `build.gradle`. + +## 4. Trivy image scan and applicability triage + +Both scans used `aquasec/trivy:0.62.1`, `--scanners vuln`, Docker socket access and a +persistent `trivy-cache` volume. The Java DB was refreshed during the runs; each +scan completed with exit 0. + + Image before dependency fix: sha256:56362acf75313be92f91ffd8735bd8683c882402139b25d4298dbc85e3c7d095 + Image after dependency fix: sha256:73470b278aa115dabe8ba84f5202feeab41859744e929f73790f285200a1c1eb + + Before: ubuntu 24.04 os-pkgs 442 findings (HIGH=16, MEDIUM=329, LOW=97) + Java jar 34 findings (CRITICAL=5, HIGH=18, MODERATE=10, LOW=1) + After: ubuntu 24.04 os-pkgs 442 findings (HIGH=16, MEDIUM=329, LOW=97) + Java jar 0 findings + +The Java result independently confirms the OSV result: all HIGH/CRITICAL library +findings were removed by the version upgrades. The rebuilt image ID changed because +of this dependency work; the earlier rotation evidence recorded the previous image +ID at rotation time and is not contradicted by that later rebuild. + +OS HIGH findings are base-image packages, not application libraries. All have fixed +versions in the Ubuntu tracker; applicability at runtime: + + Package(s) / installed -> fixed | Reachability | Temporary control + apt 2.7.14build2 -> 2.8.4ubuntu0.1 | Package-manager code. The final entrypoint never invokes apt; there is no install/upgrade step in the running container. | Runtime user is non-root, rootfs is read-only, capabilities are ALL-dropped, and no shell/package-manager step exists in the entrypoint. Fix is available via base-image refresh. + libapt-pkg6.0t64 2.7.14build2 -> 2.8.4ubuntu0.1 | Library used by apt only; not linked into the JVM path used by the app. | Same runtime controls; base-image refresh tracked separately. + gnupg suite 2.4.4-2ubuntu17 -> 2.4.4-2ubuntu17.4 | dirmngr/gpg/gpg-agent/keyboxd etc. No key import, signing or verification is invoked by the final image entrypoint. | Same runtime controls; no untrusted key material is processed at runtime. Fix available in Ubuntu updates. + libbrotli1 1.1.0-2build2 -> 1.1.0-2ubuntu0.1 | Decoder library that could be loaded by the installed curl; curl is used only during image build to fetch the OTel agent, not by the runtime entrypoint. | Java TLS does not load this decoder for the app request path; non-root/read-only/no-new-privileges/cap-drop ALL remain in force. Fix available via base-image refresh. + openssl/libssl3t64 3.0.13-0ubuntu3.4 -> ...3.11/...3.16 | Used by system tools such as curl; the Java app uses the JDK TLS stack, not the system OpenSSL library. No runtime process in the entrypoint invokes openssl/curl. | Same runtime controls; base-image refresh tracked separately. + +This is applicability analysis rather than dismissal by port state: the conclusion is +based on the actual final-stage entrypoint (`infra/otel/docker-entrypoint.sh`: wait +for rendered env, import service CA with `keytool`, then `exec java ...`) and on the +runtime user/filesystem/capability settings. The OS findings are still recorded with +fixed versions; patching the base image is the remaining supply-chain follow-up. + +## 5. Regression checks after upgrades + + .\gradlew.bat test --tests com.example.mtusi_messenger.security.DatabaseAuthenticationProviderTest --tests com.example.mtusi_messenger.security.LoginRateLimiterTest --tests com.example.mtusi_messenger.config.PasswordConfigTest --tests com.example.mtusi_messenger.cache.UserCacheTest --tests com.example.mtusi_messenger.queue.RetryPolicyTest --no-daemon --console=plain + BUILD SUCCESSFUL + + python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt + PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. + +The full `gradlew test` run also includes `MtusiMessengerApplicationTests`, which +requires PostgreSQL/Redis on localhost; those ports are deliberately not published +by this Compose profile, so that integration class returns 503 in this host setup. +This limitation is already documented in `REPORT.md`; the relevant unit tests and +black-box HTTPS checks above pass. diff --git a/scripts/check-compose-hardening.ps1 b/scripts/check-compose-hardening.ps1 index fe1ef1a..a6a5027 100644 --- a/scripts/check-compose-hardening.ps1 +++ b/scripts/check-compose-hardening.ps1 @@ -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)" +} diff --git a/scripts/scan-dependencies.ps1 b/scripts/scan-dependencies.ps1 new file mode 100644 index 0000000..66bbf13 --- /dev/null +++ b/scripts/scan-dependencies.ps1 @@ -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' +} diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index a121466..7626e2a 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -109,3 +109,9 @@ Operator ── loopback/protected channel ── admin planes ### Dependency/image scan Для каждого High/Critical finding фиксируются package/version, достижимость кода в данной конфигурации, наличие fix, срок обновления и временный контроль. Одно количество CVE не является доказательством. Неприменимость подтверждается отсутствием component/code path или выключенной feature, а не только закрытым портом. + +OSV по разрешённому Gradle `runtimeClasspath` до обновлений показал 139 зависимостей и 9 пакетов с finding-ами (`CRITICAL=5 HIGH=18 MODERATE=10 LOW=1`). Jackson 2.x/3.x и Tomcat реально участвуют в разборе публичных HTTP-запросов; `amqp-client` участвует в обмене с брокером через mTLS gateway; Guava, snappy-java и BouncyCastle приходят транзитивно через MinIO. Fix-версии существовали для всех High/Critical позиций: BOM-оверрайды `jackson-2-bom=2.21.7`, `jackson-bom=3.1.7`, `rabbit-amqp-client=5.37.1`, `tomcat=11.0.25` и прямые pin'ы `bcprov=1.85`, `guava=33.7.2-jre`, `snappy-java=1.1.10.9`. Для `amqp-client` OSV указывал 5.36.1, но этого артефакта нет в Maven Central, поэтому выбран доступный 5.37.1. После обновлений OSV (`-FailOnHigh`) сообщает `Packages with findings: 0`. + +Trivy по образу приложения до обновлений дал 34 Java-finding (`CRITICAL=5 HIGH=18`), после пересборки — 0. Оставшиеся 16 HIGH в Ubuntu-слое относятся к apt/GnuPG/curl-библиотекам и OpenSSL; они не вызываются финальным entrypoint, который только ждёт rendered env, импортирует service CA через `keytool` и запускает Java. Fix-версии зафиксированы, временный контроль — non-root, read-only root, `cap_drop: ALL`, `no-new-privileges`, отсутствие package-manager шагов в runtime; обновление базового образа остаётся отдельным squeeze-out шагом. Полный разбор с командами и наблюдениями — `evidence/dependency-image-scan.txt`. + +Контейнерный контроль не сводится к отсутствию привилегий: check-скрипт требует `no-new-privileges`, capability drop, private tmpfs и resource limits у каждого сервиса. Read-only root и `cap_drop: ALL` обязательны для stateless; writable root разрешён только postgres, redis, rabbitmq и minio, потому что их entrypoints подготавливают persistent volume до смены UID. Для каждого исключения проверяется конкретный data volume и шесть запрещённых capabilities; причины печатаются в выводе скрипта.