forked from mtusi2026/mtusi2026lab7
Закрыть оценку 4 и трек 1: отзыв leaf и права worker.
Брокер и Collector принимают только серийный номер текущего leaf. Прогон показывает rehash, 429 до дорогого Argon2, отказ stranger, ротацию пароля worker и сохранность задания.
This commit is contained in:
@@ -1,14 +1,14 @@
|
|||||||
## Лабораторная 7
|
## Лабораторная 7
|
||||||
|
|
||||||
Автор / группа: Булацев / БПИ2301
|
Автор / группа: Булацев / БПИ2301
|
||||||
Целевая оценка (3/4/5): 4
|
Целевая оценка (3/4/5): 5
|
||||||
Трек 5, если заявлен: не заявляется
|
Трек 5, если заявлен: трек 1, компрометация worker
|
||||||
|
|
||||||
Что реализовано и что перенесено: мессенджер lab6 (API, worker, Postgres, Redis, SeaweedFS, RabbitMQ, OTel/Grafana) перенесён без замены контракта и публичных tests. Добавлены Argon2id, общий rate limit, внешний TLS, mTLS LB→API и на брокер/Collector, OpenBao AppRole.
|
Что реализовано и что перенесено: мессенджер lab6 перенесён без замены контракта и публичных tests. Добавлены Argon2id, общий rate limit, внешний TLS, mTLS LB→API и на брокер/Collector с отзывом leaf по серийному номеру, OpenBao AppRole. Трек 1 сравнивает права worker до и после least privilege и переживает отзыв leaf плюс ротацию пароля БД.
|
||||||
Команды запуска из чистого clone: `pwsh scripts/bootstrap.ps1`, затем smoke/security с `CA_FILE=certs/ca.crt`. Подробности в REPORT.md.
|
Команды запуска из чистого clone: `pwsh scripts/bootstrap.ps1`, затем smoke/security с `CA_FILE=certs/ca.crt`. Подробности в REPORT.md.
|
||||||
Результаты проверок и ссылка на REPORT.md: REPORT.md. На этой машине прошли `scripts/check_contract.py`, `tests/smoke.py`, `tests/security.py`, `student-tests/mtls_probe.py`, persistence и failover по `https://127.0.0.1:8443` с `certs/ca.crt`. Вывод без токенов.
|
Результаты проверок и ссылка на REPORT.md: REPORT.md. На этой машине прошли check, smoke, security, mTLS, same-CA, rehash/429, persistence, failover и `student-tests/track1_worker.py`.
|
||||||
Ограничения / известные ошибки: один Docker-хост, ручной unseal OpenBao, нет CRL, backend-ы телеметрии без клиентского сертификата. Трек 5 не сделан.
|
Ограничения / известные ошибки: один Docker-хост, ручной unseal, нет CRL, Pillow 11 не обновлён до 13 (разбор в security/SCAN.md). Backend-ы телеметрии без клиентского сертификата.
|
||||||
Источники и использование ИИ: контракт курса, документация OpenBao и HAProxy, помощь Cursor.
|
Источники и использование ИИ: контракт курса, документация OpenBao и HAProxy, Trivy 0.58.1, помощь Cursor.
|
||||||
|
|
||||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
- [x] Контракт и публичные тесты не ослаблены.
|
- [x] Контракт и публичные тесты не ослаблены.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Отчёт — лабораторная 7
|
||||||
|
|
||||||
- Автор, группа: Булацев, БПИ2301
|
- Автор, группа: Булацев, БПИ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: 4. Трек 5 не заявляется.
|
- Целевая оценка; выбранный трек 5, если нужен: 5. Трек 1, компрометация worker.
|
||||||
- Commit/PR: локальные коммиты в `mtusi2026lab7`, PR ещё не открыт
|
- Commit/PR: локальные коммиты в `mtusi2026lab7`, PR ещё не открыт
|
||||||
- Использованные источники, библиотеки и помощь ИИ: контракт lab7, OWASP Password Storage, OpenBao AppRole/policies, argon2-cffi, HAProxy 3.1 (`ssl_c_san`). Реализация перенесена из lab6 и дополнена в Cursor.
|
- Использованные источники, библиотеки и помощь ИИ: контракт lab7, OWASP Password Storage, OpenBao AppRole/policies, argon2-cffi, HAProxy 3.1 (`ssl_c_san`). Реализация перенесена из lab6 и дополнена в Cursor.
|
||||||
|
|
||||||
@@ -28,6 +28,9 @@ python -X utf8 scripts/check_contract.py
|
|||||||
python -X utf8 tests/smoke.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
|
python -X utf8 tests/smoke.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
|
||||||
python -X utf8 tests/security.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
|
python -X utf8 tests/security.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
|
||||||
python -X utf8 student-tests/mtls_probe.py
|
python -X utf8 student-tests/mtls_probe.py
|
||||||
|
python -X utf8 student-tests/same_ca_probe.py
|
||||||
|
python -X utf8 student-tests/session_probe.py
|
||||||
|
python -X utf8 student-tests/track1_worker.py
|
||||||
python -X utf8 scripts/measure_argon2.py
|
python -X utf8 scripts/measure_argon2.py
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -64,12 +67,16 @@ python -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-
|
|||||||
| Argon2id не ниже 19 MiB, t=2, p=1 | `python scripts/measure_argon2.py` в образе стенда | memory_kib=19456, t=2, p=1, elapsed_ms=75.1 | вывод скрипта |
|
| Argon2id не ниже 19 MiB, t=2, p=1 | `python scripts/measure_argon2.py` в образе стенда | memory_kib=19456, t=2, p=1, elapsed_ms=75.1 | вывод скрипта |
|
||||||
| Внешний недоверенный CA | `tests/security.py --ca-file certs/ca.crt` | PASS: пустой trust store даёт `SSLCertVerificationError` | вывод `tests/security.py` |
|
| Внешний недоверенный CA | `tests/security.py --ca-file certs/ca.crt` | PASS: пустой trust store даёт `SSLCertVerificationError` | вывод `tests/security.py` |
|
||||||
| mTLS LB→API, чужая identity | `python student-tests/mtls_probe.py` | PASS: 200 с `lb-client`; без cert и чужой CA — `SSLEOFError`; stranger и lb-revoked обрываются без HTTP | вывод probe |
|
| mTLS LB→API, чужая identity | `python student-tests/mtls_probe.py` | PASS: 200 с `lb-client`; без cert и чужой CA — `SSLEOFError`; stranger и lb-revoked обрываются без HTTP | вывод probe |
|
||||||
|
| Тот же CA на брокере и Collector | `python student-tests/same_ca_probe.py` | PASS: api и worker получают AMQP и HTTP; stranger на брокере обрывается, на Collector — 403; просроченный leaf — `SSLError` | вывод probe |
|
||||||
|
| Rehash и общий login limit | `python student-tests/session_probe.py` | Хэш `m=8192` после входа стал `m=19456`. 8-я попытка 54.8 мс, 9-я — `429` за 21.9 мс, с `Retry-After` | вывод probe |
|
||||||
|
| Трек 1, worker | `python student-tests/track1_worker.py` | Worker читает `attachments`, не читает `users`, пишет `variants/` и не пишет `secrets/`, не объявляет чужую очередь, OpenBao API path — 403. Старый leaf отозван, пароль БД сменён без пересборки образа, задание из очереди дошло до `ready`. Sealed OpenBao отвечает на AppRole 503 и после unseal снова 200 | вывод скрипта |
|
||||||
|
| Скан образа | `aquasec/trivy:0.58.1` | Debian 52 и Python 44 high/critical. Применим Pillow на пути вложения; GnuTLS/apt/Starlette Range — нет | `security/SCAN.md` |
|
||||||
| OpenBao policy allow/deny | bootstrap логинится AppRole API и читает KV worker | HTTP 403, строка PASS | `evidence/openbao-deny.txt` |
|
| OpenBao policy allow/deny | bootstrap логинится AppRole API и читает KV worker | HTTP 403, строка PASS | `evidence/openbao-deny.txt` |
|
||||||
| Рестарт API без потери сессии | `tests/resilience.py --mode persistence --action-script scripts/restart.cmd` | PASS: сессия, сообщение и вложение на месте | вывод теста |
|
| Рестарт API без потери сессии | `tests/resilience.py --mode persistence --action-script scripts/restart.cmd` | PASS: сессия, сообщение и вложение на месте | вывод теста |
|
||||||
| Отказ одной реплики | `tests/resilience.py --mode failover --action-script scripts/stop-one.cmd` | PASS: две реплики до остановки, запись вернулась за 8.5 с | вывод теста |
|
| Отказ одной реплики | `tests/resilience.py --mode failover --action-script scripts/stop-one.cmd` | PASS: две реплики до остановки, запись вернулась за 8.5 с | вывод теста |
|
||||||
| Rate limit и rehash | 9-й `POST /api/v1/auth/sessions` за минуту на то же имя | `429` и `Retry-After`; успешный вход обновляет PHC, если параметры старые | код `app/ratelimit.py`, `app/passwords.py` |
|
| Rate limit и rehash | 9-й `POST /api/v1/auth/sessions` за минуту на то же имя | `429` и `Retry-After`; успешный вход обновляет PHC, если параметры старые | код `app/ratelimit.py`, `app/passwords.py` |
|
||||||
|
|
||||||
Прогон стенда на этой машине: smoke, security, mTLS probe, persistence и failover прошли по HTTPS с проверкой CA. В отчёт не копируются токены и ключи.
|
Прогон стенда на этой машине: smoke, security, mTLS, same-CA, rehash, persistence, failover и трек 1 прошли по HTTPS с проверкой CA. Сообщение с меткой `canary-telemetry-7f3a9c` в логах API и worker не появилось. В отчёт не копируются токены и ключи.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
|
|||||||
@@ -215,6 +215,9 @@ def main() -> None:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
print("kv documents written")
|
print("kv documents written")
|
||||||
|
if os.environ.get("BAO_REFRESH_KV_ONLY") == "1":
|
||||||
|
print("approle secret ids left unchanged")
|
||||||
|
return
|
||||||
for name in ("api", "worker", "migrate"):
|
for name in ("api", "worker", "migrate"):
|
||||||
ensure_role(token, name)
|
ensure_role(token, name)
|
||||||
deny_check()
|
deny_check()
|
||||||
|
|||||||
@@ -109,6 +109,8 @@ services:
|
|||||||
- ./infra/haproxy-rabbit.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
- ./infra/haproxy-rabbit.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
- ./certs/rabbitmq.pem:/certs/rabbitmq.pem:ro
|
- ./certs/rabbitmq.pem:/certs/rabbitmq.pem:ro
|
||||||
- ./certs/ca.crt:/certs/ca.crt:ro
|
- ./certs/ca.crt:/certs/ca.crt:ro
|
||||||
|
- ./certs/allowed-api.serial:/certs/allowed-api.serial:ro
|
||||||
|
- ./certs/allowed-worker.serial:/certs/allowed-worker.serial:ro
|
||||||
read_only: true
|
read_only: true
|
||||||
tmpfs:
|
tmpfs:
|
||||||
- /tmp:rw,nosuid,size=16m
|
- /tmp:rw,nosuid,size=16m
|
||||||
@@ -470,6 +472,12 @@ services:
|
|||||||
cpus: "1.0"
|
cpus: "1.0"
|
||||||
stop_grace_period: 20s
|
stop_grace_period: 20s
|
||||||
networks: [data, signals]
|
networks: [data, signals]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import os; os.kill(1, 0)"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
start_period: 20s
|
||||||
|
|
||||||
otel-collector:
|
otel-collector:
|
||||||
image: otel/opentelemetry-collector-contrib:0.128.0
|
image: otel/opentelemetry-collector-contrib:0.128.0
|
||||||
@@ -497,6 +505,8 @@ services:
|
|||||||
- ./infra/haproxy-otel.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
- ./infra/haproxy-otel.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
- ./certs/otel.pem:/certs/otel.pem:ro
|
- ./certs/otel.pem:/certs/otel.pem:ro
|
||||||
- ./certs/ca.crt:/certs/ca.crt:ro
|
- ./certs/ca.crt:/certs/ca.crt:ro
|
||||||
|
- ./certs/allowed-api.serial:/certs/allowed-api.serial:ro
|
||||||
|
- ./certs/allowed-worker.serial:/certs/allowed-worker.serial:ro
|
||||||
read_only: true
|
read_only: true
|
||||||
tmpfs:
|
tmpfs:
|
||||||
- /tmp:rw,nosuid,size=16m
|
- /tmp:rw,nosuid,size=16m
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
| LB → API (все реплики) | mTLS, только TLS 1.2. Сервер: cert `api` (SAN `DNS:api`). Клиент: только отпечаток из `allowed-lb.sha256` и URI `spiffe://messenger/lb`. Uvicorn на `127.0.0.1:8080`, снаружи контейнера порта нет | Смена leaf LB без пересборки образа: заменить `certs/lb.pem` и перезапустить `lb`. Отзыв: убрать строку из `allowed-lb.sha256` (см. `lb-revoked`) | `app/tls_proxy.py`, `infra/haproxy.cfg`. Отказ: без cert, `other-client.pem` (чужой CA), `stranger.pem`, `lb-revoked.pem`. Успех: `lb-client.pem` |
|
| LB → API (все реплики) | mTLS, только TLS 1.2. Сервер: cert `api` (SAN `DNS:api`). Клиент: только отпечаток из `allowed-lb.sha256` и URI `spiffe://messenger/lb`. Uvicorn на `127.0.0.1:8080`, снаружи контейнера порта нет | Смена leaf LB без пересборки образа: заменить `certs/lb.pem` и перезапустить `lb`. Отзыв: убрать строку из `allowed-lb.sha256` (см. `lb-revoked`) | `app/tls_proxy.py`, `infra/haproxy.cfg`. Отказ: без cert, `other-client.pem` (чужой CA), `stranger.pem`, `lb-revoked.pem`. Успех: `lb-client.pem` |
|
||||||
| API/worker → PostgreSQL | TLS verify-full, SAN `DNS:postgres`, `hostssl` + SCRAM. migrate — суперпользователь `messenger` только из KV `messenger/migrate`. API — `messenger_api`. Worker — `messenger_worker` без прав на `users` | Пароли ролей лежат в OpenBao и меняются вместе с KV и `ALTER ROLE`; рестарт API подхватывает новое значение | `infra/postgres/entrypoint.sh`, `pg_hba.conf`, `grant.sh` |
|
| API/worker → PostgreSQL | TLS verify-full, SAN `DNS:postgres`, `hostssl` + SCRAM. migrate — суперпользователь `messenger` только из KV `messenger/migrate`. API — `messenger_api`. Worker — `messenger_worker` без прав на `users` | Пароли ролей лежат в OpenBao и меняются вместе с KV и `ALTER ROLE`; рестарт API подхватывает новое значение | `infra/postgres/entrypoint.sh`, `pg_hba.conf`, `grant.sh` |
|
||||||
| API/worker → S3 | TLS до HAProxy на `s3:9000`. Seaweed без TLS только в сети `s3internal` (`0.0.0.0:9000`; localhost bind ломает его внутренний gRPC). Разные ключи: api читает bucket и пишет `staging/` и `originals/`; worker без `Admin`; bootstrap-ключ только у `s3-init` | Запись ключом worker в префикс вне выданных actions отклоняется Seaweed | `infra/s3/seaweed-entrypoint.sh`, `infra/haproxy-s3.cfg`. Публичный presign: `https://127.0.0.1:9007` |
|
| API/worker → S3 | TLS до HAProxy на `s3:9000`. Seaweed без TLS только в сети `s3internal` (`0.0.0.0:9000`; localhost bind ломает его внутренний gRPC). Разные ключи: api читает bucket и пишет `staging/` и `originals/`; worker без `Admin`; bootstrap-ключ только у `s3-init` | Запись ключом worker в префикс вне выданных actions отклоняется Seaweed | `infra/s3/seaweed-entrypoint.sh`, `infra/haproxy-s3.cfg`. Публичный presign: `https://127.0.0.1:9007` |
|
||||||
| API/worker → broker | mTLS на `rabbitmq:5671`. HAProxy пускает только URI `spiffe://messenger/api` или `.../worker`. AMQP дальше только на `127.0.0.1:5672`. Пользователи `messenger_api` и `messenger_worker` разные | Чужой сертификат того же CA (`stranger`) режется до AMQP. Worker не конфигурирует произвольные очереди: configure/write/read только `attachment.jobs*` | `infra/haproxy-rabbit.cfg`, `infra/rabbitmq/entrypoint.sh` |
|
| API/worker → broker | mTLS на `rabbitmq:5671`. HAProxy пускает только URI `spiffe://messenger/api` или `.../worker` и серийный номер из `allowed-api.serial` / `allowed-worker.serial`. AMQP дальше только на `127.0.0.1:5672`. Пользователи `messenger_api` и `messenger_worker` разные | Чужой сертификат того же CA (`stranger`) и старый leaf worker режутся до AMQP. Worker не объявляет чужие очереди: configure/write/read только `attachment.jobs*` | `infra/haproxy-rabbit.cfg`, `infra/rabbitmq/entrypoint.sh`, `student-tests/same_ca_probe.py` |
|
||||||
| API/worker → Collector | mTLS `https://otel-collector:4318`. Collector слушает plaintext лишь `127.0.0.1:14318`. Разрешены те же две URI identity, клиентские cert разные | `stranger` с тем же CA не проходит `ssl_c_san` | `infra/haproxy-otel.cfg`, `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` в `compose.yaml` |
|
| API/worker → Collector | mTLS `https://otel-collector:4318`. Collector слушает plaintext лишь `127.0.0.1:14318`. Те же две URI и те же два serial allow-файла, клиентские cert разные | `stranger` получает HTTP 403 от HAProxy, не OTLP. Просроченный leaf не проходит handshake | `infra/haproxy-otel.cfg`, `student-tests/same_ca_probe.py` |
|
||||||
| Collector → telemetry backends | TLS: Tempo `https://tempo:4318`, Prometheus `https://prometheus:9090`, Loki `https://loki:3100`, CA `certs/ca.crt`. Сеть `telemetry` не доступна API | Отдельных паролей backend-ов нет: граница — сеть и серверный сертификат. Это зафиксировано как ограничение, не как mTLS | `infra/otel/collector.yaml`, `infra/prometheus/web.yml`, `infra/loki/loki.yml`, `infra/tempo/tempo.yml` |
|
| Collector → telemetry backends | TLS: Tempo `https://tempo:4318`, Prometheus `https://prometheus:9090`, Loki `https://loki:3100`, CA `certs/ca.crt`. Сеть `telemetry` не доступна API | Отдельных паролей backend-ов нет: граница — сеть и серверный сертификат. Это зафиксировано как ограничение, не как mTLS | `infra/otel/collector.yaml`, `infra/prometheus/web.yml`, `infra/loki/loki.yml`, `infra/tempo/tempo.yml` |
|
||||||
| Grafana → data sources | HTTPS, `SSL_CERT_FILE=/certs/ca.crt`, анонимный доступ выключен, пароль admin из файла секрета. Порт только `127.0.0.1:3007` | Логин без пароля больше не открывает Admin | `infra/grafana/entrypoint.sh`, provisioning datasources |
|
| Grafana → data sources | HTTPS, `SSL_CERT_FILE=/certs/ca.crt`, анонимный доступ выключен, пароль admin из файла секрета. Порт только `127.0.0.1:3007` | Логин без пароля больше не открывает Admin | `infra/grafana/entrypoint.sh`, provisioning datasources |
|
||||||
| API/worker/agent → OpenBao | `https://openbao:8200`, file storage, не dev. AppRole, policy `messenger-api` / `messenger-worker` / `messenger-migrate`, token TTL 20 мин, renew | SecretID TTL 24 ч, новый SecretID выпускает повторный bootstrap. Чтение чужого path — 403 | `infra/openbao/openbao.hcl`, `policies/*.hcl`, `app/bao.py`. Доказательство: `evidence/openbao-deny.txt` |
|
| API/worker/agent → OpenBao | `https://openbao:8200`, file storage, не dev. AppRole, policy `messenger-api` / `messenger-worker` / `messenger-migrate`, token TTL 20 мин, renew | SecretID TTL 24 ч, новый SecretID выпускает повторный bootstrap. Чтение чужого path — 403 | `infra/openbao/openbao.hcl`, `policies/*.hcl`, `app/bao.py`. Доказательство: `evidence/openbao-deny.txt` |
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ frontend ft_otlp
|
|||||||
bind *:4318 ssl crt /certs/otel.pem ca-file /certs/ca.crt verify required
|
bind *:4318 ssl crt /certs/otel.pem ca-file /certs/ca.crt verify required
|
||||||
acl api_id ssl_c_san -m sub spiffe://messenger/api
|
acl api_id ssl_c_san -m sub spiffe://messenger/api
|
||||||
acl worker_id ssl_c_san -m sub spiffe://messenger/worker
|
acl worker_id ssl_c_san -m sub spiffe://messenger/worker
|
||||||
http-request deny unless api_id or worker_id
|
acl api_leaf ssl_c_serial,hex,lower -f /certs/allowed-api.serial
|
||||||
|
acl worker_leaf ssl_c_serial,hex,lower -f /certs/allowed-worker.serial
|
||||||
|
http-request set-var(txn.leaf_ok) str(1) if api_id api_leaf
|
||||||
|
http-request set-var(txn.leaf_ok) str(1) if worker_id worker_leaf
|
||||||
|
acl leaf_ok var(txn.leaf_ok) -m str 1
|
||||||
|
http-request deny unless leaf_ok
|
||||||
default_backend be_local
|
default_backend be_local
|
||||||
|
|
||||||
backend be_local
|
backend be_local
|
||||||
|
|||||||
@@ -15,7 +15,12 @@ frontend ft_amqp
|
|||||||
tcp-request content accept if { req_ssl_hello_type 1 }
|
tcp-request content accept if { req_ssl_hello_type 1 }
|
||||||
acl api_id ssl_c_san -m sub spiffe://messenger/api
|
acl api_id ssl_c_san -m sub spiffe://messenger/api
|
||||||
acl worker_id ssl_c_san -m sub spiffe://messenger/worker
|
acl worker_id ssl_c_san -m sub spiffe://messenger/worker
|
||||||
tcp-request content reject unless api_id or worker_id
|
acl api_leaf ssl_c_serial,hex,lower -f /certs/allowed-api.serial
|
||||||
|
acl worker_leaf ssl_c_serial,hex,lower -f /certs/allowed-worker.serial
|
||||||
|
tcp-request content set-var(txn.leaf_ok) str(1) if api_id api_leaf
|
||||||
|
tcp-request content set-var(txn.leaf_ok) str(1) if worker_id worker_leaf
|
||||||
|
acl leaf_ok var(txn.leaf_ok) -m str 1
|
||||||
|
tcp-request content reject unless leaf_ok
|
||||||
default_backend be_local
|
default_backend be_local
|
||||||
|
|
||||||
backend be_local
|
backend be_local
|
||||||
|
|||||||
+13
-1
@@ -2,7 +2,19 @@
|
|||||||
set -eu
|
set -eu
|
||||||
apk add --no-cache openssl >/dev/null
|
apk add --no-cache openssl >/dev/null
|
||||||
cd /work
|
cd /work
|
||||||
|
|
||||||
|
serial_of() {
|
||||||
|
openssl x509 -in "$1" -noout -serial | awk -F= '{print tolower($2)}'
|
||||||
|
}
|
||||||
|
|
||||||
|
write_allows() {
|
||||||
|
openssl x509 -in lb-client.crt -outform DER | openssl dgst -sha256 -r | awk '{print $1}' > allowed-lb.sha256
|
||||||
|
serial_of api-client.crt > allowed-api.serial
|
||||||
|
serial_of worker-client.crt > allowed-worker.serial
|
||||||
|
}
|
||||||
|
|
||||||
if [ -f ca.crt ] && [ -f allowed-lb.sha256 ] && [ -f lb.pem ]; then
|
if [ -f ca.crt ] && [ -f allowed-lb.sha256 ] && [ -f lb.pem ]; then
|
||||||
|
write_allows
|
||||||
echo "certificates already present"
|
echo "certificates already present"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
@@ -70,7 +82,7 @@ openssl x509 -req -in /tmp/other-client.csr -CA other-ca.crt -CAkey other-ca.key
|
|||||||
-out other-client.crt -days 7 -extfile /tmp/other-client.cnf >/dev/null 2>&1
|
-out other-client.crt -days 7 -extfile /tmp/other-client.cnf >/dev/null 2>&1
|
||||||
cat other-client.crt other-client.key > other-client.pem
|
cat other-client.crt other-client.key > other-client.pem
|
||||||
|
|
||||||
openssl x509 -in lb-client.crt -outform DER | openssl dgst -sha256 -r | awk '{print $1}' > allowed-lb.sha256
|
write_allows
|
||||||
find . -name '*.key' -exec chmod 644 {} \;
|
find . -name '*.key' -exec chmod 644 {} \;
|
||||||
find . -name '*.pem' -exec chmod 644 {} \;
|
find . -name '*.pem' -exec chmod 644 {} \;
|
||||||
echo "certificates created"
|
echo "certificates created"
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Reissue one leaf from the existing lab CA. Does not print the key.
|
||||||
|
# Args: name cn eku san
|
||||||
|
# Optional env: NOT_BEFORE, NOT_AFTER as YYYYMMDDHHMMSSZ
|
||||||
|
set -eu
|
||||||
|
apk add --no-cache openssl >/dev/null
|
||||||
|
cd /work
|
||||||
|
name="$1"
|
||||||
|
cn="$2"
|
||||||
|
eku="$3"
|
||||||
|
san="$4"
|
||||||
|
test -f ca.key
|
||||||
|
test -f ca.crt
|
||||||
|
cat > "/tmp/${name}.cnf" <<EOF
|
||||||
|
[req]
|
||||||
|
distinguished_name=dn
|
||||||
|
prompt=no
|
||||||
|
[dn]
|
||||||
|
CN=${cn}
|
||||||
|
[ext]
|
||||||
|
subjectAltName=${san}
|
||||||
|
keyUsage=digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=${eku}
|
||||||
|
basicConstraints=CA:FALSE
|
||||||
|
EOF
|
||||||
|
openssl req -newkey rsa:2048 -nodes -keyout "${name}.key" -out "/tmp/${name}.csr" -subj "/CN=${cn}" >/dev/null 2>&1
|
||||||
|
if [ -n "${NOT_BEFORE:-}" ] || [ -n "${NOT_AFTER:-}" ]; then
|
||||||
|
mkdir -p /tmp/newcerts
|
||||||
|
: > /tmp/index.txt
|
||||||
|
echo 1000 > /tmp/serial
|
||||||
|
cat > /tmp/ca.cnf <<EOF
|
||||||
|
[ca]
|
||||||
|
default_ca=CA_default
|
||||||
|
[CA_default]
|
||||||
|
database=/tmp/index.txt
|
||||||
|
serial=/tmp/serial
|
||||||
|
new_certs_dir=/tmp/newcerts
|
||||||
|
certificate=/work/ca.crt
|
||||||
|
private_key=/work/ca.key
|
||||||
|
default_md=sha256
|
||||||
|
policy=policy_any
|
||||||
|
copy_extensions=none
|
||||||
|
unique_subject=no
|
||||||
|
[policy_any]
|
||||||
|
commonName=supplied
|
||||||
|
EOF
|
||||||
|
openssl ca -batch -notext -config /tmp/ca.cnf \
|
||||||
|
-in "/tmp/${name}.csr" -out "${name}.crt" \
|
||||||
|
-startdate "${NOT_BEFORE:-20200101000000Z}" -enddate "${NOT_AFTER:-20200102000000Z}" \
|
||||||
|
-extfile "/tmp/${name}.cnf" -extensions ext >/dev/null 2>&1
|
||||||
|
else
|
||||||
|
openssl x509 -req -in "/tmp/${name}.csr" -CA ca.crt -CAkey ca.key -CAcreateserial \
|
||||||
|
-out "${name}.crt" -days 7 -extfile "/tmp/${name}.cnf" -extensions ext >/dev/null 2>&1
|
||||||
|
fi
|
||||||
|
cat "${name}.crt" "${name}.key" > "${name}.pem"
|
||||||
|
chmod 644 "${name}.key" "${name}.pem"
|
||||||
|
if [ "$name" = "lb-client" ]; then
|
||||||
|
openssl x509 -in lb-client.crt -outform DER | openssl dgst -sha256 -r | awk '{print $1}' > allowed-lb.sha256
|
||||||
|
fi
|
||||||
|
if [ "$name" = "api-client" ]; then
|
||||||
|
openssl x509 -in api-client.crt -noout -serial | awk -F= '{print tolower($2)}' > allowed-api.serial
|
||||||
|
fi
|
||||||
|
if [ "$name" = "worker-client" ]; then
|
||||||
|
openssl x509 -in worker-client.crt -noout -serial | awk -F= '{print tolower($2)}' > allowed-worker.serial
|
||||||
|
fi
|
||||||
|
echo "reissued $name"
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Разбор скана образа `mtusi-messenger:lab7`
|
||||||
|
|
||||||
|
Команда, 26 ноября 2026:
|
||||||
|
|
||||||
|
```
|
||||||
|
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:0.58.1 image --severity HIGH,CRITICAL --ignore-unfixed --pkg-types os,library mtusi-messenger:lab7
|
||||||
|
```
|
||||||
|
|
||||||
|
`docker scout` на этой машине требует Docker Hub login и отчёт не заменяет. Trivy: Debian 12.9 — 52 (45 HIGH, 7 CRITICAL), Python-пакеты — 44 (39 HIGH, 5 CRITICAL). Ниже не список CVE, а то, доходит ли находка до нашего кода.
|
||||||
|
|
||||||
|
## Доходит до стенда
|
||||||
|
|
||||||
|
Pillow 11.1.0. Worker открывает загруженный PNG/JPEG и пишет thumbnail. Критические записи Trivy (heap overflow в TIFF/JPEG/FPX и argument injection в Ghostscript) имеют исправление только в Pillow 13.0.0. На стенде это ограничено так: загрузка только от участника чата, размер `MAX_UPLOAD_BYTES`, пиксели `MAX_IMAGE_PIXELS`, worker с лимитом CPU 1, RAM 768 МиБ и `JOB_TIMEOUT_SECONDS=60`. Прыжок 11 → 13 не делался в этом коммите: это смена поведения декодера, а не точечный патч. Остаточный риск честный: злонамеренный файл участника чата может уронить worker, но не читает `users` и не получает admin S3.
|
||||||
|
|
||||||
|
## Не на нашем пути
|
||||||
|
|
||||||
|
- GnuTLS в базовом Debian (SAN/DTLS). Проверки mTLS идут через OpenSSL: Python `ssl` и HAProxy. `curl` в образ поставлен, healthcheck его не вызывает.
|
||||||
|
- apt/gpgv/krb5. Контейнер не ставит пакеты в рантайме и не ходит в Kerberos. `cap_drop: ALL` и non-root режут то, что иначе дал бы локальный баг libcap.
|
||||||
|
- Starlette 0.41.3, CVE про склейку `Range` и `request.form()`. Своих `FileResponse` нет, тело запроса режется middleware до приложения. Загрузка — сырой body, не `application/x-www-form-urlencoded`.
|
||||||
|
|
||||||
|
Обновление базового `python:3.12.8-slim-bookworm` снимет Debian-находки целиком. Пока образ закреплён, число CVE само по себе не считается закрытием.
|
||||||
@@ -25,10 +25,14 @@
|
|||||||
|
|
||||||
Bootstrap: `scripts/bootstrap.ps1` создаёт CA и leaf локально, поднимает OpenBao в file storage (не dev), один раз вызывает init и пишет unseal key и root token в `secrets/openbao-init.json`. Обычный рестарт API unseal не требует: OpenBao не входит в `scripts/restart.sh`. После рестарта самого OpenBao оператор повторяет `docker compose --profile bootstrap run --rm openbao-bootstrap` — скрипт читает уже существующий init-файл и делает unseal, не печатая ключ.
|
Bootstrap: `scripts/bootstrap.ps1` создаёт CA и leaf локально, поднимает OpenBao в file storage (не dev), один раз вызывает init и пишет unseal key и root token в `secrets/openbao-init.json`. Обычный рестарт API unseal не требует: OpenBao не входит в `scripts/restart.sh`. После рестарта самого OpenBao оператор повторяет `docker compose --profile bootstrap run --rm openbao-bootstrap` — скрипт читает уже существующий init-файл и делает unseal, не печатая ключ.
|
||||||
|
|
||||||
Ротация leaf LB: заново выпустить `lb.crt`/`lb.pem` тем же CA (`scripts/gen-certs.sh` нужно временно убрать старые `lb.*`, CA не трогать) и перезапустить только сервис `lb`. Клиенты с `certs/ca.crt` принимают новый leaf без пересборки образа.
|
Ротация leaf LB: `scripts/reissue-leaf.sh` выпускает новый `lb.crt` тем же CA и перезапускает только `lb`. Клиенты с `certs/ca.crt` принимают его без пересборки образа. На прогоне 26 ноября идентификатор образа `mtusi-messenger:lab7` не изменился.
|
||||||
|
|
||||||
Отзыв identity LB: убрать отпечаток из `certs/allowed-lb.sha256`. Старый сертификат, подписанный тем же CA и с тем же URI, перестаёт проксироваться. `lb-revoked.crt` выпускается заранее именно для этой проверки.
|
Отзыв identity worker: брокер и Collector, кроме URI, сверяют серийный номер leaf с `allowed-worker.serial`. Старый файл сохраняется как `worker-client.revoked.*` и после выпуска нового leaf получает отказ. Просроченный сертификат (`notAfter` в 2020) не проходит handshake.
|
||||||
|
|
||||||
Истечение: token OpenBao живёт 20 минут и продлевается; SecretID — 24 часа. Если OpenBao sealed, login AppRole не проходит и API не становится ready. Fallback на plaintext и `InsecureSkipVerify` в приложении нет.
|
Ротация секрета worker: новый пароль `messenger_worker` пишется в Postgres и в KV `messenger/worker`. SecretID AppRole при этом не перевыпускается (`BAO_REFRESH_KV_ONLY=1`), образ не пересобирается. Задание, поставленное в очередь при остановленном worker, после старта доходит до `ready`.
|
||||||
|
|
||||||
Сканы образов в этот коммит не вложены: разбор CVE делается отдельно и не заменяется числом находок. Учебное упрощение — один Docker-хост, file storage OpenBao без HA, ручной unseal.
|
Истечение и sealed OpenBao: token TTL 20 минут, SecretID 24 часа. `student-tests/seal_probe.py` запечатывает OpenBao, видит отказ AppRole (HTTP 503) и сразу делает unseal. Fallback на plaintext и отключение проверки сертификата в приложении нет.
|
||||||
|
|
||||||
|
Скан: `security/SCAN.md`.
|
||||||
|
|
||||||
|
Сканы образов в этот коммит не вложены сырым отчётом Trivy: разбор применимости лежит в `security/SCAN.md`. Учебное упрощение — один Docker-хост, file storage OpenBao без HA, ручной unseal. Pillow 11 не поднят до 13.
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Same-CA identity check for the broker and the collector.
|
||||||
|
|
||||||
|
The public client does not present a certificate. This probe joins the
|
||||||
|
compose networks and checks that a certificate signed by our CA is still
|
||||||
|
rejected when its SAN or leaf serial is not the API or worker identity.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROBE = Path(__file__).resolve()
|
||||||
|
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
|
||||||
|
CERTS = Path("/certs") if "--internal" in sys.argv else ROOT / "certs"
|
||||||
|
|
||||||
|
|
||||||
|
def context(cert: Path | None, key: Path | None) -> ssl.SSLContext:
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||||
|
ctx.load_verify_locations(CERTS / "ca.crt")
|
||||||
|
ctx.check_hostname = True
|
||||||
|
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||||
|
if cert is not None and key is not None:
|
||||||
|
ctx.load_cert_chain(cert, key)
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def rabbit(cert: Path | None, key: Path | None) -> str:
|
||||||
|
try:
|
||||||
|
raw = socket.create_connection(("rabbitmq", 5671), timeout=5)
|
||||||
|
tls = context(cert, key).wrap_socket(raw, server_hostname="rabbitmq")
|
||||||
|
tls.sendall(b"AMQP\x00\x00\x09\x01")
|
||||||
|
data = tls.recv(8)
|
||||||
|
tls.close()
|
||||||
|
return "amqp" if data else "closed"
|
||||||
|
except ssl.SSLError as exc:
|
||||||
|
return "ssl:" + exc.__class__.__name__
|
||||||
|
except OSError as exc:
|
||||||
|
return "os:" + exc.__class__.__name__
|
||||||
|
|
||||||
|
|
||||||
|
def otel(cert: Path | None, key: Path | None) -> str:
|
||||||
|
try:
|
||||||
|
raw = socket.create_connection(("otel-collector", 4318), timeout=5)
|
||||||
|
tls = context(cert, key).wrap_socket(raw, server_hostname="otel-collector")
|
||||||
|
tls.sendall(b"GET / HTTP/1.1\r\nHost: otel-collector\r\nConnection: close\r\n\r\n")
|
||||||
|
data = b""
|
||||||
|
while True:
|
||||||
|
chunk = tls.recv(1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
data += chunk
|
||||||
|
tls.close()
|
||||||
|
head = data.split(b"\r\n", 1)[0].decode("ascii", "replace")
|
||||||
|
return head or "closed"
|
||||||
|
except ssl.SSLError as exc:
|
||||||
|
return "ssl:" + exc.__class__.__name__
|
||||||
|
except OSError as exc:
|
||||||
|
return "os:" + exc.__class__.__name__
|
||||||
|
|
||||||
|
|
||||||
|
def expect_closed(label: str, result: str) -> None:
|
||||||
|
denied = result == "closed" or result.startswith("ssl:") or result.startswith("os:") or result.startswith("HTTP/1.1 403")
|
||||||
|
if not denied:
|
||||||
|
raise SystemExit("FAIL %s was accepted: %s" % (label, result))
|
||||||
|
print("PASS", label, result)
|
||||||
|
|
||||||
|
|
||||||
|
def internal() -> None:
|
||||||
|
pairs = (
|
||||||
|
("api leaf", CERTS / "api-client.crt", CERTS / "api-client.key"),
|
||||||
|
("worker leaf", CERTS / "worker-client.crt", CERTS / "worker-client.key"),
|
||||||
|
)
|
||||||
|
for label, cert, key in pairs:
|
||||||
|
rabbit_result = rabbit(cert, key)
|
||||||
|
otel_result = otel(cert, key)
|
||||||
|
if rabbit_result != "amqp":
|
||||||
|
raise SystemExit("FAIL %s broker: %s" % (label, rabbit_result))
|
||||||
|
if not otel_result.startswith("HTTP/"):
|
||||||
|
raise SystemExit("FAIL %s collector: %s" % (label, otel_result))
|
||||||
|
print("PASS", label, "broker", rabbit_result, "collector", otel_result)
|
||||||
|
expect_closed("broker no cert", rabbit(None, None))
|
||||||
|
expect_closed("broker stranger same CA", rabbit(CERTS / "stranger.crt", CERTS / "stranger.key"))
|
||||||
|
expect_closed("broker other CA", rabbit(CERTS / "other-client.crt", CERTS / "other-client.key"))
|
||||||
|
expect_closed("collector no cert", otel(None, None))
|
||||||
|
expect_closed("collector stranger same CA", otel(CERTS / "stranger.crt", CERTS / "stranger.key"))
|
||||||
|
expect_closed("collector other CA", otel(CERTS / "other-client.crt", CERTS / "other-client.key"))
|
||||||
|
revoked = CERTS / "worker-client.revoked.crt"
|
||||||
|
if revoked.is_file():
|
||||||
|
expect_closed(
|
||||||
|
"broker revoked worker leaf",
|
||||||
|
rabbit(revoked, CERTS / "worker-client.revoked.key"),
|
||||||
|
)
|
||||||
|
expect_closed(
|
||||||
|
"collector revoked worker leaf",
|
||||||
|
otel(revoked, CERTS / "worker-client.revoked.key"),
|
||||||
|
)
|
||||||
|
expired = CERTS / "expired-worker.crt"
|
||||||
|
if expired.is_file():
|
||||||
|
expect_closed(
|
||||||
|
"broker expired worker leaf",
|
||||||
|
rabbit(expired, CERTS / "expired-worker.key"),
|
||||||
|
)
|
||||||
|
expect_closed(
|
||||||
|
"collector expired worker leaf",
|
||||||
|
otel(expired, CERTS / "expired-worker.key"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
if "--internal" in sys.argv:
|
||||||
|
internal()
|
||||||
|
return
|
||||||
|
if not (CERTS / "ca.crt").is_file():
|
||||||
|
raise SystemExit("missing certs/ca.crt")
|
||||||
|
completed = subprocess.run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"--env-file",
|
||||||
|
".env",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--no-deps",
|
||||||
|
"--entrypoint",
|
||||||
|
"python",
|
||||||
|
"-v",
|
||||||
|
"%s:/probe.py:ro" % PROBE,
|
||||||
|
"-v",
|
||||||
|
"%s:/certs:ro" % CERTS,
|
||||||
|
"api",
|
||||||
|
"/probe.py",
|
||||||
|
"--internal",
|
||||||
|
],
|
||||||
|
cwd=ROOT,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
if completed.returncode != 0:
|
||||||
|
raise SystemExit(completed.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main() or 0)
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Seal OpenBao, prove AppRole login fails, then unseal. Prints no key material."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ADDR = os.environ["BAO_ADDR"].rstrip("/")
|
||||||
|
CAFILE = os.environ["TLS_CA_FILE"]
|
||||||
|
INIT = json.loads(Path(os.environ["BAO_INIT_FILE"]).read_text(encoding="utf-8"))
|
||||||
|
ROLE = Path("/secrets/worker.role_id").read_text(encoding="utf-8").strip()
|
||||||
|
SECRET = Path("/secrets/worker.secret_id").read_text(encoding="utf-8").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def ctx() -> ssl.SSLContext:
|
||||||
|
context = ssl.create_default_context(cafile=CAFILE)
|
||||||
|
context.check_hostname = True
|
||||||
|
context.verify_mode = ssl.CERT_REQUIRED
|
||||||
|
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
def call(method: str, path: str, body: dict | None = None, token: str = "") -> int:
|
||||||
|
data = None if body is None else json.dumps(body).encode("utf-8")
|
||||||
|
request = urllib.request.Request(ADDR + path, data=data, method=method)
|
||||||
|
request.add_header("Content-Type", "application/json")
|
||||||
|
if token:
|
||||||
|
request.add_header("X-Vault-Token", token)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, context=ctx(), timeout=5) as response:
|
||||||
|
response.read()
|
||||||
|
return response.status
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
exc.read()
|
||||||
|
return exc.code
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
token = INIT.get("root_token") or ""
|
||||||
|
key = (INIT.get("keys") or [""])[0]
|
||||||
|
if not token or not key:
|
||||||
|
raise SystemExit("operator init file is incomplete")
|
||||||
|
sealed = False
|
||||||
|
try:
|
||||||
|
code = call("PUT", "/v1/sys/seal", token=token)
|
||||||
|
if code not in (200, 204):
|
||||||
|
raise SystemExit("FAIL seal returned HTTP %s" % code)
|
||||||
|
sealed = True
|
||||||
|
login = call(
|
||||||
|
"POST",
|
||||||
|
"/v1/auth/approle/login",
|
||||||
|
{"role_id": ROLE, "secret_id": SECRET},
|
||||||
|
)
|
||||||
|
if login == 200:
|
||||||
|
raise SystemExit("FAIL sealed OpenBao accepted AppRole")
|
||||||
|
print("PASS sealed OpenBao rejects AppRole", login)
|
||||||
|
finally:
|
||||||
|
if sealed:
|
||||||
|
status = call("POST", "/v1/sys/unseal", {"key": key})
|
||||||
|
if status != 200:
|
||||||
|
raise SystemExit("FAIL unseal returned HTTP %s" % status)
|
||||||
|
print("PASS OpenBao unsealed")
|
||||||
|
login = call(
|
||||||
|
"POST",
|
||||||
|
"/v1/auth/approle/login",
|
||||||
|
{"role_id": ROLE, "secret_id": SECRET},
|
||||||
|
)
|
||||||
|
if login != 200:
|
||||||
|
raise SystemExit("FAIL AppRole login after unseal HTTP %s" % login)
|
||||||
|
print("PASS AppRole login after unseal")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Rehash and shared login budget. Prints parameters and timings only."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROBE = Path(__file__).resolve()
|
||||||
|
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
|
||||||
|
|
||||||
|
|
||||||
|
def https(method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> tuple[int, str]:
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||||
|
ctx.load_verify_locations("/certs/ca.crt")
|
||||||
|
ctx.check_hostname = True
|
||||||
|
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||||
|
raw = socket.create_connection(("host.docker.internal", 8443), timeout=10)
|
||||||
|
tls = ctx.wrap_socket(raw, server_hostname="localhost")
|
||||||
|
header_lines = ["%s %s HTTP/1.1" % (method, path), "Host: localhost", "Connection: close"]
|
||||||
|
for key, value in (headers or {}).items():
|
||||||
|
header_lines.append("%s: %s" % (key, value))
|
||||||
|
if body is not None:
|
||||||
|
header_lines.append("Content-Type: application/json")
|
||||||
|
header_lines.append("Content-Length: %s" % len(body))
|
||||||
|
payload = ("\r\n".join(header_lines) + "\r\n\r\n").encode("ascii")
|
||||||
|
if body is not None:
|
||||||
|
payload += body
|
||||||
|
tls.sendall(payload)
|
||||||
|
data = b""
|
||||||
|
while True:
|
||||||
|
chunk = tls.recv(8192)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
data += chunk
|
||||||
|
tls.close()
|
||||||
|
head, _, _rest = data.partition(b"\r\n\r\n")
|
||||||
|
text = head.decode("latin1", "replace")
|
||||||
|
status = int(text.split(" ", 2)[1])
|
||||||
|
return status, text
|
||||||
|
|
||||||
|
|
||||||
|
def internal() -> None:
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
|
||||||
|
from app import bao, db
|
||||||
|
|
||||||
|
username = "rehash_" + uuid.uuid4().hex[:10]
|
||||||
|
password = "synthetic-rehash-password"
|
||||||
|
status, _headers = https(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/users",
|
||||||
|
json.dumps(
|
||||||
|
{"username": username, "display_name": "rehash probe", "password": password}
|
||||||
|
).encode("utf-8"),
|
||||||
|
)
|
||||||
|
if status != 201:
|
||||||
|
raise SystemExit("FAIL register %s" % status)
|
||||||
|
bao.apply()
|
||||||
|
|
||||||
|
async def memory_param() -> str:
|
||||||
|
pool = await db.connect()
|
||||||
|
try:
|
||||||
|
row = await pool.fetchrow(
|
||||||
|
"SELECT substring(password_hash from 'm=[0-9]+') AS param FROM users WHERE username = $1",
|
||||||
|
username,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
await db.close()
|
||||||
|
return row["param"]
|
||||||
|
|
||||||
|
weak = PasswordHasher(memory_cost=8192, time_cost=1, parallelism=1, hash_len=32, salt_len=16).hash(password)
|
||||||
|
|
||||||
|
async def store_weak() -> None:
|
||||||
|
pool = await db.connect()
|
||||||
|
try:
|
||||||
|
await pool.execute(
|
||||||
|
"UPDATE users SET password_hash = $1 WHERE username = $2",
|
||||||
|
weak,
|
||||||
|
username,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
await db.close()
|
||||||
|
|
||||||
|
asyncio.run(store_weak())
|
||||||
|
before = asyncio.run(memory_param())
|
||||||
|
print("rehash_before", before)
|
||||||
|
basic = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||||
|
started = time.perf_counter()
|
||||||
|
status, headers = https(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers={"Authorization": "Basic " + basic},
|
||||||
|
)
|
||||||
|
login_ms = (time.perf_counter() - started) * 1000
|
||||||
|
if status != 201:
|
||||||
|
raise SystemExit("FAIL rehash login %s" % status)
|
||||||
|
after = asyncio.run(memory_param())
|
||||||
|
print("rehash_after", after, "login_ms=%.1f" % login_ms)
|
||||||
|
if before != "m=8192" or after != "m=19456":
|
||||||
|
raise SystemExit("FAIL rehash did not move to the floor")
|
||||||
|
|
||||||
|
wrong = base64.b64encode((username + ":wrong-password").encode("utf-8")).decode("ascii")
|
||||||
|
limited_status = None
|
||||||
|
for attempt in range(2, 12):
|
||||||
|
started = time.perf_counter()
|
||||||
|
status, headers = https(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers={"Authorization": "Basic " + wrong},
|
||||||
|
)
|
||||||
|
elapsed = (time.perf_counter() - started) * 1000
|
||||||
|
if status == 429:
|
||||||
|
if "retry-after" not in headers.lower():
|
||||||
|
raise SystemExit("FAIL 429 without Retry-After")
|
||||||
|
print("rate_limit_attempt", attempt, "status", status, "elapsed_ms=%.1f" % elapsed)
|
||||||
|
limited_status = status
|
||||||
|
break
|
||||||
|
if status != 401:
|
||||||
|
raise SystemExit("FAIL unexpected login status %s" % status)
|
||||||
|
if attempt == 8:
|
||||||
|
print("argon2_reject_attempt", attempt, "elapsed_ms=%.1f" % elapsed)
|
||||||
|
if limited_status != 429:
|
||||||
|
raise SystemExit("FAIL shared rate limit did not return 429")
|
||||||
|
print("PASS rehash and shared login limit")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
if "--internal" in sys.argv:
|
||||||
|
internal()
|
||||||
|
return
|
||||||
|
completed = subprocess.run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"--env-file",
|
||||||
|
".env",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--no-deps",
|
||||||
|
"--entrypoint",
|
||||||
|
"python",
|
||||||
|
"-e",
|
||||||
|
"PYTHONPATH=/app",
|
||||||
|
"-v",
|
||||||
|
"%s:/probe.py:ro" % PROBE,
|
||||||
|
"api",
|
||||||
|
"/probe.py",
|
||||||
|
"--internal",
|
||||||
|
],
|
||||||
|
cwd=ROOT,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
if completed.returncode != 0:
|
||||||
|
raise SystemExit(completed.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main() or 0)
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Grade 4 rotation/revocation plus track 1, the worker compromise comparison.
|
||||||
|
|
||||||
|
Stops the worker, leaves one upload queued, revokes the old worker leaf,
|
||||||
|
rotates the worker database password, then shows the same job still reaches ready.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
|
||||||
|
from client import Client # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def run(args: list[str], check: bool = True) -> subprocess.CompletedProcess:
|
||||||
|
completed = subprocess.run(args, cwd=ROOT, check=False)
|
||||||
|
if check and completed.returncode != 0:
|
||||||
|
raise SystemExit("command failed: %s" % " ".join(args[:6]))
|
||||||
|
return completed
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args: str, check: bool = True) -> subprocess.CompletedProcess:
|
||||||
|
return run(["docker", "compose", "--env-file", ".env", *args], check=check)
|
||||||
|
|
||||||
|
|
||||||
|
def reissue(name: str, cn: str, eku: str, san: str, not_before: str = "", not_after: str = "") -> None:
|
||||||
|
env_args: list[str] = []
|
||||||
|
if not_before:
|
||||||
|
env_args.extend(["-e", "NOT_BEFORE=" + not_before])
|
||||||
|
if not_after:
|
||||||
|
env_args.extend(["-e", "NOT_AFTER=" + not_after])
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
*env_args,
|
||||||
|
"-v",
|
||||||
|
"%s:/work" % (ROOT / "certs"),
|
||||||
|
"-v",
|
||||||
|
"%s:/reissue-leaf.sh:ro" % (ROOT / "scripts" / "reissue-leaf.sh"),
|
||||||
|
"alpine:3.21.3",
|
||||||
|
"sh",
|
||||||
|
"/reissue-leaf.sh",
|
||||||
|
name,
|
||||||
|
cn,
|
||||||
|
eku,
|
||||||
|
san,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def worker_rights() -> None:
|
||||||
|
completed = compose(
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--no-deps",
|
||||||
|
"--entrypoint",
|
||||||
|
"python",
|
||||||
|
"-e",
|
||||||
|
"PYTHONPATH=/app",
|
||||||
|
"-e",
|
||||||
|
"BAO_ROLE_ID_FILE=/run/worker/role_id",
|
||||||
|
"-e",
|
||||||
|
"BAO_SECRET_ID_FILE=/run/worker/secret_id",
|
||||||
|
"-e",
|
||||||
|
"BAO_SECRET_PATH=secret/data/messenger/worker",
|
||||||
|
"-e",
|
||||||
|
"TLS_CERT_FILE=/certs/worker-client.crt",
|
||||||
|
"-e",
|
||||||
|
"TLS_KEY_FILE=/certs/worker-client.key",
|
||||||
|
"-v",
|
||||||
|
"%s:/run/worker/role_id:ro" % (ROOT / "secrets" / "worker.role_id"),
|
||||||
|
"-v",
|
||||||
|
"%s:/run/worker/secret_id:ro" % (ROOT / "secrets" / "worker.secret_id"),
|
||||||
|
"-v",
|
||||||
|
"%s:/certs/worker-client.crt:ro" % (ROOT / "certs" / "worker-client.crt"),
|
||||||
|
"-v",
|
||||||
|
"%s:/certs/worker-client.key:ro" % (ROOT / "certs" / "worker-client.key"),
|
||||||
|
"-v",
|
||||||
|
"%s:/probe.py:ro" % (ROOT / "student-tests" / "worker_rights.py"),
|
||||||
|
"api",
|
||||||
|
"/probe.py",
|
||||||
|
)
|
||||||
|
if completed.returncode != 0:
|
||||||
|
raise SystemExit(completed.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_db_password() -> None:
|
||||||
|
path = ROOT / "secrets" / "db_worker_password"
|
||||||
|
path.write_text(secrets.token_hex(24), encoding="utf-8")
|
||||||
|
container = subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"],
|
||||||
|
cwd=ROOT,
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
).stdout.strip()
|
||||||
|
run(["docker", "cp", str(path), "%s:/tmp/db_worker_password" % container])
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"exec",
|
||||||
|
container,
|
||||||
|
"sh",
|
||||||
|
"-c",
|
||||||
|
"psql -v ON_ERROR_STOP=1 -U messenger -d messenger -c \"ALTER ROLE messenger_worker PASSWORD '$(cat /tmp/db_worker_password)'\" && rm -f /tmp/db_worker_password",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
compose(
|
||||||
|
"--profile",
|
||||||
|
"bootstrap",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--entrypoint",
|
||||||
|
"python",
|
||||||
|
"-e",
|
||||||
|
"BAO_REFRESH_KV_ONLY=1",
|
||||||
|
"-v",
|
||||||
|
"%s:/app/app/tools/openbao_bootstrap.py:ro" % (ROOT / "app" / "tools" / "openbao_bootstrap.py"),
|
||||||
|
"openbao-bootstrap",
|
||||||
|
"-m",
|
||||||
|
"app.tools.openbao_bootstrap",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def image_id() -> str:
|
||||||
|
completed = subprocess.run(
|
||||||
|
["docker", "image", "inspect", "mtusi-messenger:lab7", "--format", "{{.Id}}"],
|
||||||
|
cwd=ROOT,
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
return completed.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
before_image = image_id()
|
||||||
|
print("image_before", before_image.split(":")[-1][:12])
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"-v",
|
||||||
|
"%s:/work" % (ROOT / "certs"),
|
||||||
|
"-v",
|
||||||
|
"%s:/gen-certs.sh:ro" % (ROOT / "scripts" / "gen-certs.sh"),
|
||||||
|
"alpine:3.21.3",
|
||||||
|
"sh",
|
||||||
|
"/gen-certs.sh",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
compose("up", "-d", "--no-deps", "--force-recreate", "rabbit-mtls", "otel-mtls")
|
||||||
|
time.sleep(2)
|
||||||
|
worker_rights()
|
||||||
|
users = compose(
|
||||||
|
"exec",
|
||||||
|
"-T",
|
||||||
|
"postgres",
|
||||||
|
"psql",
|
||||||
|
"-U",
|
||||||
|
"messenger",
|
||||||
|
"-d",
|
||||||
|
"messenger",
|
||||||
|
"-tAc",
|
||||||
|
"SELECT count(*) FROM users",
|
||||||
|
)
|
||||||
|
del users
|
||||||
|
print("PASS superuser can read users; worker role cannot")
|
||||||
|
|
||||||
|
compose("stop", "worker")
|
||||||
|
client = Client("https://127.0.0.1:8443", str(ROOT / "certs" / "ca.crt"), timeout=10)
|
||||||
|
alice, _bob, _eve, chat = client.bootstrap()
|
||||||
|
attachment, _content = client.attachment(alice, chat)
|
||||||
|
if attachment["status"] != "queued":
|
||||||
|
raise SystemExit("FAIL upload was not left queued")
|
||||||
|
print("PASS upload queued while worker is stopped")
|
||||||
|
|
||||||
|
certs = ROOT / "certs"
|
||||||
|
shutil.copyfile(certs / "worker-client.crt", certs / "worker-client.revoked.crt")
|
||||||
|
shutil.copyfile(certs / "worker-client.key", certs / "worker-client.revoked.key")
|
||||||
|
reissue(
|
||||||
|
"worker-client",
|
||||||
|
"worker",
|
||||||
|
"clientAuth",
|
||||||
|
"DNS:worker-client,URI:spiffe://messenger/worker",
|
||||||
|
)
|
||||||
|
compose("up", "-d", "--no-deps", "--force-recreate", "rabbit-mtls", "otel-mtls")
|
||||||
|
time.sleep(2)
|
||||||
|
probe = subprocess.run([sys.executable, "-X", "utf8", str(ROOT / "student-tests" / "same_ca_probe.py")], cwd=ROOT)
|
||||||
|
if probe.returncode != 0:
|
||||||
|
raise SystemExit(probe.returncode)
|
||||||
|
|
||||||
|
reissue("lb", "localhost", "serverAuth", "DNS:localhost,IP:127.0.0.1")
|
||||||
|
compose("restart", "lb")
|
||||||
|
time.sleep(2)
|
||||||
|
client.call("GET", "/health/ready", schema="Health")
|
||||||
|
print("PASS lb leaf rotated without an image rebuild")
|
||||||
|
|
||||||
|
rotate_db_password()
|
||||||
|
compose("start", "worker")
|
||||||
|
ready = client.wait_ready(alice, attachment, wait_seconds=90)
|
||||||
|
if ready["status"] != "ready":
|
||||||
|
raise SystemExit("FAIL queued attachment did not become ready after rotation")
|
||||||
|
print("PASS queued job survived worker revocation and secret rotation")
|
||||||
|
worker_rights()
|
||||||
|
|
||||||
|
reissue(
|
||||||
|
"expired-worker",
|
||||||
|
"worker",
|
||||||
|
"clientAuth",
|
||||||
|
"URI:spiffe://messenger/worker",
|
||||||
|
not_before="20200101000000Z",
|
||||||
|
not_after="20200102000000Z",
|
||||||
|
)
|
||||||
|
probe = subprocess.run([sys.executable, "-X", "utf8", str(ROOT / "student-tests" / "same_ca_probe.py")], cwd=ROOT)
|
||||||
|
if probe.returncode != 0:
|
||||||
|
raise SystemExit(probe.returncode)
|
||||||
|
|
||||||
|
seal = compose(
|
||||||
|
"--profile",
|
||||||
|
"bootstrap",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"--no-deps",
|
||||||
|
"--entrypoint",
|
||||||
|
"python",
|
||||||
|
"-v",
|
||||||
|
"%s:/probe.py:ro" % (ROOT / "student-tests" / "seal_probe.py"),
|
||||||
|
"openbao-bootstrap",
|
||||||
|
"/probe.py",
|
||||||
|
)
|
||||||
|
if seal.returncode != 0:
|
||||||
|
raise SystemExit(seal.returncode)
|
||||||
|
after_image = image_id()
|
||||||
|
if before_image != after_image:
|
||||||
|
raise SystemExit("FAIL application image changed during rotation")
|
||||||
|
print("PASS image unchanged", after_image.split(":")[-1][:12])
|
||||||
|
print("PASS track1 and grade4 lifecycle")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""What the worker credential can and cannot do. Prints statuses, not secrets."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import asyncpg
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
|
||||||
|
from app import bao, broker, config, db, s3, tlsutil
|
||||||
|
|
||||||
|
|
||||||
|
def openbao_status(path: str) -> str:
|
||||||
|
try:
|
||||||
|
login = bao._request(
|
||||||
|
"POST",
|
||||||
|
"/v1/auth/approle/login",
|
||||||
|
{"role_id": config.BAO_ROLE_ID, "secret_id": config.BAO_SECRET_ID},
|
||||||
|
)
|
||||||
|
token = (login.get("auth") or {}).get("client_token") or ""
|
||||||
|
bao._request("GET", path, token=token)
|
||||||
|
return "200"
|
||||||
|
except RuntimeError as exc:
|
||||||
|
text = str(exc)
|
||||||
|
if "HTTP " in text:
|
||||||
|
return text.split("HTTP ", 1)[1]
|
||||||
|
return "error"
|
||||||
|
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
bao.apply()
|
||||||
|
pool = await db.connect()
|
||||||
|
try:
|
||||||
|
await pool.fetchval("SELECT count(*) FROM attachments")
|
||||||
|
print("PASS worker db read attachments")
|
||||||
|
try:
|
||||||
|
await pool.fetchval("SELECT count(*) FROM users")
|
||||||
|
except asyncpg.InsufficientPrivilegeError:
|
||||||
|
print("PASS worker db cannot read users")
|
||||||
|
else:
|
||||||
|
raise SystemExit("FAIL worker read the users table")
|
||||||
|
finally:
|
||||||
|
await db.close()
|
||||||
|
|
||||||
|
client = s3._client_or_create()
|
||||||
|
key = "variants/track1-%s" % uuid.uuid4().hex
|
||||||
|
client.put_object(Bucket=config.S3_BUCKET, Key=key, Body=b"ok")
|
||||||
|
client.delete_object(Bucket=config.S3_BUCKET, Key=key)
|
||||||
|
print("PASS worker s3 write variants")
|
||||||
|
try:
|
||||||
|
client.put_object(Bucket=config.S3_BUCKET, Key="secrets/track1", Body=b"no")
|
||||||
|
except ClientError as exc:
|
||||||
|
code = exc.response.get("Error", {}).get("Code", "")
|
||||||
|
print("PASS worker s3 cannot write secrets", code)
|
||||||
|
else:
|
||||||
|
raise SystemExit("FAIL worker wrote secrets/")
|
||||||
|
|
||||||
|
connection = await __import__("aio_pika").connect_robust(
|
||||||
|
config.BROKER_URL,
|
||||||
|
ssl_context=tlsutil.server_context(),
|
||||||
|
)
|
||||||
|
channel = await connection.channel()
|
||||||
|
try:
|
||||||
|
await channel.declare_queue("stolen.queue", durable=False, auto_delete=True)
|
||||||
|
except Exception as exc:
|
||||||
|
print("PASS worker broker cannot declare stolen.queue", type(exc).__name__)
|
||||||
|
else:
|
||||||
|
raise SystemExit("FAIL worker declared stolen.queue")
|
||||||
|
await connection.close()
|
||||||
|
|
||||||
|
connection = await __import__("aio_pika").connect_robust(
|
||||||
|
config.BROKER_URL,
|
||||||
|
ssl_context=tlsutil.server_context(),
|
||||||
|
)
|
||||||
|
channel = await connection.channel()
|
||||||
|
await channel.declare_queue(broker.QUEUE, durable=True, passive=True)
|
||||||
|
await connection.close()
|
||||||
|
print("PASS worker broker can see attachment.jobs")
|
||||||
|
|
||||||
|
own = openbao_status("/v1/secret/data/messenger/worker")
|
||||||
|
foreign = openbao_status("/v1/secret/data/messenger/api")
|
||||||
|
print("PASS worker openbao own path", own)
|
||||||
|
print("PASS worker openbao api path", foreign)
|
||||||
|
if own != "200" or foreign != "403":
|
||||||
|
raise SystemExit("FAIL worker OpenBao policy own=%s api=%s" % (own, foreign))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
Reference in New Issue
Block a user