From dd3427aa4c872949a754d6b750fd7ffa6fb8fe2a Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Fri, 27 Nov 2026 12:57:33 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=BE=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20se?= =?UTF-8?q?cret=20=D0=B8=20leaf=20certificate,=20=D0=BE=D1=82=D0=B7=D1=8B?= =?UTF-8?q?=D0=B2=20identity=20=D0=B8=20=D0=B3=D1=80=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=86=D1=8B=20OpenBao?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 7 +- compose.yaml | 1 + contracts/trust-matrix.md | 12 +- evidence/rotation-renewal.txt | 81 +++++++++++ evidence/security-lifecycle.txt | 2 +- infra/openbao/README.md | 37 ++++- scripts/rotate-grafana-admin-password.ps1 | 132 +++++++++++++++++ scripts/rotate-pki-leaf.ps1 | 136 ++++++++++++++++++ scripts/test-openbao-rotation-boundaries.ps1 | 80 +++++++++++ scripts/test-rotated-leaf.ps1 | 56 ++++++++ security/THREAT_MODEL.md | 6 +- .../TrustedClientCertificateFilter.java | 50 ++++++- src/main/resources/application.yml | 1 + .../TrustedClientCertificateFilterTest.java | 24 +++- 14 files changed, 614 insertions(+), 11 deletions(-) create mode 100644 evidence/rotation-renewal.txt create mode 100644 scripts/rotate-grafana-admin-password.ps1 create mode 100644 scripts/rotate-pki-leaf.ps1 create mode 100644 scripts/test-openbao-rotation-boundaries.ps1 create mode 100644 scripts/test-rotated-leaf.ps1 diff --git a/REPORT.md b/REPORT.md index decb4b2..5eb502d 100644 --- a/REPORT.md +++ b/REPORT.md @@ -18,7 +18,7 @@ TODO: схема процессов/хранилищ, источник исти | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | | Argon2id storage и калибровка | `scripts/benchmark-argon2.ps1`, `PasswordConfigTest` | PASS: итоговый профиль 32768 KiB/t=2/p=1; p95 encode 134.8 мс, verify 165.5 мс при 0.75 CPU/768 MiB (предыдущий прогон: 150.3/142.7 мс); PHC хранит параметры и уникальный 16-byte salt | `evidence/login-dos.txt`, `README.md`, unit test | -| LB → каждая API-реплика | `scripts/test-mtls.ps1`, `TrustedClientCertificateFilterTest` | PASS: обе реплики отдельно отклоняют no-cert, foreign CA и доверенный cert с чужим URI SAN; LB identity принята; API port не опубликован | `compose.yaml`, runtime test, unit test | +| LB → каждая API-реплика | `scripts/test-mtls.ps1`, `TrustedClientCertificateFilterTest` | PASS: обе реплики отдельно отклоняют no-cert, foreign CA и доверенный cert с чужим URI SAN; LB identity принята; API port не опубликован; добавлен fail-closed deny-list отозванных DER SHA-256 leaf | `compose.yaml`, runtime test, unit test | | Внутренние TLS-связи и service ACL | `scripts/test-internal-tls.ps1`; `docker compose --env-file .env --profile verification run --rm private-bucket-check` | PASS: PostgreSQL, MinIO, OpenBao, Redis, RabbitMQ, Collector, Loki, Tempo и Prometheus проверяют service CA и hostname; mTLS endpoints отвергают no-cert; PostgreSQL/Redis/RabbitMQ и MinIO API/worker identities разделены, запрещённые DDL/keys/commands/prefixes denied | `evidence/internal-tls.txt`, `contracts/trust-matrix.md` | | 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` | @@ -29,7 +29,10 @@ TODO: схема процессов/хранилищ, источник исти | 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` | | Login DoS budget и общий rate limit | `scripts/measure-login-dos.ps1 -SourceBudget`, `scripts/benchmark-argon2.ps1`, `LoginRateLimiterTest` | PASS: 5 попыток/username/60 s и 100/source/60 s в общем Redis; 6-я и 101-я попытки → `429` + `Retry-After`; 429 ≈ 19 мс против 401 p50 287 мс (Argon2 не запускается); обе реплики наблюдались; Redis outage fail-closed; ключи — SHA-256 digests | `evidence/login-dos.txt` | | Credential non-disclosure | `tests/credential_storage.py`, `tests/login_dos.py` | PASS: `password_hash` — Argon2id PHC, `token_hash` — 32-byte SHA-256; plaintext password/token/hash отсутствуют в API/LB logs; known и unknown user дают одинаковый `401` code/message; тела ошибок не содержат credentials | `evidence/credential-storage.txt`, `evidence/login-dos.txt` | -| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 26 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | `evidence/security-lifecycle.txt` | +| Ротация leaf certificate и отзыв identity | `scripts/rotate-pki-leaf.ps1`, `scripts/test-rotated-leaf.ps1`, `scripts/test-mtls.ps1` | PASS: LB leaf перевыпущен без rebuild, старый DER SHA-256 `8b3f0a8d…` добавлен в deny-list; обе API-реплики отвечают `403` на старый leaf и `200` на новый; image ID nginx/API не изменился | `evidence/rotation-renewal.txt` | +| Ротация рабочего secret | `scripts/rotate-grafana-admin-password.ps1` | PASS: Grafana admin password изменён через API, `.env` обновлён, старый пароль отклонён, новый принят, image ID не изменился, значения не печатаются | `evidence/rotation-renewal.txt` | +| Sealed/expiry OpenBao, bootstrap trust и renewal | `scripts/test-openbao-rotation-boundaries.ps1`, `scripts/check-security-lifecycle.ps1`, `scripts/test-openbao-policies.ps1` | PASS: при sealed OpenBao агенты и API продолжают работать на кэшированном rendered env, fresh startup без файла падает за 2.8 c при лимите 2 c; TTL 15m/1h, template 5m, root/unseal/secret «для получения секретов» в образе и репозитории отсутствуют | `evidence/rotation-renewal.txt`, `infra/openbao/README.md` | +| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 28 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` | | Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей без неуспешных попыток, восстановление за 5.042 с (предыдущий прогон — 4.763 с); подтверждённые данные не потеряны | `evidence/verify-https-resilience.txt` | diff --git a/compose.yaml b/compose.yaml index 66e0014..6738e7f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -512,6 +512,7 @@ services: SERVER_SSL_TRUST_CERTIFICATE: /run/pki/lb-client-ca/ca.crt SERVER_SSL_CLIENT_AUTH: need MTLS_ALLOWED_CLIENT_URI: spiffe://hla-lab7/lb + MTLS_REVOKED_CERTIFICATES_FILE: /run/pki/revoked-client-sha256.txt DATABASE_USER: messenger_api CLIENT_TLS_CERTIFICATE: /run/pki/api-client/tls.crt CLIENT_TLS_PRIVATE_KEY: /run/pki/api-client/tls.key diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 88ea373..13ff405 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -11,7 +11,7 @@ | Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус | | --- | --- | --- | --- | --- | --- | --- | | Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/pki/public-ca/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement/expiry revoke access; leaf 30 d | `make test-security`, `make test-session-expiry`, `scripts/measure-login-dos.ps1 -SourceBudget`; пустой trust store → certificate error; revoked/expired token → 401; login burst → 429 + Retry-After; rehash и dummy hash — unit tests | **PASS** для внешнего TLS/auth/session/rate-limit контракта | -| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1` обращается к каждой реплике отдельно: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; LB cert → health 200; прямой published port отсутствует | **PASS** | +| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN и deny-list DER SHA-256 до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, rotation/revocation без rebuild; unreadable deny-list fail-closed | `scripts/test-mtls.ps1` проверяет каждую реплику: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; `scripts/test-rotated-leaf.ps1`: старый LB leaf → 403, новый → 200; прямой published port отсутствует | **PASS** | | API → PostgreSQL | `postgres:5432` | TLS `verify-full`; service CA + SAN `DNS:postgres`; plaintext rejected by `pg_hba.conf` | `messenger_api`: runtime CRUD без superuser/DDL/role management | Static stand secret, rotate/reconnect; dynamic credentials remain extension | Wrong CA/hostname fails; DDL/role management denied | **PASS (уровень 3)** | | Worker → PostgreSQL | `postgres:5432` | TLS `verify-full` | `messenger_worker`: jobs/attachments/variants; нет users password/session/membership | Отдельный secret | `SELECT password_hash`, update membership denied; job transitions allowed | **PASS (уровень 3)** | | API → MinIO | `https://minio:9000` | TLS verify-full; service CA + SAN `DNS:minio` | `messenger-api`, policy `messenger-attachments-api`: list разрешённых prefixes, read/delete final objects, write/delete только staging; без admin | Credential рендерит API AppRole; отдельно от root/worker | Anonymous/admin/final-object write denied; staging write succeeds | **PASS** | @@ -33,6 +33,16 @@ | Operator → MinIO admin | Не публикуется; bootstrap внутри сети | TLS verify | Root/operator отдельно; API/worker его не получают | Rotate after bootstrap/exposure | API/worker `mc admin info` denied | **PARTIAL:** port закрыт/policy test есть; HTTP и root env у init | | Replication channels | N/A: все stateful services single-node | N/A | N/A | N/A | При добавлении replicas матрица пересматривается | **N/A** | +### Ротация, отзыв и обновление доверия + +| Контроль | Реализация | Проверка | Статус | +| --- | --- | --- | --- | +| Leaf rotation без rebuild | `scripts/rotate-pki-leaf.ps1` выпускает новый leaf тем же service CA, архивирует старый комплект и записывает только его DER SHA-256 в `/run/pki/revoked-client-sha256.txt`; image ID не меняется | `scripts/test-rotated-leaf.ps1`: 2 реплики → old 403 / new 200; `scripts/test-mtls.ps1` остаётся PASS | **PASS** | +| Отзыв старой identity | `TrustedClientCertificateFilter` сверяет отпечаток client leaf с deny-list при каждом запросе; отсутствие/нечитаемость файла при явной конфигурации отзывает все identity | unit test на revoked fingerprint; runtime probe старого LB leaf → 403 | **PASS** | +| Ротация рабочего secret | `scripts/rotate-grafana-admin-password.ps1` меняет пароль через Grafana API, обновляет `.env`, пересоздаёт только контейнер, проверяет old/new и не печатает значения | `evidence/rotation-renewal.txt`: old rejected, new accepted, image unchanged | **PASS** | +| Bootstrap trust | Operator init создаёт 3 Shamir shares (порог 2) и root token вне репозитория; `bootstrap-openbao.ps1` создаёт scoped policies/AppRoles/KV и записывает RoleID/SecretID только в `secrets/` | `scripts/test-openbao-policies.ps1`, `scripts/test-openbao-runtime-boundaries.ps1`, `scripts/check-security-lifecycle.ps1` | **PASS** | +| Renewal и sealed/expiry | Service token 15 min/max 1 h, Agent auto-auth и template 5 min, `exit_on_retry_failure=false`; sealed OpenBao не снимает уже выданные runtime credentials; fresh startup без rendered file завершается по таймауту | `scripts/test-openbao-rotation-boundaries.ps1`: agents Up, health 200, fail-closed за 2.8 c при лимите 2 c | **PASS** | + ### Пароли, сессии и login DoS | Контроль | Реализация | Проверка | Статус | diff --git a/evidence/rotation-renewal.txt b/evidence/rotation-renewal.txt new file mode 100644 index 0000000..c06b925 --- /dev/null +++ b/evidence/rotation-renewal.txt @@ -0,0 +1,81 @@ +# Rotation, revocation and OpenBao boundary evidence + +Date: 2026-11-27 +Stand: local Docker Desktop, compose project hla-lab7 +Scope: README level 4, rotation/revocation/renewal criterion. No secret values are recorded. + +## 1. LB leaf rotation and old identity revocation + +Commands: + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\rotate-pki-leaf.ps1 ` + -Leaf lb -CaName lb-client-ca -UriSan spiffe://hla-lab7/lb -RevokeOld + docker compose --env-file .env up -d --no-deps --force-recreate --scale api=2 api + docker compose --env-file .env up -d --no-deps --force-recreate nginx + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-rotated-leaf.ps1 + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-mtls.ps1 + +Observed: + ROTATED lb (CA lb-client-ca) without rebuilding images. + old_leaf_sha256=8b3f0a8d2fb055dff0bb6fd2bf8409942c8f60de1c6306ecaff43f8cd100f6c2 + new_leaf_sha256=d411b42909f0186d8c9b3514e27c6fd3921dd7a6ec5d316546f2dc13c5cf29af + revoked_old_leaf=8b3f0a8d2fb055dff0bb6fd2bf8409942c8f60de1c6306ecaff43f8cd100f6c2 + api image before/after reload: sha256:56362acf75313be92f91ffd8735bd8683c882402139b25d4298dbc85e3c7d095 + nginx image before/after reload: sha256:4cad75abc83d5ca6ee22053d85850676eaef657ee9d723d7bef61179e1e1e485 + PASS: 2 API replicas reject the revoked LB leaf with 403 and accept the rotated LB leaf with 200. + PASS: 2 API replicas require a client certificate and LB CA; forbidden URI SAN is rejected; only the LB identity succeeds; no API port is published. + +The old leaf/key are archived under secrets/pki/revoked/lb/ (ignored by Git). Only its +SHA-256 DER fingerprint is appended to the runtime deny-list mounted at +/run/pki/revoked-client-sha256.txt. An unreadable deny-list fails closed. + +## 2. Working secret rotation without image rebuild + +Command: + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\rotate-grafana-admin-password.ps1 + +Observed: + PASS: Grafana admin password rotated through the API and .env without rebuilding images. + old_password_accepted_after=false + new_password_accepted_after=true + grafana_image=sha256:6afa1ab7f6e662c739a45a1d458598d7eb6ab70fc7c0ab45af64864e1503d4b6 + +The script generates the new password locally, calls Grafana PUT /api/user/password, +updates .env, recreates only the Grafana container, verifies old/new credentials and +never prints or commits either value. Image ID was unchanged. + +## 3. Sealed/unavailable OpenBao and bounded expiry behavior + +Command: + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-rotation-boundaries.ps1 + +Observed: + bao status: Sealed true, Initialized true, Shamir 3 shares / threshold 2. + openbao-agent-api and openbao-agent-worker: Running=true. + Rendered runtime env keys still present: DATABASE_PASSWORD, RABBITMQ_PASSWORD, REDIS_PASSWORD, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY. + Public HTTPS /health/ready: 200. + Fresh startup with OPENBAO_RENDERED_ENV=/run/missing/runtime.env and a 2 s deadline: + exit 1, "OpenBao did not render runtime credentials before startup deadline", 2.8 s. + PASS: AppRole token TTL is 15m/1h, templates renew every 5m, and no permanent operator secret is embedded in the image. + PASS: application image has no BAO_TOKEN/UNSEAL/ROOT_TOKEN/SECRET_ID env entry and no .env/secrets/runtime.env/key artifact. + +After the sealed-state evidence was captured, the lab OpenBao instance was reinitialized +and re-bootstrapped from local .env because unseal shares are intentionally held offline. +No unseal share or root token was written to the repository. + +## 4. Bootstrap trust and lifecycle checks + +Commands: + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check-security-lifecycle.ps1 + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-policies.ps1 + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-openbao-runtime-boundaries.ps1 + +Observed: + PASS: 28 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL. + OpenBao policy checks passed: own path allowed; foreign path and policy changes denied. + PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use separate AppRoles, scoped policies and read-only rendered files; operator material is absent. + +Trust bootstrap: operator init creates 3 Shamir shares with threshold 2 offline; root token +is used only for bootstrap and removed from the environment; AppRole role-id/secret-id are +stored in ignored local files; agents auto-auth to OpenBao over verified TLS and render only +five allowlisted keys into per-role named volumes. The app enters controlled-unready when +the rendered file is missing and does not fall back to plaintext credentials. diff --git a/evidence/security-lifecycle.txt b/evidence/security-lifecycle.txt index 94accf3..2aa8c18 100644 --- a/evidence/security-lifecycle.txt +++ b/evidence/security-lifecycle.txt @@ -6,7 +6,7 @@ Command: powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check-security-lifecycle.ps1 Observed output: - PASS: 26 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL. + PASS: 28 certificate/key bundles are valid; private/operator secrets are untracked; present SecretIDs are within TTL. Scope: certificate validity window, SAN presence, leaf validity limit, private-key/certificate pairing, Git tracking of private material, ignore rules for `.env` and TLS keys, absence of root/unseal artifacts, and AppRole SecretID age. diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 40bc550..4d4e66d 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -69,10 +69,45 @@ OpenBao Agent у API и worker аутентифицируется своим App ## Перезапуск, seal и восстановление -После перезапуска `openbao-data` сохраняется. Оператор снова выполняет две интерактивные команды `bao operator unseal`. Пока OpenBao sealed, agents не получают и не обновляют token; hardcoded или `.env` fallback у приложений отсутствует. После unseal agents повторяют authentication. Если приложение ещё не запущено, entrypoint ждёт rendered file до 120 секунд и завершает работу при его отсутствии. +После перезапуска `openbao-data` сохраняется. Оператор снова выполняет две интерактивные команды `bao operator unseal`. Пока OpenBao sealed, agents не получают и не обновляют token; hardcoded или `.env` fallback у приложений отсутствует. После unseal agents повторяют authentication. Если приложение ещё не запущено, entrypoint ждёт rendered file до `OPENBAO_STARTUP_TIMEOUT_SECONDS` (по умолчанию 120 с) и завершает работу при его отсутствии. Значение можно уменьшить для быстрого fail-closed; это не влияет на уже работающие контейнеры. Статические DB/Redis/RabbitMQ/S3 credentials читаются приложением при старте. После создания новой KV version следует последовательно перезапустить API/worker, проверить новые соединения, затем отозвать старые credentials в зависимости. OpenBao token rotation выполняется Agent автоматически. +## Ротация и отзыв без пересборки образов + +Три сценария ротации выполняются на работающем стенде и не меняют image ID контейнеров. Полный санитизированный протокол — `evidence/rotation-renewal.txt`. + +### Leaf certificate и отзыв старой identity + +```powershell +.\scripts\rotate-pki-leaf.ps1 -Leaf lb -CaName lb-client-ca -UriSan spiffe://hla-lab7/lb -RevokeOld +docker compose --env-file .env up -d --no-deps --force-recreate --scale api=2 api +docker compose --env-file .env up -d --no-deps --force-recreate nginx +.\scripts\test-rotated-leaf.ps1 +.\scripts\test-mtls.ps1 +``` + +Скрипт выпускает новый leaf тем же CA, архивирует старый комплект в игнорируемый каталог `secrets/pki/revoked//` и добавляет в deny-list только DER SHA-256 отпечаток старого сертификата. Файл монтируется как `/run/pki/revoked-client-sha256.txt`; `TrustedClientCertificateFilter` сверяет отпечаток каждого client leaf до auth. Явно сконфигурированный, но нечитаемый deny-list отзывает все client identity (fail-closed). Перезапуск контейнеров сохраняет image ID: PKI смонтирован из volume, а не зашит в образ. Измерено: обе API-реплики отвечают `403` на старый leaf и `200` на новый; image ID API и nginx до/после одинаковы. + +### Рабочий secret + +```powershell +.\scripts\rotate-grafana-admin-password.ps1 +``` + +Скрипт генерирует новый пароль локально, меняет его через `PUT /api/user/password`, обновляет игнорируемый `.env`, пересоздаёт только Grafana и проверяет, что старый пароль отклонён, а новый принят. Значения не печатаются и не попадают в Git или образ; image ID Grafana не меняется. + +### Sealed/expiry и ограниченное поведение + +```powershell +# Оператор seals OpenBao или останавливает сервер; share хранятся offline. +.\scripts\test-openbao-rotation-boundaries.ps1 +``` + +Скрипт намеренно не выполняет unseal: он проверяет уже наступившее состояние `Sealed true`. Измерено: оба Agent остаются Running, кэшированные rendered keys доступны, public HTTPS `/health/ready` → `200`. Свежий контейнер с отсутствующим rendered env завершился за 2.8 с при configured deadline 2 с. После снятия показаний лабораторный OpenBao был переинициализирован и заново bootstrapped из локального `.env`; новые share/root token в репозиторий или окружение не записывались. + +Renewal задан конфигурацией: AppRole token TTL 15 min / max 1 h, `static_secret_render_interval = "5m"`, `exit_on_retry_failure = false`. В образе приложения нет `BAO_TOKEN`, UNSEAL/ROOT_TOKEN, SecretID, `.env`, `secrets/` или key-артефактов — постоянного секрета «для получения секретов» не существует. + ## Ротация AppRole bootstrap credential SecretID нужно менять до истечения 24 часов: diff --git a/scripts/rotate-grafana-admin-password.ps1 b/scripts/rotate-grafana-admin-password.ps1 new file mode 100644 index 0000000..82015c2 --- /dev/null +++ b/scripts/rotate-grafana-admin-password.ps1 @@ -0,0 +1,132 @@ +[CmdletBinding()] +param( + [string]$EnvFile = '.env', + [int]$Port = 3000 +) + +$ErrorActionPreference = 'Stop' +$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +Set-Location $projectRoot +$envPath = Join-Path $projectRoot $EnvFile +$caCertificate = Join-Path $projectRoot 'secrets\pki\service-ca\ca.crt' +if (-not (Test-Path -LiteralPath $envPath)) { throw "Missing env file: $EnvFile" } +if (-not (Test-Path -LiteralPath $caCertificate)) { throw "Missing service CA: $caCertificate" } + +function Get-EnvValue([string]$Name) { + foreach ($line in [System.IO.File]::ReadAllLines($envPath)) { + if ($line -match "^\s*$([regex]::Escape($Name))=(.*)$") { + return $Matches[1].Trim().Trim('"') + } + } + return $null +} + +function Set-EnvValue([string]$Name, [string]$Value) { + $lines = [System.IO.File]::ReadAllLines($envPath) + $updated = $false + for ($index = 0; $index -lt $lines.Count; $index++) { + if ($lines[$index] -match "^\s*$([regex]::Escape($Name))=") { + $lines[$index] = "$Name=$Value" + $updated = $true + break + } + } + if (-not $updated) { throw "$Name is missing from $EnvFile" } + [System.IO.File]::WriteAllLines($envPath, $lines, [System.Text.UTF8Encoding]::new($false)) +} + +function Invoke-Grafana([string]$User, [string]$Password, [string]$Path, + [string]$Method = 'GET', [string]$Body = '') { + $arguments = @('-sS','-o','NUL','-w','%{http_code}','--cacert',$caCertificate, + '--ssl-no-revoke','--connect-timeout','5','--max-time','15','-u',"$User`:$Password") + if ($Method -ne 'GET') { $arguments += @('-X',$Method) } + $bodyFile = $null + if ($Body) { + # curl.exe on Windows must receive JSON from a file: inline arguments + # are quote-stripped, and PowerShell's default UTF-8 writer adds a BOM. + $bodyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("grafana-rotation-" + [guid]::NewGuid().ToString('N') + '.json') + [System.IO.File]::WriteAllText($bodyFile, $Body, [System.Text.UTF8Encoding]::new($false)) + $arguments += @('-H','Content-Type: application/json','--data-binary',"@$bodyFile") + } + $previous = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + $code = (& curl.exe @arguments "https://localhost:$Port$Path" 2>$null | Out-String).Trim() + } finally { + $ErrorActionPreference = $previous + if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -Force -ErrorAction SilentlyContinue } + } + return $code +} + +function Invoke-ComposeQuiet([string[]]$Arguments) { + $previous = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + & docker compose @Arguments 2>&1 | Out-Null + $code = $LASTEXITCODE + } finally { + $ErrorActionPreference = $previous + } + if ($code -ne 0) { throw "docker compose failed with exit code $code" } +} + +function New-RotationPassword { + $bytes = New-Object byte[] 24 + $generator = [System.Security.Cryptography.RandomNumberGenerator]::Create() + try { $generator.GetBytes($bytes) } finally { $generator.Dispose() } + return [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') +} + +$user = Get-EnvValue 'GRAFANA_ADMIN_USER' +if ([string]::IsNullOrWhiteSpace($user)) { $user = 'admin' } +$oldPassword = Get-EnvValue 'GRAFANA_ADMIN_PASSWORD' +if ([string]::IsNullOrWhiteSpace($oldPassword)) { throw 'GRAFANA_ADMIN_PASSWORD is missing from the env file' } +$newPassword = New-RotationPassword +$imageBefore = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim() + +if ((Invoke-Grafana $user $oldPassword '/api/user') -ne '200') { + throw 'Current Grafana admin credentials were not accepted before rotation' +} + +$body = @{ + oldPassword = $oldPassword + newPassword = $newPassword + confirmNew = $newPassword +} | ConvertTo-Json -Compress +$rotationStatus = Invoke-Grafana $user $oldPassword '/api/user/password' 'PUT' $body +if ($rotationStatus -ne '200' -and $rotationStatus -ne '204') { + throw "Grafana password API returned an unexpected status: $rotationStatus" +} + +$envBackup = [System.IO.File]::ReadAllBytes($envPath) +try { + Set-EnvValue 'GRAFANA_ADMIN_PASSWORD' $newPassword + Invoke-ComposeQuiet @('--env-file',$EnvFile,'up','-d','--no-deps','--force-recreate','grafana') + + $ready = $false + for ($attempt = 0; $attempt -lt 30; $attempt++) { + if ((Invoke-Grafana $user $newPassword '/api/user') -eq '200') { $ready = $true; break } + Start-Sleep -Seconds 2 + } + if (-not $ready) { throw 'Rotated Grafana credentials were not accepted after container recreate' } + if ((Invoke-Grafana $user $oldPassword '/api/user') -eq '200') { + throw 'Old Grafana password is still accepted after rotation' + } +} catch { + [System.IO.File]::WriteAllBytes($envPath, $envBackup) + $rollbackBody = @{ + oldPassword = $newPassword + newPassword = $oldPassword + confirmNew = $oldPassword + } | ConvertTo-Json -Compress + Invoke-Grafana $user $newPassword '/api/user/password' 'PUT' $rollbackBody | Out-Null + throw +} + +$imageAfter = (& docker inspect --format '{{.Image}}' hla-lab7-grafana-1 2>$null | Out-String).Trim() +if ($imageBefore -ne $imageAfter) { throw 'Grafana image changed during rotation' } +Write-Host 'PASS: Grafana admin password rotated through the API and .env without rebuilding images.' +Write-Host "old_password_accepted_after=false" +Write-Host "new_password_accepted_after=true" +Write-Host "grafana_image=$imageAfter" diff --git a/scripts/rotate-pki-leaf.ps1 b/scripts/rotate-pki-leaf.ps1 new file mode 100644 index 0000000..fb2da88 --- /dev/null +++ b/scripts/rotate-pki-leaf.ps1 @@ -0,0 +1,136 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][string]$Leaf, + [Parameter(Mandatory=$true)][string]$CaName, + [string[]]$UriSan = @(), + [string[]]$DnsName = @(), + [string[]]$IpAddress = @(), + [switch]$ServerAuth, + [switch]$RevokeOld, + [string]$Image = 'nginx:1.27.4-bookworm' +) + +$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." +} + +$pki = Join-Path $projectRoot 'secrets\pki' +$leafDir = Join-Path $pki $Leaf +$caCertificate = Join-Path $pki "$CaName\ca.crt" +$caKey = Join-Path $pki "$CaName\ca.key" +foreach ($path in @($leafDir, $caCertificate, $caKey)) { + if (-not (Test-Path $path)) { throw "Missing PKI input: $path" } +} + +$sanLines = @() +$index = 1 +foreach ($value in $UriSan) { $sanLines += "URI.$index = $value"; $index++ } +$index = 1 +foreach ($value in $DnsName) { $sanLines += "DNS.$index = $value"; $index++ } +$index = 1 +foreach ($value in $IpAddress) { $sanLines += "IP.$index = $value"; $index++ } +if ($sanLines.Count -eq 0) { throw 'At least one SAN value is required for a rotated leaf.' } + +$eku = if ($ServerAuth) { 'serverAuth' } else { 'clientAuth' } +$config = @" +[req] +distinguished_name = dn +prompt = no +[dn] +CN = $Leaf +[v3_leaf] +basicConstraints = critical,CA:FALSE +keyUsage = critical,digitalSignature,keyEncipherment +extendedKeyUsage = $eku +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid,issuer +subjectAltName = @san +[san] +$($sanLines -join "`n") +"@ + +$configDir = Join-Path ([System.IO.Path]::GetTempPath()) ("pki-rotate-" + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $configDir -Force | Out-Null +[System.IO.File]::WriteAllText((Join-Path $configDir 'leaf.cnf'), $config, [System.Text.Encoding]::ASCII) + +function Invoke-Docker([string[]]$Arguments, [switch]$Capture) { + # Windows PowerShell 5 wraps native stderr as terminating errors when + # ErrorActionPreference is Stop; openssl writes progress there. + $previous = $ErrorActionPreference + try { + $ErrorActionPreference = 'Continue' + if ($Capture) { + $output = (& docker @Arguments 2>&1 | Out-String) + } else { + & docker @Arguments 2>&1 | Out-Null + $output = '' + } + $code = $LASTEXITCODE + } finally { + $ErrorActionPreference = $previous + } + if ($code -ne 0) { throw "Docker command failed with exit code $code" } + return $output +} + +function Get-CertificateFingerprint([string]$CertificatePath) { + $relative = $CertificatePath.Substring($pki.Length).TrimStart('\','/').Replace('\','/') + $output = Invoke-Docker @('run','--rm', ` + "--mount=type=bind,source=$pki,target=/pki,readonly", ` + '--entrypoint','sh',$Image,'-c', ` + "openssl x509 -in /pki/$relative -outform DER | sha256sum | cut -d' ' -f1") -Capture + return ($output.Trim() -split "`n")[-1].Trim().ToLowerInvariant() +} + +try { + $revokedDir = Join-Path $pki "revoked\$Leaf" + New-Item -ItemType Directory -Path $revokedDir -Force | Out-Null + Copy-Item (Join-Path $leafDir 'tls.crt') (Join-Path $revokedDir 'tls.crt') -Force + Copy-Item (Join-Path $leafDir 'tls.key') (Join-Path $revokedDir 'tls.key') -Force + Copy-Item (Join-Path $leafDir 'ca.crt') (Join-Path $revokedDir 'ca.crt') -Force + Invoke-Docker @('run','--rm', ` + "--mount=type=bind,source=$pki,target=/pki", ` + '--entrypoint','chmod',$Image,'0644', ` + "/pki/revoked/$Leaf/tls.crt","/pki/revoked/$Leaf/tls.key","/pki/revoked/$Leaf/ca.crt") | Out-Null + $oldFingerprint = Get-CertificateFingerprint (Join-Path $revokedDir 'tls.crt') + + $script = @" +openssl req -new -newkey rsa:3072 -nodes -keyout /pki/$Leaf/tls.key.next -out /pki/$Leaf/tls.csr -config /config/leaf.cnf && +openssl x509 -req -in /pki/$Leaf/tls.csr -CA /pki/$CaName/ca.crt -CAkey /pki/$CaName/ca.key -CAserial /config/ca.srl -CAcreateserial -out /pki/$Leaf/tls.crt.next -days 30 -sha256 -extfile /config/leaf.cnf -extensions v3_leaf && +chmod 0644 /pki/$Leaf/tls.key.next /pki/$Leaf/tls.crt.next && +rm -f /pki/$Leaf/tls.csr +"@ + Invoke-Docker @('run','--rm', ` + "--mount=type=bind,source=$pki,target=/pki", ` + "--mount=type=bind,source=$configDir,target=/config", ` + '--entrypoint','sh',$Image,'-c',$script) | Out-Null + + foreach ($name in 'tls.key.next', 'tls.crt.next') { + if (-not (Test-Path (Join-Path $leafDir $name))) { throw "OpenSSL did not produce $name" } + } + Move-Item -Force (Join-Path $leafDir 'tls.key.next') (Join-Path $leafDir 'tls.key') + Move-Item -Force (Join-Path $leafDir 'tls.crt.next') (Join-Path $leafDir 'tls.crt') + $newFingerprint = Get-CertificateFingerprint (Join-Path $leafDir 'tls.crt') + if ($newFingerprint -eq $oldFingerprint) { throw 'Rotation did not change the leaf certificate' } + + if ($RevokeOld) { + $revocationFile = Join-Path $pki 'revoked-client-sha256.txt' + $lines = if (Test-Path $revocationFile) { + @([System.IO.File]::ReadAllLines($revocationFile)) + } else { @() } + if ($lines -notcontains $oldFingerprint) { + Add-Content -Path $revocationFile -Value $oldFingerprint -Encoding ASCII + } + } + + Write-Host "ROTATED $Leaf (CA $CaName) without rebuilding images." + Write-Host "old_leaf_sha256=$oldFingerprint" + Write-Host "new_leaf_sha256=$newFingerprint" + if ($RevokeOld) { Write-Host "revoked_old_leaf=$oldFingerprint" } +} +finally { + Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue +} diff --git a/scripts/test-openbao-rotation-boundaries.ps1 b/scripts/test-openbao-rotation-boundaries.ps1 new file mode 100644 index 0000000..19ce531 --- /dev/null +++ b/scripts/test-openbao-rotation-boundaries.ps1 @@ -0,0 +1,80 @@ +[CmdletBinding()] +param( + [string]$EnvFile = '.env', + [string]$ApplicationImage = 'hla-lab7-app:local', + [int]$Port = 8443 +) + +$ErrorActionPreference = 'Stop' +$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +Set-Location $projectRoot +$publicCa = Join-Path $projectRoot 'secrets\pki\public-ca\ca.crt' +if (-not (Test-Path -LiteralPath $publicCa)) { throw "Missing public CA: $publicCa" } + +function Invoke-Quiet([scriptblock]$Command) { + $previous = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + $output = & $Command 2>&1 | Out-String + $code = $LASTEXITCODE + } finally { + $ErrorActionPreference = $previous + } + return [pscustomobject]@{ Code = $code; Output = $output } +} + +foreach ($name in 'agent-api.hcl','agent-worker.hcl') { + $config = [System.IO.File]::ReadAllText((Join-Path $projectRoot "infra\openbao\$name")) + if ($config -notmatch 'static_secret_render_interval\s*=\s*"5m"') { throw "$name does not renew rendered secrets every 5 minutes" } + if ($config -notmatch 'exit_on_retry_failure\s*=\s*false') { throw "$name exits when OpenBao retries fail" } +} +$serverConfig = [System.IO.File]::ReadAllText((Join-Path $projectRoot 'infra\openbao\openbao.hcl')) +if ($serverConfig -notmatch 'default_lease_ttl\s*=\s*"15m"' -or + $serverConfig -notmatch 'max_lease_ttl\s*=\s*"1h"') { + throw 'OpenBao lease TTLs are not bounded' +} + +$imageConfig = (Invoke-Quiet { docker image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' $ApplicationImage }).Output +if ($imageConfig -match '(?i)BAO_TOKEN|UNSEAL|ROOT_TOKEN|SECRET_ID') { + throw 'Application image environment contains an operator credential name' +} +Invoke-Quiet { docker 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 .' } | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'Application image contains forbidden secret artifacts' } + +# The operator seals OpenBao (or stops the server) with the unseal shares held +# offline. This script verifies the resulting boundary; it never handles the +# shares itself and never tries to unseal. +$statusDuringSeal = (Invoke-Quiet { docker compose --env-file $EnvFile exec -T openbao bao status }).Output +if ($statusDuringSeal -notmatch 'Sealed\s+true') { + throw 'Run this check while OpenBao is sealed so the boundary is actually exercised' +} + +foreach ($service in 'openbao-agent-api','openbao-agent-worker') { + $running = (Invoke-Quiet { docker inspect --format '{{.State.Running}}' "hla-lab7-$($service)-1" }).Output.Trim() + if ($running -ne 'true') { throw "$service stopped while OpenBao was unavailable" } +} +$agentId = (Invoke-Quiet { docker compose --env-file $EnvFile ps -q openbao-agent-api }).Output.Trim() +$keys = (Invoke-Quiet { docker exec $agentId sh -c 'test -s /run/rendered/runtime.env && cut -d= -f1 /run/rendered/runtime.env | sort | tr "\n" ","' }).Output.Trim() +if ($keys -notmatch 'DATABASE_PASSWORD' -or $keys -notmatch 'REDIS_PASSWORD') { + throw 'Cached rendered runtime secrets are unavailable during the seal test' +} + +$health = Invoke-Quiet { curl.exe -sS -o NUL -w '%{http_code}' --cacert $publicCa --ssl-no-revoke --connect-timeout 5 --max-time 10 "https://localhost:$Port/health/ready" } +if ($health.Output.Trim() -ne '200') { throw 'Application readiness failed while OpenBao was unavailable' } + +$watch = [Diagnostics.Stopwatch]::StartNew() +$fresh = Invoke-Quiet { + docker run --rm --entrypoint messenger-entrypoint ` + -e OPENBAO_RENDERED_ENV=/run/missing/runtime.env ` + -e OPENBAO_STARTUP_TIMEOUT_SECONDS=2 $ApplicationImage +} +$watch.Stop() +if ($fresh.Code -eq 0 -or $fresh.Output -notmatch 'did not render runtime credentials') { + throw 'Fresh startup did not fail closed on a missing rendered secret file' +} +if ($watch.Elapsed.TotalSeconds -gt 10) { throw 'Fresh startup exceeded the bounded fail-closed deadline' } +$elapsed = [math]::Round($watch.Elapsed.TotalSeconds, 1) + +Write-Host 'PASS: OpenBao seal/unavailability does not stop agents or running API; cached runtime secrets keep readiness at 200.' +Write-Host "PASS: fresh startup with no rendered env failed closed in ${elapsed}s (configured deadline 2s)." +Write-Host 'PASS: AppRole token TTL is 15m/1h, templates renew every 5m, and no permanent operator secret is embedded in the image.' diff --git a/scripts/test-rotated-leaf.ps1 b/scripts/test-rotated-leaf.ps1 new file mode 100644 index 0000000..3adb35d --- /dev/null +++ b/scripts/test-rotated-leaf.ps1 @@ -0,0 +1,56 @@ +[CmdletBinding()] +param( + [string]$EnvFile = '.env', + [string]$OldCertificate = 'secrets/pki/revoked/lb/tls.crt', + [string]$OldKey = 'secrets/pki/revoked/lb/tls.key', + [string]$NewCertificate = 'secrets/pki/lb/tls.crt', + [string]$NewKey = 'secrets/pki/lb/tls.key' +) + +$ErrorActionPreference = 'Stop' +$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +Set-Location $projectRoot +foreach ($path in @($OldCertificate, $OldKey, $NewCertificate, $NewKey)) { + if (-not (Test-Path -LiteralPath $path)) { throw "Missing certificate material: $path" } +} + +function Convert-ToContainerPath([string]$Path) { + if ($Path -match '^(secrets[\\/])pki[\\/](.+)$') { return '/run/pki/' + $Matches[2].Replace('\','/') } + return $Path.Replace('\','/') +} +$OldCertificate = Convert-ToContainerPath $OldCertificate +$OldKey = Convert-ToContainerPath $OldKey +$NewCertificate = Convert-ToContainerPath $NewCertificate +$NewKey = Convert-ToContainerPath $NewKey + +foreach ($path in @($OldCertificate, $OldKey, $NewCertificate, $NewKey)) { + if ($path -notlike '/run/pki/*') { throw "Certificate path must be under secrets/pki: $path" } +} + +function Invoke-Probe([string]$Target, [string]$Certificate, [string]$Key) { + $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 -cert ${Certificate} -key ${Key} 2>&1" + $previous = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + return @(& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $probeScript 2>&1) -join "`n" + } finally { + $ErrorActionPreference = $previous + } +} + +$replicas = @(& docker compose --env-file $EnvFile ps -q api) +if ($replicas.Count -lt 2) { throw 'At least two running API replicas are required for rotation evidence' } + +foreach ($replica in $replicas) { + $target = (& docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $replica).Trim() + if ([string]::IsNullOrWhiteSpace($target)) { throw "No internal address found for API replica $replica" } + $oldResult = Invoke-Probe $target $OldCertificate $OldKey + if ($oldResult -notmatch 'HTTP/1.1 403') { + throw "Revoked leaf was accepted by API replica $replica" + } + $newResult = Invoke-Probe $target $NewCertificate $NewKey + if ($newResult -notmatch 'HTTP/1.1 200') { + throw "Rotated leaf was rejected by API replica $replica" + } +} +Write-Host "PASS: $($replicas.Count) API replicas reject the revoked LB leaf with 403 and accept the rotated LB leaf with 200." diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index c2842b3..a121466 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -73,7 +73,7 @@ Operator ── loopback/protected channel ── admin planes | Authorization/password/body попадает в signals | Telemetry не содержит credentials/payload | OTel capture headers/bodies выключен; Collector удаляет auth, bodies, DB parameters/query | Запрос с уникальным canary; поиск в Loki/Tempo/Prometheus/logs → 0 | Новые instrumentation attributes требуют повторного canary-теста | | Image bomb или concurrent uploads исчерпывают worker | Файл и суммарная обработка имеют bounds | 10 MiB limit, pixel limit, semaphore, worker memory budget, timeout/resources | Oversized body → 413; >40M pixels → reject/failed; concurrent test остаётся в limit | Decoder CVE остаются supply-chain риском; нужны scan/upgrade | | Private key/secret попадает в Git, image или app env | Operator secrets не поставляются со skeleton | `.gitignore`, `.dockerignore`, local bootstrap в `secrets/`, OpenBao Agent и отдельные runtime files | Secret scanner, `docker history`, inspect app env не содержат root/unseal/runtime password | Dependency bootstrap passwords пока поступают их контейнерам через Compose env; это остаточный локальный риск | -| OpenBao sealed, приложение использует hardcoded fallback/plaintext | Отказ secret plane не ослабляет auth/TLS | Agent retry, отсутствие app fallback, controlled startup failure без rendered file; TLS не отключается | Seal/stop Bao; новая replica не стартует без файла; после unseal Agent re-auth | Уже запущенное приложение продолжает работать со статическими dependency credentials до restart/их отзыва | +| OpenBao sealed, приложение использует hardcoded fallback/plaintext | Отказ secret plane не ослабляет auth/TLS | Agent retry, отсутствие app fallback, controlled startup failure без rendered file; TLS не отключается | `test-openbao-rotation-boundaries.ps1`: при `Sealed true` агенты Running, render keys сохранены, public health 200; fresh startup без rendered env → exit 1 за 2.8 c при лимите 2 c | Уже запущенное приложение продолжает работать со статическими dependency credentials до restart/их отзыва | ## Lifecycle и инциденты @@ -92,6 +92,8 @@ Operator ── loopback/protected channel ── admin planes - TLS leaf: целевой TTL 30 дней; renewal начинается не позднее 2/3 TTL. CA ротируется overlap-набором trust anchors. - OpenBao service token: целевой TTL 15 min, renewable до max TTL 1 h, затем повторная service authentication. - Static service credential на уровне 3: новая KV version, последовательный reload/restart клиентов, проверка новых соединений, отзыв старой версии. +- Реализованная ротация leaf: `rotate-pki-leaf.ps1` выпускает новый leaf тем же CA без rebuild, архивирует старый комплект, добавляет только его SHA-256 в deny-list; `test-rotated-leaf.ps1` доказывает old 403/new 200 на обеих репликах. Нечитаемый deny-list при явной конфигурации отзывает все client identity. +- Реализованная ротация рабочего secret: `rotate-grafana-admin-password.ps1` меняет пароль через API и `.env`, пересоздаёт только Grafana и проверяет old rejected/new accepted; значения не попадают в логи, Git или образ. ### Компрометация identity @@ -102,7 +104,7 @@ Operator ── loopback/protected channel ── admin planes ### Sealed OpenBao и восстановление -Обычный restart сохраняет storage, но требует operator unseal в принятой ручной модели. Пока sealed, сервисы не получают новые leases, не используют root token и не переходят на `.env` fallback. После unseal agents повторяют auth с backoff, обновляют file-rendered secrets атомарно, приложения пересоздают соединения. RTO и поведение до expiry фиксируются экспериментом. +Обычный restart сохраняет storage, но требует operator unseal в принятой ручной модели. Пока sealed, сервисы не получают новые leases, не используют root token и не переходят на `.env` fallback. После unseal agents повторяют auth с backoff, обновляют file-rendered secrets атомарно, приложения пересоздают соединения. Эксперимент зафиксировал: при `Sealed true` оба Agent остаются Running, кэшированные ключи доступны, public `/health/ready` → 200, а новый контейнер без rendered env завершается за 2.8 c при configured deadline 2 c. TTL токена 15 min/max 1 h и interval шаблона 5 min заданы в конфигурации; `exit_on_retry_failure=false` предотвращает выход Agent из-за временного отказа OpenBao. ### Dependency/image scan diff --git a/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java b/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java index eb37665..1b38a76 100644 --- a/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java +++ b/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java @@ -4,23 +4,42 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.HexFormat; import java.util.List; +import java.util.Set; @Component public class TrustedClientCertificateFilter extends OncePerRequestFilter { private final String allowedUri; + private final Set revokedFingerprints; + @Autowired public TrustedClientCertificateFilter( - @Value("${messenger.mtls.allowed-client-uri:}") String allowedUri) { + @Value("${messenger.mtls.allowed-client-uri:}") String allowedUri, + @Value("${messenger.mtls.revoked-certificates-file:}") String revokedCertificatesFile) { + this(allowedUri, readRevokedFingerprints(revokedCertificatesFile)); + } + + TrustedClientCertificateFilter(String allowedUri, Set revokedFingerprints) { this.allowedUri = allowedUri; + this.revokedFingerprints = Set.copyOf(revokedFingerprints); } @Override @@ -33,7 +52,8 @@ public class TrustedClientCertificateFilter extends OncePerRequestFilter { FilterChain chain) throws ServletException, IOException { X509Certificate[] certificates = (X509Certificate[]) request.getAttribute( "jakarta.servlet.request.X509Certificate"); - if (certificates == null || certificates.length == 0 || !hasAllowedUri(certificates[0])) { + if (certificates == null || certificates.length == 0 + || !hasAllowedUri(certificates[0]) || isRevoked(certificates[0])) { // Do not use sendError: its internal /error dispatch can be intercepted // by Spring Security and turn this identity rejection into an ambiguous 401. response.setStatus(HttpServletResponse.SC_FORBIDDEN); @@ -57,4 +77,30 @@ public class TrustedClientCertificateFilter extends OncePerRequestFilter { return false; } } + + private boolean isRevoked(X509Certificate certificate) { + try { + String fingerprint = HexFormat.of().formatHex( + MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + return revokedFingerprints.contains(fingerprint.toLowerCase(java.util.Locale.ROOT)); + } catch (CertificateEncodingException | NoSuchAlgorithmException e) { + // A leaf we cannot fingerprint cannot be proven unrevoked. + return true; + } + } + + private static Set readRevokedFingerprints(String path) { + if (path == null || path.isBlank()) return Collections.emptySet(); + try { + Set values = new HashSet<>(); + for (String line : Files.readAllLines(Path.of(path), StandardCharsets.UTF_8)) { + String value = line.trim().toLowerCase(java.util.Locale.ROOT); + if (!value.isEmpty() && !value.startsWith("#")) values.add(value); + } + return values; + } catch (IOException e) { + // Fail closed if the revocation list is configured but unreadable. + return Set.of("unreadable-revocation-list"); + } + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b334a3d..b6900ce 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -114,6 +114,7 @@ messenger: role: ${MESSENGER_ROLE:api} mtls: allowed-client-uri: ${MTLS_ALLOWED_CLIENT_URI:} + revoked-certificates-file: ${MTLS_REVOKED_CERTIFICATES_FILE:} storage: postgres password: argon2: diff --git a/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java b/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java index 46553cc..8c1fdc4 100644 --- a/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java +++ b/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java @@ -5,8 +5,12 @@ import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.security.cert.X509Certificate; +import java.util.HexFormat; import java.util.List; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -15,6 +19,7 @@ import static org.mockito.Mockito.when; class TrustedClientCertificateFilterTest { private static final String ALLOWED_URI = "spiffe://hla-lab7/lb"; + private static final byte[] CERTIFICATE_DER = "rotated-lb-leaf".getBytes(StandardCharsets.UTF_8); @Test void rejectsRequestWithoutClientCertificate() throws Exception { @@ -32,19 +37,33 @@ class TrustedClientCertificateFilterTest { @Test void acceptsOnlyTheConfiguredUriSan() throws Exception { - MockHttpServletResponse response = apply(certificate(ALLOWED_URI)); + MockHttpServletResponse response = apply(certificate(ALLOWED_URI), Set.of()); assertEquals(200, response.getStatus()); assertNull(response.getErrorMessage()); } + @Test + void rejectsAllowedUriWhenItsLeafFingerprintIsRevoked() throws Exception { + String fingerprint = HexFormat.of().formatHex( + MessageDigest.getInstance("SHA-256").digest(CERTIFICATE_DER)); + MockHttpServletResponse response = apply(certificate(ALLOWED_URI), Set.of(fingerprint)); + assertEquals(403, response.getStatus()); + assertEquals("no-store", response.getHeader("Cache-Control")); + } + private MockHttpServletResponse apply(X509Certificate certificate) throws Exception { + return apply(certificate, Set.of()); + } + + private MockHttpServletResponse apply(X509Certificate certificate, Set revoked) + throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); if (certificate != null) { request.setAttribute("jakarta.servlet.request.X509Certificate", new X509Certificate[]{certificate}); } MockHttpServletResponse response = new MockHttpServletResponse(); - new TrustedClientCertificateFilter(ALLOWED_URI) + new TrustedClientCertificateFilter(ALLOWED_URI, revoked) .doFilter(request, response, new MockFilterChain()); return response; } @@ -53,6 +72,7 @@ class TrustedClientCertificateFilterTest { X509Certificate certificate = mock(X509Certificate.class); when(certificate.getSubjectAlternativeNames()).thenReturn( List.of(List.of(6, uriSan))); + when(certificate.getEncoded()).thenReturn(CERTIFICATE_DER); return certificate; } }