lab7: исправления по независимому ревью

This commit is contained in:
Vladislav Kunetskiy
2026-11-10 14:22:47 +03:00
parent d1dc6d6b78
commit 30b6672058
18 changed files with 20572 additions and 20366 deletions
+18 -14
View File
@@ -47,29 +47,33 @@ python3 scripts/lab7_scan.py --output evidence/lab7/scans
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke, HTTPS CA/hostname | `make test`; `make test-security` | trusted HTTPS проходит; недоверенный CA отклоняется ошибкой верификации | `evidence/lab7/security.json` (`public_ca_hostname`), `verification.json` |
| Argon2id salt/параметры | `make auth-budget`; `internal/platform/password` | m=19 MiB, t=2, p=1; host-бенчмарк Argon2 p50 15.9 ms, p95 17.5 ms; API login: 120 запросов, p50 5.3 ms, p95 58.8 ms, 429 при исчерпании бюджета; cgroup peak 74–84 MB | `evidence/lab7/auth.json` |
| LB→API обязательный mTLS + identity | `make test-lab7`; `make test-pki` | lb 200; нет cert/чужой CA/неверный URI — TLS rejection; отзыв старого LB отклоняется на свежем соединении | `security.json` (`mtls_and_telemetry_acl`), `native-revocation.json`, `track2.json` |
| Backend TLS и минимальные права | `make test-lab7` | PostgreSQL SQLSTATE 42501 для чужих таблиц; S3 prefix/COPY 403; Redis foreign key NOPERM; broker EXTERNAL ACL; Bao foreign KV/issuer 403 | `security.json` (`database_privileges`, `s3_prefix_acl`, `redis_tls_cache_acl`, `broker_external_acl`, `bao_api_policy`) |
| OpenBao non-dev, scoped, persistent | `securityctl.py up`, `audit-summary`; `make test-lab7` | root token отозван; app использует cert auth; unseal — у оператора; KV/issuer только свои; audit пишет login/issue/revoke/renew | `security.json`, `evidence/lab7/root-crl.json`, `restart-scope.json` |
| Публичный smoke, HTTPS CA/hostname | `make test`; `make test-security` | trusted HTTPS проходит; недоверенный CA отклоняется ошибкой верификации | `evidence/lab7/security.json` (`public_ca_hostname`), `final-verification.txt` |
| Argon2id salt/параметры | `make auth-budget`; `internal/platform/password` | m=19 MiB, t=2, p=1; host-бенчмарк Argon2 p50 14.7 ms, p95 17.0 ms; API login: 120 запросов, p50 5.2 ms, p95 57.6 ms, 429 при исчерпании бюджета; cgroup peak 76–92 MB (after) | `evidence/lab7/auth.json` |
| LB→API обязательный mTLS + identity | `make test-lab7`; `make test-pki` | lb 200; нет cert/чужой CA/неверный URI — TLS rejection; отзыв старого LB отклоняется на свежем соединении | `security.json` (`mtls_and_telemetry_acl`), `track2.json` |
| Backend TLS и минимальные права | `make test-lab7` | PostgreSQL SQLSTATE 42501 для чужих таблиц; S3 GET/PUT/DELETE/COPY по чужому prefix — 403 (worker bucket-level LIST возвращает metadata, задокументировано); Redis foreign key NOPERM; broker EXTERNAL ACL; Bao foreign KV/issuer 403 | `security.json` (`database_privileges`, `s3_prefix_acl`, `redis_tls_cache_acl`, `broker_external_acl`, `bao_api_policy`) |
| OpenBao non-dev, scoped, persistent | `securityctl.py up`, `audit-summary`; `make test-lab7` | root token отозван; app использует cert auth; unseal — у оператора; KV/issuer только свои; audit пишет login/issue/revoke/renew | `security.json` (`bao_api_policy`), `track2.json` (`bootstrap.root_token_revoked`, `actions.bao_audit`), `bao-audit.txt` |
| Контейнеры без privileged/host/socket | `runtime_container_network_isolation` | apps non-root/read_only; из соседнего namespace connection refused; лишние capabilities сняты | `security.json`, `compose.yaml` |
| Rate limit/body limit/ACL/logout/expiry | `make test-lab7`; `make test` | общий 429 + `Retry-After`; чужой чат/вложение недоступны; logout и DB expiry закрывают доступ; forged `X-User-Id` не меняет identity | `security.json` (`shared_rate_limit`, `http_acl_logout_expiry_bounds`, `real_async_pipeline`) |
| Уровень 4: broker и Collector mTLS | `broker_external_acl`, `mtls_and_telemetry_acl` | разные identities; разрешённая роль 200/публикация, запрещённая роль 403, нет cert/чужой CA — TLS rejection | `security.json` |
| Отказ plaintext/чужому CA на backends и telemetry | `make test-lab7` | PostgreSQL/Redis/S3 plaintext-канал отвергнут; S3 с чужим CA — ca_rejected; Loki не содержит sentinel-секретов | `security.json` (`plaintext_refusal`, `credential_log_sentinels`) |
| Уровень 4: rehash, отсутствие утечек, login DoS | `auth-budget`, `credential_log_sentinels` | rehash старого hash при успешном входе; пароли/токены не в логах; бюджет измерен | `auth.json`, `security.json` |
| Уровень 4: ротация secret/leaf, отзыв, expiry/sealed | `make test-pki`; `make test-lab7`; `native-revocation.json` | leaf renewal без пересборки; отзыв старого leaf; sealed Bao закрывает admission; CA prepare→issue→retire с проверкой старой identity | `track2.json`, `native-revocation.json` |
| Уровень 4: rehash, отсутствие утечек, login DoS | `auth-budget`, `credential_log_sentinels`; unit `TestAuthenticateUpgradesHashesWithCAS` | rehash старого hash реализован и покрыт unit-тестом (CAS), runtime-вход с legacy-PHC отдельно не снимался; пароли/токены не в логах; бюджет измерен | `auth.json`, `security.json`, `internal/service/session/service_test.go` |
| Уровень 4: ротация secret/leaf, отзыв, expiry/sealed | `make test-pki`; `make test-lab7` | leaf renewal без пересборки; отзыв старого leaf; sealed Bao закрывает admission; CA prepare→issue→retire с проверкой старой identity | `track2.json` |
| Уровень 4: hardening + scans + threat model | `runtime_container_network_isolation`; `scans/summary.json`; `security/THREAT_MODEL.md` | 13 образов просканированы, все scanner exits 0; достижимых findings в коде приложения нет; остаточные CVE разобраны по применимости | `scans/summary.json`, `security/SCAN_TRIAGE.md`, `THREAT_MODEL.md` |
| Уровень 5, трек 2 | `make test-pki` | 3 изолированных прогона: renewal/expiry/sealed/revocation/CA rollover под нагрузкой; измерены ошибки и восстановление; fallback на plaintext/verify-off отсутствует | `evidence/lab7/track2.json`, `root-crl.json`, `native-revocation.json` |
| Уровень 5, трек 2 | `make test-pki` | 3 изолированных прогона: renewal/expiry/sealed/revocation/CA rollover под нагрузкой; измерены ошибки и восстановление; fallback на plaintext/verify-off отсутствует | `evidence/lab7/track2.json`, `renewer.json`, `bao-audit.txt` |
Примечание: `native-revocation.json`, `root-crl.json`, `verification.json`, `restart-scope.json`, `failover-scope.json`, `sequential-failover.json`, `track2-ca-before.json` и `track2-renewal-before.json` — pre-final fixtures предыдущих прогонов. Финальные заявления подкреплены `track2.json`, `security.json`, `auth.json`, `renewer.json`, `bao-audit.txt`, `resilience-final.txt` и `final-verification.txt`.
**Гипотеза трека 2:** при короткоживущих leaf и трёхфазном CA rollover стенд не имеет fallback на plaintext/verify-off, а окно отказа ограничено рестартом/сменой trust и восстанавливается без потери сообщений, вложений и sessions. Опровержение — любой успешный запрос без проверки TLS, сохранение старой identity после retire или потеря данных после recovery.
### Наблюдаемые отказы и восстановление
| Воздействие | Ожидание | Наблюдение | Время восстановления / потеря |
| --- | --- | --- | --- |
| Рестарт стенда (`make test-persistence ACTION_SCRIPT=scripts/restart.sh`) | сообщение, полные байты вложения и сессия сохраняются | Full attachment bytes, confirmed message and existing session preserved; имена volumes не изменились | данные не потеряны |
| Остановка одной API-реплики (`make test-failover ACTION_SCRIPT=scripts/stop-one.sh`) | вторая реплика продолжает сервис | 93 успешные записи, 0 failed attempts; message/attachment/session сохранены; stateful-сервисы не перезапускались | first recovery 1.36 s (`evidence/lab7/resilience-final.txt`) |
| Остановка одной API-реплики (`make test-failover ACTION_SCRIPT=scripts/stop-one.sh`) | вторая реплика продолжает сервис | 84 успешные записи, 0 failed attempts; message/attachment/session сохранены; stateful-сервисы не перезапускались | first recovery 1.365 s (`evidence/lab7/resilience-final.txt`) |
| Последовательная остановка обеих реплик (`student-tests/replica_failover.py`) | сервис восстанавливается после возврата реплик | 91 и 100 успешных записей, 0 failed; история 191 сообщение, дублей/потерь нет | 1.786 s / 0.889 s |
| Истечение API leaf под нагрузкой | admission закрывается, процесс завершается в bound, затем recovery | ready закрыт; bounded process exit; после issue 1h API восстановлен; сообщение/вложение сохранены | recovery 0.85–1.70 s в прогонах |
| Sealed OpenBao | admission закрывается не позже 60 s freshness; после unseal — recovery | ready закрыт; после unseal API/worker/relay восстановлены; сообщение/вложение сохранены | recovery 1.9–2.1 s |
| Истечение API leaf под нагрузкой | admission закрывается, процесс завершается в bound, затем recovery | ready закрыт; bounded process exit; после issue 1h API восстановлен; сообщение/вложение сохранены | recovery 1.05–2.75 s в прогонах (`track2.json`) |
| Sealed OpenBao | admission закрывается не позже 60 s freshness; после unseal — recovery | ready закрыт; наблюдаемое закрытие 60.5–61.7 s (включая 1 s cadence watchdog); после unseal API/worker/relay восстановлены; сообщение/вложение сохранены | recovery 2.25–6.41 s (`track2.json`) |
| Отзыв старого leaf LB/Collector | свежие и resumption-попытки отклоняются | `tls_certificate_rejected`; новый leaf работает | без потери данных |
| CA rollover prepare→issue→retire | overlap старого trust, затем отказ старой identity и работа нового pipeline | старый leaf проходит в overlap; после retire отклоняется; новый upload/readiness, Bao/Redis/telemetry пути и retained bytes проходят | см. `track2.json` |
| Истечение offline root CRL | CRL обновляется оператором до final 24h | refreshed signed CRL, NextUpdate > 24h; unexpired CRL не перегенерируется; Docker targets не мутируются | без простоя |
@@ -78,9 +82,9 @@ python3 scripts/lab7_scan.py --output evidence/lab7/scans
Методика трека 2: `scripts/lab7_track2.py` создаёт отдельный compose-проект на каждый повтор (свои порты и volumes), поднимает полный стенд, гоняет замкнутый HTTPS-клиент 2 rps и выполняет фазы: baseline → leaf renewal (20 s TTL, watcher) → intentional expiry → recovery → sealed Bao → recovery → LB leaf revoke → worker S3 secret rotation → CA prepare/issue/retire. Для каждой фазы фиксируются HTTP-статусы, ошибки по классам, latency, окна отказа и восстановление. После каждой фазы CA rollover сначала прогоняется полный публичный upload pipeline (retry с 15 s timeout, deadline 180 s), затем проверяются контрактные детали. Ограничения: один Docker Desktop host, single-node PostgreSQL/Redis/RabbitMQ/SeaweedFS/OpenBao, замкнутый клиент — это lifecycle-проба, а не capacity benchmark; оба API leaf намеренно истекают (total outage, не A/B failover); TLS tickets/cache отключены.
Результат трека: `evidence/lab7/track2.json` — 3/3 повторений, `passed: true`. Leaf renewal: по 138–139 запросов на прогон, 0 ошибок, p95 ≈ 17–18 ms. Intentional expiry: наблюдаемое окно 6.4–7.5 s, recovery 0.6–1.6 s; sealed Bao: окно 6.5–7.6 s, recovery 1.8–3.3 s; отзыв LB leaf: окна ≈ 0.5 s; CA prepare/issue/retire: 192.4–196.6 s на фазу, 114–125 ошибок на 380–388 запросов (1–2 connection/TLS, 5–7 HTTP 502, 106–119 HTTP 503 при rolling restart/store reload), затем `final_recovery_control` — 59–60/60 успешных, 0 ошибок. `warm_pipeline` после каждой фазы: 1 попытка, 0 ошибок; retire перепубликовал 19 identities, старый LB отклонён с `TLSV1_ALERT_UNKNOWN_CA`. Ошибки ограничены окнами рестартов и перечислены в `load.observed_outage_windows`; fallback на plaintext/verify-off отсутствует.
Результат трека: `evidence/lab7/track2.json` — 3/3 повторений, `passed: true`. Leaf renewal: по 139–140 запросов на прогон, 0 ошибок, p95 12.9–18.2 ms. Intentional expiry: recovery 1.05–2.75 s; sealed Bao: recovery 2.25–6.41 s; отзыв LB leaf: окна ≈ 0.5 s; CA prepare/issue/retire: 179.4–203.2 s на фазу, 114–153 ошибок на 355–402 запросов (1–2 connection/TLS, 6–8 HTTP 502, 107–144 HTTP 503 при rolling restart/store reload), затем `final_recovery_control` — 60/60 успешных, 0 ошибок. `warm_pipeline` после каждой фазы: 1 попытка, 0 ошибок; retire перепубликовал 19 identities, старый LB отклонён с `TLSV1_ALERT_UNKNOWN_CA`. Ошибки ограничены окнами рестартов и перечислены в `load.observed_outage_windows`; fallback на plaintext/verify-off отсутствует.
Argon2/login: `auth.json` содержит два измерения. Host-бенчмарк `hash_verify`: m=19 MiB, t=2, p=1, p50 15.9 ms, p95 17.5 ms, peak RSS 47.9 MB; это верхняя оценка стоимости Argon2, не API-контейнер. API-проба `api_auth`: 120 запросов, p50 5.3 ms, p95 58.8 ms, 429 при превышении account/source/global лимитов, cgroup peak 74–84 MB. Бюджет дериваций ограничен per-process, `ErrBusy` отдаётся как 429 с `Retry-After`, неизвестный пользователь тратит тот же Argon2-бюджет (dummy verify), rehash не блокирует успешный вход при занятом бюджете. Ограничение: host-бенчмарк не воспроизводит CPU-квоту API; API-проба измеряет реальный контейнер, но включает сеть и rate limiter.
Argon2/login: `auth.json` содержит два измерения. Host-бенчмарк `hash_verify`: m=19 MiB, t=2, p=1, p50 14.7 ms, p95 17.0 ms, peak RSS 48.0 MB; это верхняя оценка стоимости Argon2, не API-контейнер. API-проба `api_auth`: 120 запросов, p50 5.2 ms, p95 57.6 ms, 429 при превышении account/source/global лимитов, cgroup peak 76–92 MB (after). Бюджет дериваций ограничен per-process, `ErrBusy` отдаётся как 429 с `Retry-After`, неизвестный пользователь тратит тот же Argon2-бюджет (dummy verify), ошибка необязательного rehash не блокирует успешный вход. Ограничение: host-бенчмарк не воспроизводит CPU-квоту API; API-проба измеряет реальный контейнер, но включает сеть и rate limiter.
Сканирование: `scans/summary.json` — 13 образов, все scanner exits 0; `govulncheck` не нашёл достижимых symbol/package findings в коде приложения (module-only GO-2026-5932 разобран в triage). Остаточные HIGH/MEDIUM относятся к инфраструктурным образам (Grafana/Loki и др.) и ограничены сетевыми границами, non-root, resource limits и отсутствием публикации; детали и residual risk — в `security/SCAN_TRIAGE.md`.
@@ -93,6 +97,6 @@ Argon2/login: `auth.json` содержит два измерения. Host-бе
- CA private key/unseal shares — offline у оператора; автоматизация их хранения не реализована и не заявляется.
- Модель оператора учебная: root key и 2-of-3 unseal shares лежат в одном operator-only каталоге на том же хосте (0700/0600), а operator-сертификат по политике эквивалентен root. Это не HSM и не раздельное хранение долей; отзыв root token — defense-in-depth, а не граница против скомпрометированного оператора.
- `jobctl`/миграции используют DB-роль оператора; отдельная least-privilege migration role — production-улучшение, не заявленное здесь.
- TLS-аудит покрывает заявленные mTLS/ACL-границы и negative TLS-проверки, но не содержит отдельного plaintext-refusal теста для PostgreSQL/Redis/S3 и sentinel-скана Loki/Tempo; это остаточный пробел, перечисленный в threat model.
- TLS-аудит покрывает заявленные mTLS/ACL-границы, plaintext-refusal для PostgreSQL/Redis/S3 и sentinel-скан Loki; Tempo-атрибуты и historic deleted logs не text-сканируются. Это остаточный пробел, перечисленный в threat model.
- `make renewer` — host-side loop под supervisor; в production его место занимает оркестратор/короткоживущие workload identities.
- Следующие шаги: HA stateful-слоя, динамические DB credentials, автоматическая ротация backend secrets по TTL, более строгий контроль первого bootstrap root of trust.
+1 -1
View File
@@ -222,7 +222,7 @@ func run(
ReadTimeout: cfg.Server.ReadTimeout,
BaseContext: func(net.Listener) context.Context { return ctx },
}
healthServer := localHealthServer(ctx, health.New(pingers...), loader.VerifyTrust)
healthServer := localHealthServer(ctx, health.New(pingers...), loader.VerifyTrustExact)
defer func() {
err = errors.Join(err, finish(ctx, manager, func(shutdownCtx context.Context) error {
results := make(chan error, 2)
+1 -1
View File
@@ -14,7 +14,7 @@ x-hardened: &hardened
read_only: true
group_add: ["10001"]
tmpfs:
- /tmp:rw,noexec,nosuid,size=64m,mode=1777
- /tmp:rw,noexec,nosuid,size=128m,mode=1777
logging: *log
stop_grace_period: 40s
restart: unless-stopped
+7 -4
View File
@@ -11,7 +11,8 @@ Default leaf TTL — 1h, максимум PKI role — 1h; host-side `make renew
выпускает новые leaf каждые 30 минут и синхронизирует CRL; исследовательский renewal/expiry
использует 20s. Cert-auth tokens: 60s, max/explicit max300s. KV freshness у Go
приложения — 60s, независимо от срока leaf и token; admission закрывается за1s
до ближайшего deadline. Backend KV passwords/SigV4 keys статические и живут до
до ближайшего deadline (наблюдаемое закрытие при sealed Bao: 60.5–61.7s с учётом
1s cadence watchdog). Backend KV passwords/SigV4 keys статические и живут до
явной ротации — это не динамические60s credentials. Session TTL3600s;
server хранит только SHA-256 token hash.
@@ -20,9 +21,9 @@ server хранит только SHA-256 token hash.
| Клиент → ingress/LB | `https://localhost:8443`, TLS, Bearer | DNS SANlocalhost; без clientcert. LB заменяет forwarding headers и удаляет X-User-Id | LB leaf; пользовательская session3600s/logout/expiry | `make test test-security`; `public_ca_hostname`, `http_acl_logout_expiry_bounds`, `shared_rate_limit` |
| LB → все API-реплики | `api-replica:8080`, native mTLS | LB проверяет SANapi-replica/CA/CRL; Go server требует точный URI`spiffe://mtusi/lb` | Atomic leaf/CRL reload Go; trust changes restart; tickets/cache off | `mtls_and_telemetry_acl`: lb200; absent/wrongCA/wrongURI TLS拒绝; `make test-pki` oldLB revoke/retire |
| API/worker/relay → PostgreSQL | `postgres:5432`, native TLS+SCRAM, verify-full | Раздельные messenger_api/worker/relay roles; no superuser/DDL. Worker/relay не читают users/sessions/messages | Статический password в ownKV; connection lifetime30s; credentials change → bounded restart | `database_privileges`: SQLSTATE42501; `make integration-test` actual nativeTLS DB suites |
| API/worker → S3 | `https://seaweedfs:8333`, native TLS+SigV4 | API stagingRead/Write, finalRead; worker managed-prefixRead/Write+bucketList; foreign prefixes/buckets403 | Static keys until explicitrotation; role-specific ownKV. No claim of required clientcert on S3HTTP | `s3_prefix_acl`: GET/PUT/DELETE/COPY+fullreadback; `make test-presign test-queue`; workerkeyrotation inPKIstudy |
| API/worker → S3 | `https://seaweedfs:8333`, native TLS+SigV4 | API stagingRead/Write, finalRead; worker managed-prefixRead/Write+bucketList; foreign GET/PUT/DELETE/COPY/bucket 403, worker bucket-level LIST returns managed metadata (documented limitation) | Static keys until explicitrotation; role-specific ownKV. No claim of required clientcert on S3HTTP | `s3_prefix_acl`: GET/PUT/DELETE/COPY+fullreadback; `make test-presign test-queue`; workerkeyrotation inPKIstudy |
| Relay/API outbox/worker → broker | `broker:5671`, native mTLS/EXTERNAL-only | API commits DBoutbox, relay publishes onlyattachments.jobs; worker consumes onlyattachment.process.v1. First DNS SAN principal, anchored broker ACL | Leaf+broker user permissions; nativeprincipal revoke distinct from serial CRL | `broker_external_acl`: positive relaypublish/workerconsume; opposite/topology/wrongDNS403, no-cert/wrongCA TLS rejection |
| API/worker/relay → Collector | `otel-collector:4318`, mTLS gateway → loopback14318 | Exact CNapi/worker/relay and POST/v1/{traces,metrics,logs}; unknownCN/verb/path denied | Gateway loads CA/CRL atstartup; revoke/rollover reloads and drains | `mtls_and_telemetry_acl`: api200, lb403, missing/wrongCA rejection; full `make test-observability` |
| API/worker/relay → Collector | `otel-collector:4318`, mTLS gateway → loopback14318 | Exact CNapi/worker/relay and POST/v1/{traces,metrics,logs}; unknownCN/verb/path denied | Gateway loads CA/CRL atstartup; revoke/rollover restarts gateways; app pools are not claimed drained | `mtls_and_telemetry_acl`: api200, lb403, missing/wrongCA rejection; full `make test-observability` |
| Collector → telemetry backends | Loki`https://loki:3100`; TempoGRPCS`tempo:4437` | CollectorCN onlylogpush/OTLP; no dataquery. Native hops127.0.0.1:13100/14317 | Distinct collectorleaf; fixedsingletenantfake | `mtls_and_telemetry_acl` collectorquery403; actual traces/logs in `make test-observability` |
| Grafana → data sources | Prometheus9090/Loki3100/Tempo3200, HTTPS/mTLS | GrafanaCN query allowlist; push/delete/admin/reload forbidden; CA+hostname verified | Ownleaf in secureJsonData rendered outsideGit; rotation rerenders/restarts | `mtls_and_telemetry_acl` forbiddenwrite403; Grafana/dataSources/TraceQL correlation intelemetrygate |
| API/worker/relay → OpenBao | `https://openbao:8200`, verifiedTLS+cert-auth | Authrole checks CN+URI; ownsecret/data/<role> and ownpki/issue/<role> only; no root/defaultpolicy | Token60s/max300s; cert reauth; KVfresh60s; independentleafdeadline | `bao_api_policy`: ownKV200, foreignKV/issuer/policyadmin403; `make test-pki` renewal/expiry/recovery |
@@ -63,7 +64,9 @@ by apps, `observability` by telemetry, `edge` by their TLS owners.
4. `make pki-renew ROLE=api CERT_TTL=1h` and `renew-watch` use owncert-auth. Token
renewal cannot renew theleaf. Missing/expired/revoked material fails closed.
5. `securityctl.py revoke ROLE --serial SERIAL`: publishes issuer-signed CRLs,
updates BaoauthCRLs, thenreloads/drains nativeCRL-consumingHAProxy gateways.
updates BaoauthCRLs, then restarts native CRL-consuming HAProxy gateways.
Existing application TLS/DB/S3/broker pools are not claimed to be drained;
only fresh/resumption attempts are measured.
Go verifies currentCRLs onfreshconnections. Principalcompromise also requires
backendcredential/token/authrole disable; RabbitMQ EXTERNAL user/connection
revocation is separate and not falsely represented by CRLfileupdate.
+1449 -1449
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
{"audit_events": {"update auth/cert/login": 1658, "update pki/issue/api": 18, "update pki/issue/worker": 34, "update pki/issue/relay": 12, "update pki/issue/lb": 14, "update pki/issue/postgres": 12, "update pki/issue/redis": 12, "update pki/issue/s3": 12, "update pki/issue/broker": 12, "update pki/issue/collector": 14, "update pki/issue/prometheus": 14, "update pki/issue/loki": 14, "update pki/issue/tempo": 14, "update pki/issue/grafana": 14, "update pki/issue/openbao": 14, "update pki/issue/operator": 14, "update auth/token/renew-self": 8746, "update pki/revoke": 10, "update pki/issue/rogue": 4}, "raw_credentials_exported": false}
+14
View File
@@ -0,0 +1,14 @@
2026-11-10, final image mtusi-messenger:lab7 (working tree -> lab7 branch)
go test ./... PASS
make lint PASS, 0 issues
make check PASS (offline structure/Python)
make validate PYTHON=.venv/bin/python PASS (OpenAPI 3.1 + JSON Schema)
make test PASS (public HTTPS smoke)
make test-security PASS (trusted HTTPS; untrusted CA rejected)
make test-lab7 14/14 security groups passed
make test-pki 3/3 repetitions passed
make auth-budget measured (hash_verify + api_auth)
make renew-once 15 roles + CRL sync passed
make test-persistence ACTION_SCRIPT=scripts/restart.sh PASS
make test-failover ACTION_SCRIPT=scripts/stop-one.sh PASS (93 writes, 0 failed, 1.36 s)
python3 scripts/check_evidence.py PASS (no obvious secrets/signed URLs/tokens)
+16 -16
View File
@@ -1,81 +1,81 @@
{
"timestamp": "2026-11-10T07:56:32.713259+00:00",
"timestamp": "2026-11-10T11:14:31.210330+00:00",
"ttl": "1h",
"roles": {
"api": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"api\", \"serial_number\": \"162d336ac64bf588cb605c18a7dfa5da2ba14770\", \"not_after\": \"Nov 10 08:56:32 2026 GMT\"}"
"output": "{\"role\": \"api\", \"serial_number\": \"1aa48f2c79560ee6255a712c07546a1e2674bd3b\", \"not_after\": \"Nov 10 12:14:31 2026 GMT\"}"
},
"worker": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"worker\", \"serial_number\": \"59ea998e72169b9ffd2ccf321b900bba95eee4a2\", \"not_after\": \"Nov 10 08:56:33 2026 GMT\"}"
"output": "{\"role\": \"worker\", \"serial_number\": \"26be7b87f0b59ce4afaaa7025e64f7a14f83ad64\", \"not_after\": \"Nov 10 12:14:31 2026 GMT\"}"
},
"relay": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"relay\", \"serial_number\": \"050c0d78612bc04f8deb11cbb6b94c803ec676ef\", \"not_after\": \"Nov 10 08:56:33 2026 GMT\"}"
"output": "{\"role\": \"relay\", \"serial_number\": \"56db38bc020935548ed33112df3e4872753fb5b1\", \"not_after\": \"Nov 10 12:14:32 2026 GMT\"}"
},
"lb": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"lb\", \"serial_number\": \"4cfeb215b9c8e2b0eef72160b7d4082814acc91a\", \"not_after\": \"Nov 10 08:56:33 2026 GMT\"}"
"output": "{\"role\": \"lb\", \"serial_number\": \"1f4dd141b7245ead56b2b76f30de0ae5c2f08b60\", \"not_after\": \"Nov 10 12:14:32 2026 GMT\"}"
},
"postgres": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"postgres\", \"serial_number\": \"204a420c319906ee249d192fbd773ccf1eef8525\", \"not_after\": \"Nov 10 08:56:34 2026 GMT\"}"
"output": "{\"role\": \"postgres\", \"serial_number\": \"2c22edc594ad37460d218aff16744a1e1eabab8a\", \"not_after\": \"Nov 10 12:14:33 2026 GMT\"}"
},
"redis": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"redis\", \"serial_number\": \"0c5b5d7282d991ffcc914249ff2b3234da8faca0\", \"not_after\": \"Nov 10 08:56:35 2026 GMT\"}"
"output": "{\"role\": \"redis\", \"serial_number\": \"1fe0f04dc1406f8504cc1e276bef84d75b9ba7d6\", \"not_after\": \"Nov 10 12:14:33 2026 GMT\"}"
},
"s3": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"s3\", \"serial_number\": \"219d03c95951446fe4e8bd2c17cf6c2b70db180d\", \"not_after\": \"Nov 10 08:56:35 2026 GMT\"}"
"output": "{\"role\": \"s3\", \"serial_number\": \"500905f19677e271be1123b81312e333c837df77\", \"not_after\": \"Nov 10 12:14:34 2026 GMT\"}"
},
"broker": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"broker\", \"serial_number\": \"0f5081d2cf86907ecbc441e10d2af1d8267fb7bd\", \"not_after\": \"Nov 10 08:57:01 2026 GMT\"}"
"output": "{\"role\": \"broker\", \"serial_number\": \"68673bd02eb82a061229fb567a81827a553b02de\", \"not_after\": \"Nov 10 12:14:45 2026 GMT\"}"
},
"collector": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"collector\", \"serial_number\": \"4607c993a50af826cde8a4315331c8624aef1702\", \"not_after\": \"Nov 10 08:57:13 2026 GMT\"}"
"output": "{\"role\": \"collector\", \"serial_number\": \"69bfc8ed94a3176a23706d6b04c535e52de70f07\", \"not_after\": \"Nov 10 12:14:57 2026 GMT\"}"
},
"prometheus": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"prometheus\", \"serial_number\": \"743c80e8de6cb6d51b8c1155b92d7f48be345ac7\", \"not_after\": \"Nov 10 08:57:13 2026 GMT\"}"
"output": "{\"role\": \"prometheus\", \"serial_number\": \"0ae5d6a037b34083d50e230753c1303d3a995042\", \"not_after\": \"Nov 10 12:15:28 2026 GMT\"}"
},
"loki": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"loki\", \"serial_number\": \"62f37ab0ac4eca0d85a8db5eb844209a7cba6340\", \"not_after\": \"Nov 10 08:57:14 2026 GMT\"}"
"output": "{\"role\": \"loki\", \"serial_number\": \"02ccff65b5564f63b1f079bdc113bdc3e09d0a5f\", \"not_after\": \"Nov 10 12:15:28 2026 GMT\"}"
},
"tempo": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"tempo\", \"serial_number\": \"5f446da237e9e07c67db3ba7887886ad6ed99747\", \"not_after\": \"Nov 10 08:57:16 2026 GMT\"}"
"output": "{\"role\": \"tempo\", \"serial_number\": \"2f934d2031a9168bd54e5d27194f5f9b97d10516\", \"not_after\": \"Nov 10 12:15:30 2026 GMT\"}"
},
"grafana": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"grafana\", \"serial_number\": \"601cb9ceacbde1d34e4d2ec959c769d1db506f16\", \"not_after\": \"Nov 10 08:57:19 2026 GMT\"}"
"output": "{\"role\": \"grafana\", \"serial_number\": \"2bd436cc066dbd03ec24d900e36a5aa8cd0857e8\", \"not_after\": \"Nov 10 12:15:33 2026 GMT\"}"
},
"openbao": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"openbao\", \"serial_number\": \"3ca03157e464ca40bed9321b187805e9df970e29\", \"not_after\": \"Nov 10 08:57:20 2026 GMT\"}"
"output": "{\"role\": \"openbao\", \"serial_number\": \"18bf225b8d809f02b344f0b1f0e53bfb6f5e50f5\", \"not_after\": \"Nov 10 12:15:34 2026 GMT\"}"
},
"operator": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"operator\", \"serial_number\": \"346438665915e9c02da93b59918763d6c042440d\", \"not_after\": \"Nov 10 08:57:24 2026 GMT\"}"
"output": "{\"role\": \"operator\", \"serial_number\": \"1466d3f2b333fe21138e4886d4e57ccc845d07f0\", \"not_after\": \"Nov 10 12:15:38 2026 GMT\"}"
}
},
"crls": {
+1 -1
View File
@@ -3,5 +3,5 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
{"observed_instances_before": 2, "successful_writes": 93, "failed_attempts": 0, "first_recovery_seconds": 1.36}
{"observed_instances_before": 2, "successful_writes": 84, "failed_attempts": 0, "first_recovery_seconds": 1.365}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+53 -53
View File
@@ -15,7 +15,7 @@
},
"name": "public_ca_hostname",
"passed": true,
"seconds": 0.051
"seconds": 0.027
},
{
"classification": "passed",
@@ -37,12 +37,12 @@
},
"collector_api": {
"classification": "http_response",
"serial": "490E552FB82974E56757F142888CFDA7AAD6C312",
"serial": "69BFC8ED94A3176A23706D6B04C535E52DE70F07",
"status": 200
},
"collector_lb": {
"classification": "http_response",
"serial": "490E552FB82974E56757F142888CFDA7AAD6C312",
"serial": "69BFC8ED94A3176A23706D6B04C535E52DE70F07",
"status": 403
},
"collector_wrong_ca_client": {
@@ -51,32 +51,32 @@
},
"lb": {
"classification": "http_response",
"serial": "0155EAEEF71E5999CA92C032A92DDA01529D5EEB",
"serial": "1AA48F2C79560EE6255A712C07546A1E2674BD3B",
"status": 200
},
"loki_collector_route": {
"classification": "http_response",
"serial": "7F2B3167B45A2D4B63832E8E0C44E392E18A6DDF",
"serial": "02CCFF65B5564F63B1F079BDC113BDC3E09D0A5F",
"status": 403
},
"loki_grafana_route": {
"classification": "http_response",
"serial": "7F2B3167B45A2D4B63832E8E0C44E392E18A6DDF",
"serial": "02CCFF65B5564F63B1F079BDC113BDC3E09D0A5F",
"status": 403
},
"otel-collector_api_route": {
"classification": "http_response",
"serial": "490E552FB82974E56757F142888CFDA7AAD6C312",
"serial": "69BFC8ED94A3176A23706D6B04C535E52DE70F07",
"status": 403
},
"prometheus_grafana_route": {
"classification": "http_response",
"serial": "6029AFC83F7F9D0A57FF8B90F5A0C2750DDD8C64",
"serial": "0AE5D6A037B34083D50E230753C1303D3A995042",
"status": 403
},
"tempo_prometheus_route": {
"classification": "http_response",
"serial": "32371E0C6D4C3A2E5F2D47ECA5CEC729B3AC37F5",
"serial": "2F934D2031A9168BD54E5D27194F5F9B97D10516",
"status": 403
},
"wrong_uri": {
@@ -86,7 +86,7 @@
},
"name": "mtls_and_telemetry_acl",
"passed": true,
"seconds": 5.617
"seconds": 5.619
},
{
"classification": "passed",
@@ -135,7 +135,7 @@
},
"name": "broker_external_acl",
"passed": true,
"seconds": 3.922
"seconds": 3.914
},
{
"classification": "passed",
@@ -150,7 +150,7 @@
},
"name": "bao_api_policy",
"passed": true,
"seconds": 0.422
"seconds": 0.437
},
{
"classification": "passed",
@@ -179,7 +179,7 @@
},
"name": "seaweed_auxiliary_mtls",
"passed": true,
"seconds": 1.962
"seconds": 1.945
},
{
"classification": "passed",
@@ -191,7 +191,7 @@
},
"name": "redis_tls_cache_acl",
"passed": true,
"seconds": 0.369
"seconds": 0.412
},
{
"classification": "passed",
@@ -235,7 +235,7 @@
},
"name": "database_privileges",
"passed": true,
"seconds": 2.322
"seconds": 2.329
},
{
"classification": "passed",
@@ -304,7 +304,7 @@
},
"name": "s3_prefix_acl",
"passed": true,
"seconds": 0.704
"seconds": 0.733
},
{
"classification": "passed",
@@ -333,7 +333,7 @@
},
"name": "plaintext_refusal",
"passed": true,
"seconds": 1.948
"seconds": 1.92
},
{
"classification": "passed",
@@ -348,25 +348,25 @@
},
"name": "http_acl_logout_expiry_bounds",
"passed": true,
"seconds": 0.212
"seconds": 0.214
},
{
"classification": "passed",
"details": {
"attachment_id": "01a1c475-3caf-79fb-9773-48f42dac83a1",
"message_id": "01a1c475-3f41-70c2-ae58-5cdd189b49a8",
"attachment_id": "01a1c531-83ba-7adc-96f9-631390aaf0db",
"message_id": "01a1c531-8789-7a2b-ab28-2cdcd2e49aa9",
"status": "ready"
},
"name": "real_async_pipeline",
"passed": true,
"seconds": 0.664
"seconds": 0.992
},
{
"classification": "passed",
"details": {
"instances": [
"5ac7c7f4b4c1",
"c7f052699205"
"b5de44cc1680",
"c534d1225a79"
],
"retry_after": [
59,
@@ -392,35 +392,35 @@
},
"name": "shared_rate_limit",
"passed": true,
"seconds": 0.186
"seconds": 0.196
},
{
"classification": "passed",
"details": {
"containers_scanned": [
"44090eb99929",
"2af89a00f783",
"c12c8d58df88",
"1e262ec4cb1b",
"a79377c4bbbc",
"069ea30589fa",
"777189bb5cd5",
"5e3ba57943d6",
"0b631f460215",
"5b0de6ed0103",
"15dd9970ddd4",
"cd7d6970581b",
"11798cd9ae8c",
"b5de44cc1680",
"11f3801cb11f",
"274ce8478fdd",
"c534d1225a79",
"a0c8dd6b20a3",
"7984632bd709",
"158d63b7ac3c",
"f0227fea8781",
"62a070cbf1c7",
"21bab268e79a",
"01c1b15ae56e",
"1da94197b83d",
"c10b6dd1a9cb",
"9bc2d57bbc8a",
"41065fa7a807",
"92a23aef5975",
"3cda591b3fca",
"c29aa8ecccfb",
"85695e9822f0",
"eacebab2aafd",
"6ef95f7e9f28",
"085529fc6b9f",
"f652bb3c38e6",
"f4948c9a7a7e",
"c7f052699205",
"5ac7c7f4b4c1",
"946bc77e25af",
"cf186c1ce356",
"1df4bf079b3c",
"9770e79a39ef",
"8c8145d0204a"
"1df4bf079b3c"
],
"limitations": [
"Scans retained container logs and Loki streams with service_name; Tempo attributes and historic deleted logs are not text-scanned."
@@ -430,7 +430,7 @@
},
"name": "credential_log_sentinels",
"passed": true,
"seconds": 0.825
"seconds": 0.929
},
{
"classification": "passed",
@@ -438,26 +438,26 @@
"applications": {
"api": [
{
"id": "c7f052699205",
"id": "b5de44cc1680",
"readonly": true,
"running_uid_nonzero": true
},
{
"id": "5ac7c7f4b4c1",
"id": "c534d1225a79",
"readonly": true,
"running_uid_nonzero": true
}
],
"relay": [
{
"id": "f652bb3c38e6",
"id": "274ce8478fdd",
"readonly": true,
"running_uid_nonzero": true
}
],
"worker": [
{
"id": "f4948c9a7a7e",
"id": "11f3801cb11f",
"readonly": true,
"running_uid_nonzero": true
}
@@ -505,9 +505,9 @@
},
"name": "runtime_container_network_isolation",
"passed": true,
"seconds": 2.044
"seconds": 2.188
}
],
"study": "lab7-security",
"timestamp": "2026-11-10T07:56:23.609085+00:00"
"timestamp": "2026-11-10T11:22:03.202717+00:00"
}
+18893 -18779
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -16,6 +16,7 @@ listener "tcp" {
tls_client_ca_file = "/run/identity/current/ca.crt"
tls_min_version = "tls12"
tls_disable_client_certs = false
tls_require_client_cert = true
}
audit "file" "file" {
+42 -8
View File
@@ -274,6 +274,24 @@ func (l *Loader) verifyOwnChain(cert *tls.Certificate) ([][]*x509.Certificate, e
return chains, nil
}
func (l *Loader) mountedRoots(files Files) (map[string]struct{}, error) {
trust, err := secretfile.Read(files.CA)
if err != nil {
return nil, fmt.Errorf("read tls trust: %w", err)
}
issuers, err := parseCertificates(trust)
if err != nil {
return nil, err
}
current := map[string]struct{}{}
for _, cert := range issuers {
if bytes.Equal(cert.RawIssuer, cert.RawSubject) {
current[string(cert.Raw)] = struct{}{}
}
}
return current, nil
}
func (l *Loader) checkTrust(files Files) error {
trust, err := secretfile.Read(files.CA)
if err != nil {
@@ -282,16 +300,10 @@ func (l *Loader) checkTrust(files Files) error {
if bytes.Equal(trust, l.trust) {
return nil
}
issuers, err := parseCertificates(trust)
current, err := l.mountedRoots(files)
if err != nil {
return err
}
current := map[string]struct{}{}
for _, cert := range issuers {
if bytes.Equal(cert.RawIssuer, cert.RawSubject) {
current[string(cert.Raw)] = struct{}{}
}
}
// Adding roots (prepare overlap) is safe before a restart; removing a
// startup root requires a restart and fails closed.
for raw := range l.trustRoots {
@@ -302,8 +314,30 @@ func (l *Loader) checkTrust(files Files) error {
return nil
}
// VerifyTrustExact closes readiness unless the mounted roots equal the startup
// roots. A superset is safe for handshakes but not for the frozen TLS pools.
func (l *Loader) VerifyTrustExact() error {
files, err := l.files.snapshot()
if err != nil {
return err
}
current, err := l.mountedRoots(files)
if err != nil {
return err
}
if len(current) != len(l.trustRoots) {
return errors.New("tls trust differs from startup; restart required")
}
for raw := range l.trustRoots {
if _, ok := current[raw]; !ok {
return errors.New("tls trust differs from startup; restart required")
}
}
return nil
}
// VerifyTrust reports whether the mounted trust bundle still contains every
// root loaded at startup. Readiness uses it to retire un-restarted replicas.
// root loaded at startup. Kept for handshake-level subset checks.
func (l *Loader) VerifyTrust() error {
return l.verifyTrust()
}
+12 -13
View File
@@ -56,24 +56,23 @@ func (s *Service) Authenticate(ctx context.Context, username, plain string) (dom
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
}
if verified.NeedsRehash {
hash, err := password.Hash(plain)
if errors.Is(err, password.ErrBusy) {
// The credential is valid; a contended optional upgrade must not
// turn a successful login into a failure.
return credentials.User, nil
}
if err != nil {
return domain.User{}, fmt.Errorf("rehash password: %w", err)
}
// A concurrent upgrade wins the CAS; it must not invalidate this login.
if _, err := s.sessions.UpdatePasswordHash(ctx, credentials.User.ID, credentials.PasswordHash, hash); err != nil {
return domain.User{}, fmt.Errorf("upgrade password: %w", err)
}
// Optional upgrade: a busy derivation or transient write error must not
// turn an already verified login into a failure.
s.rehash(ctx, credentials.User.ID, credentials.PasswordHash, plain)
}
return credentials.User, nil
}
func (s *Service) rehash(ctx context.Context, userID uuid.UUID, oldHash, plain string) {
hash, err := password.Hash(plain)
if err != nil {
return
}
// A concurrent upgrade wins the CAS; both outcomes are acceptable.
_, _ = s.sessions.UpdatePasswordHash(ctx, userID, oldHash, hash)
}
func (s *Service) Resolve(ctx context.Context, raw string) (domain.User, error) {
hash, err := s.tokens.Hash(raw)
if err != nil {
+4 -4
View File
@@ -177,16 +177,16 @@ func (s *ServiceSuite) TestWrongLegacyPasswordDoesNotUpgrade() {
s.sessions.AssertNotCalled(s.T(), "UpdatePasswordHash", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
}
func (s *ServiceSuite) TestPasswordUpgradeFailureIsNotAuthenticationFailure() {
func (s *ServiceSuite) TestPasswordUpgradeFailureDoesNotBlockLogin() {
oldHash := obsoleteHash("secret-password-123", false)
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
s.sessions.On("UpdatePasswordHash", mock.Anything, s.user.ID, oldHash, mock.Anything).
Return(false, domain.ErrUnavailable).Once()
_, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
s.Require().ErrorIs(err, domain.ErrUnavailable)
s.Require().NotErrorIs(err, domain.ErrUnauthenticated)
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
s.Require().NoError(err)
s.Equal(s.user, got)
}
func obsoleteHash(plain string, legacy bool) string {
+25 -2
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
import os
from pathlib import Path
import re
import secrets
import ssl
import time
@@ -156,7 +157,7 @@ subjectAltName={san}
restarted_listener = False
for role in ('operator', 'openbao'):
certificate = self.env.identity(role) / 'tls.crt'
valid = self.env.run(['openssl', 'x509', '-checkend', '30', '-noout',
valid = self.env.run(['openssl', 'x509', '-checkend', '300', '-noout',
'-in', str(certificate)], check=False).returncode == 0
if valid:
continue
@@ -331,6 +332,19 @@ authorityKeyIdentifier=keyid,issuer
next_renewal = time.time() + max(1, (expiry - time.time()) / 2)
time.sleep(interval)
def crl_contains_serial(self, bundle: str, normalized: str) -> bool:
wanted = normalized.lstrip('0').lower()
for block in re.findall(r'-----BEGIN X509 CRL-----.*?-----END X509 CRL-----', bundle, re.S):
output = self.env.run(['openssl', 'crl', '-noout', '-text'], data=block,
check=False).stdout
for line in output.splitlines():
if 'Serial Number:' not in line:
continue
value = line.split(':', 1)[1].strip().replace(':', '').lower().lstrip('0')
if value == wanted:
return True
return False
def revoke(self, role: str, serial: str) -> dict:
normalized = serial.replace(':', '').replace('-', '').lower()
if not normalized or any(ch not in '0123456789abcdef' for ch in normalized):
@@ -344,7 +358,10 @@ authorityKeyIdentifier=keyid,issuer
# exposes rotation as GET /pki/crl/rotate (POST is 405 here).
client.request('GET', 'pki/crl/rotate', token=token)
self.sync_crls(client, token)
return {'role': role, 'revoked_serial': normalized, 'crls_updated': True, 'crl_rotated': True}
if not self.crl_contains_serial(self.cached_crls(), normalized):
raise OperationError('published CRL does not contain the revoked serial')
return {'role': role, 'revoked_serial': normalized, 'crls_updated': True,
'crl_rotated': True, 'crl_contains_serial': True}
def prepare_rollover(self) -> dict:
if self.state.get('next_root'):
@@ -405,6 +422,12 @@ authorityKeyIdentifier=keyid,issuer
continue
if self.certificate_name(current / 'tls.crt', 'issuer') not in active_issuers:
raise OperationError('retire blocked: leaf is not from the active issuer: ' + role)
verified = self.env.run(['openssl', 'verify',
'-CAfile', str(root_dir / 'ca.crt'),
'-untrusted', str(root_dir / 'intermediate.crt'),
str(current / 'tls.crt')], check=False)
if verified.returncode:
raise OperationError('retire blocked: leaf chain does not verify: ' + role)
client = BaoClient(self.env)
token = client.login()
self.state['trust_roots'] = [self.state['active_root']]
+16 -5
View File
@@ -234,7 +234,7 @@ user operator on >{operator_password} ~* &* +@all
def unseal(self) -> dict:
deadline = time.monotonic() + 60
client = BaoClient(self.env, None)
client = BaoClient(self.env)
while True:
try:
status = client.request('GET', 'sys/seal-status')
@@ -311,7 +311,7 @@ user operator on >{operator_password} ~* &* +@all
root_token = material.get('root_token')
if root_token:
self.env.redactions.add(root_token)
client = BaoClient(self.env, None)
client = BaoClient(self.env)
token = root_token
else:
client = BaoClient(self.env)
@@ -437,12 +437,20 @@ END $$;
certificate = self.env.identity(role) / 'tls.crt'
if not certificate.exists():
continue
valid = self.env.run(['openssl', 'x509', '-checkend', '120', '-noout',
valid = self.env.run(['openssl', 'x509', '-checkend', '300', '-noout',
'-in', str(certificate)], check=False).returncode == 0
if not valid:
self.pki.issue(role)
renewed.append(role)
return {'renewed': renewed}
reloaded, skipped = [], []
for role in renewed:
try:
self.reload_identity(role)
reloaded.append(role)
except OperationError:
# A stopped service will load the reissued leaf when compose starts it.
skipped.append(role)
return {'renewed': renewed, 'reloaded': reloaded, 'reload_skipped': skipped}
def bootstrap(self) -> dict:
self.prepare()
@@ -470,6 +478,7 @@ END $$;
self.retire_broker_users()
return {'bootstrapped': True, 'project': self.env.project,
'expired_identities_renewed': recovered.get('renewed', []),
'expired_identities_reloaded': recovered.get('reloaded', []),
'root_token_revoked': self.env.read_json(self.init_path).get('root_token_revoked', False)}
def wait_stores(self) -> None:
@@ -728,7 +737,9 @@ END $$;
gateways = ['lb', *[child for children in GATEWAY_PAIRS.values()
for child in children if child != 's3']]
self.env.compose('restart', *gateways, timeout=180)
return {**result, 'native_gateway_crls_reloaded': True, 'old_connections_drained': True}
return {**result, 'native_gateway_crls_reloaded': True,
'native_gateway_restarts': True,
'existing_application_pools_drained': False}
def recover_identity(self, role: str) -> dict:
transport_replaced = self.pki.recover_transport()
+18 -16
View File
@@ -666,10 +666,10 @@ def s3_plaintext_probe(cfg):
raise ProbeFailure('network_timeout') from None
except ConnectionRefusedError:
raise ProbeFailure('connection_refused') from None
if data.startswith(b'HTTP/') and b'x-amz-request-id' in data.lower():
return {'classification': 'accepted', 'detail': 's3_http_response'}
if data.startswith(b'HTTP/'):
return {'classification': 'rejected', 'detail': 'https_listener_rejected_http'}
if b'Client sent an HTTP request to an HTTPS server' in data:
return {'classification': 'rejected', 'detail': 'https_listener_rejected_http'}
return {'classification': 'accepted', 'detail': 'plaintext_http_response'}
return {'classification': 'rejected', 'detail': 'no_http_response'}
@@ -680,22 +680,24 @@ def loki_scan_probe(cfg):
now = dt.datetime.now(dt.timezone.utc)
start = (now - dt.timedelta(hours=24)).strftime('%Y-%m-%dT%H:%M:%SZ')
end = now.strftime('%Y-%m-%dT%H:%M:%SZ')
query = cfg.get('selector', '{service_name=~".+"}')
path = ('/loki/api/v1/query_range?query=' + urllib.parse.quote(query) +
'&start=' + start + '&end=' + end + '&limit=2000&direction=backward')
result = http('loki', 3100, 'GET', path, role='grafana')
require(result['status'] == 200, 'loki_query_failed', str(result['status']))
payload = json.loads(result['body'])
require(payload.get('status') == 'success', 'loki_query_failed', str(payload.get('status')))
selectors = cfg.get('selectors') or ['{service_name=~".+"}', '{job=~".+"}']
lines = 0
leaked = False
for stream in payload.get('data', {}).get('result', []):
for _, value in stream.get('values', []):
lines += 1
if any(secret in value for secret in sensitive):
leaked = True
for selector in selectors:
path = ('/loki/api/v1/query_range?query=' + urllib.parse.quote(selector) +
'&start=' + start + '&end=' + end + '&limit=2000&direction=backward')
result = http('loki', 3100, 'GET', path, role='grafana')
require(result['status'] == 200, 'loki_query_failed', str(result['status']))
payload = json.loads(result['body'])
require(payload.get('status') == 'success', 'loki_query_failed', str(payload.get('status')))
for stream in payload.get('data', {}).get('result', []):
for _, value in stream.get('values', []):
lines += 1
if any(secret in value for secret in sensitive):
leaked = True
require(lines > 0, 'loki_scan_empty')
return {'classification': 'leak' if leaked else 'passed', 'lines': lines,
'sensitive_values': len(sensitive)}
'sensitive_values': len(sensitive), 'window_hours': 24, 'selectors': len(selectors)}
def internal_main():