This commit is contained in:
@@ -9,13 +9,14 @@
|
||||
|
||||
Нужны Docker с Compose, Python 3.9+ для операторских и публичных скриптов и OpenSSL. Порты по умолчанию: HTTPS API `127.0.0.1:8443`, OpenBao `127.0.0.1:18200`, Grafana `127.0.0.1:3000`. Если порт занят, измените `PUBLIC_HTTPS_PORT`, `BAO_HOST_PORT` или `GRAFANA_HOST_PORT` в `.env`; для операторского скрипта при изменённом порте OpenBao задайте `BAO_OPERATOR_ADDR=https://localhost:<порт>`.
|
||||
|
||||
Чистый запуск проверен на Docker Desktop для macOS. Права на файловые Compose secrets при запуске на Linux отдельно не проверены; non-root процессы должны иметь доступ только к назначенным им файлам. Переменные в `.env.example` являются подсказками задания: сетевые адреса контейнеров и пути секретов фактически заданы в `compose.yaml`.
|
||||
Чистый запуск проверен на Docker Desktop для macOS. После генерации secrets выполните `scripts/prepare-secret-access.py`: каталог остаётся 0700, отдельно монтируемые файлы получают 0640 и группу оператора; её GID записывается в `.env` как `LAB_SECRET_GID` и добавляется контейнерам через `group_add`. CA key и operator JSON остаются 0600 и не монтируются приложениям. После повторной генерации secrets повторите этот шаг. Это учитывает [ограничение Compose для file secrets](https://docs.docker.com/reference/compose-file/services/#secrets): uid/gid/mode не переназначаются для bind-mounted файлов. Полный запуск на отдельном Linux-хосте пока не проверен. Переменные в `.env.example` являются подсказками задания: сетевые адреса контейнеров и пути секретов фактически заданы в `compose.yaml`.
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
python3 scripts/init-secrets.py
|
||||
sh scripts/bootstrap-pki.sh
|
||||
sh scripts/bootstrap-internal-pki.sh
|
||||
python3 scripts/prepare-secret-access.py
|
||||
docker compose --env-file .env up -d openbao
|
||||
# Дождаться ответа статуса, затем один раз инициализировать:
|
||||
python3 scripts/openbao-operator.py status
|
||||
@@ -66,7 +67,7 @@ OpenBao использует persistent file storage вне dev-mode. API и wor
|
||||
|
||||
Argon2id настроен на `m=19456 KiB`, `t=2`, `p=1`. Один запуск `docker compose exec -T api-a /app/.venv/bin/python - < scripts/benchmark-argon2.py` выполнил по 10 последовательных хеширований и проверок: медианы 11,84 и 11,27 мс. Контейнер API ограничен 0,5 CPU и 512 MiB; Docker сообщил 10 CPU и 10 416 644 096 байт памяти. Параметры соответствуют минимуму задания, а замер показывает задержку одной операции на этом стенде; выбор не исследован при параллельной нагрузке и не является оценкой устойчивости к DoS.
|
||||
|
||||
`docker inspect` показал для API и worker пользователя `65534:65534`, `privileged=false` и `cap_drop=[ALL]`; лимиты API — 0,5 CPU/512 MiB, worker — 2 CPU/4 GiB. Конфигурация остальных сервисов также содержит CPU и memory limits. Для защиты необходима отдельная демонстрация отсутствия лишних опубликованных портов и утечек в telemetry.
|
||||
`docker inspect` показал для API и worker пользователя `65534:65534`, `privileged=false` и `cap_drop=[ALL]`; лимиты API — 0,5 CPU/512 MiB, worker — 2 CPU/4 GiB. Конфигурация остальных сервисов также содержит CPU и memory limits. Повторная проверка `python3 student-tests/runtime_hardening.py` подтверждает ограничения фактически работающих контейнеров. `student-tests/ingress_redaction.py` проверяет отсутствие синтетических секретов в access-логах; `student-tests/telemetry_unit.py` — фильтрацию полей OTLP. Это не исчерпывающий аудит всех каналов утечки.
|
||||
|
||||
## Ограничения
|
||||
|
||||
@@ -75,3 +76,13 @@ Rate limit локален каждой API-реплике: 60 попыток з
|
||||
Для SeaweedFS опубликовано [сообщение о обходе bucket policy через POST Object](https://github.com/seaweedfs/seaweedfs/security/advisories/GHSA-qmx6-fpcw-q3xg), в котором указаны затронутые версии до 4.45 включительно и отсутствие исправленной версии на дату публикации. Стенд использует 4.17. В приложении POST Object не нужен; прокси запрещает HTTP POST, что проверяет `student-tests/dependency_tls.py`. Это ограничение конкретного пути, а не утверждение об устранении всех уязвимостей SeaweedFS.
|
||||
|
||||
Не проверены все возможные пути утечки секретов в телеметрию и все сценарии отказа зависимостей. Оценка не подтверждается одним smoke-тестом.
|
||||
|
||||
## Повторный строгий аудит
|
||||
|
||||
Обнаружена и воспроизведена запись синтетического секрета из query string в stdout HAProxy. `infra/haproxy.cfg` теперь пишет только статус, размер, backend/server и код завершения; URL и заголовки исключены. Регрессия: `BASE_URL=https://localhost:18443 python3 student-tests/ingress_redaction.py`. Проверка касается этих access-логов, а не всех потенциальных каналов утечки.
|
||||
|
||||
Добавлены подготовка прав файлов secrets для non-root контейнеров и зависимость outbox/reconcile от успешного `db-provision`, чтобы запуск не опережал выдачу прав БД. S3-прокси явно отклоняет повторные Authorization; в проверенном исходном сценарии обход ACL не воспроизвёлся (403), поэтому это усиление, а не подтверждённая уязвимость.
|
||||
|
||||
Повторные проверки сохранены в [evidence/lab7-strict-audit.json](evidence/lab7-strict-audit.json): HTTPS smoke, внешний TLS, mTLS обеих реплик, ACL/expiry/hostname, scoped policies и права API/worker, TLS зависимостей, лимиты, OTLP redaction и доступ Grafana к трём источникам. Linux DAC проверен в одноразовом контейнере на синтетических файлах (`student-tests/secret_file_permissions.py`), без утверждения о полном развёртывании на отдельном Linux-хосте.
|
||||
|
||||
После исправлений повторно прошёл persistence с фактическими временами рестарта (`evidence/lab7-persistence.json`). Повторный последовательный failover и восстановление API-A/API-B фиксируются отдельно в `evidence/lab7-failover-audit.json`. Публичные тесты и контракт не изменялись.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
x-api: &api
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
cap_drop: [ALL]
|
||||
@@ -63,6 +64,7 @@ x-api: &api
|
||||
|
||||
services:
|
||||
openbao:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: openbao/openbao:2.3.2
|
||||
user: "0:0"
|
||||
entrypoint: ["bao"]
|
||||
@@ -83,6 +85,7 @@ services:
|
||||
cpus: "0.50"
|
||||
|
||||
broker:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
hostname: broker
|
||||
extra_hosts: ["broker:127.0.0.1"]
|
||||
@@ -115,6 +118,7 @@ services:
|
||||
memory: 256M
|
||||
|
||||
broker-tcp:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:broker
|
||||
depends_on:
|
||||
@@ -127,6 +131,7 @@ services:
|
||||
cpus: "0.25"
|
||||
|
||||
s3:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: chrislusf/seaweedfs:4.17@sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9
|
||||
command: ["server", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=127.0.0.1", "-s3", "-s3.port=18333", "-s3.config=/run/secrets/s3_config", "-s3.cert.file=/run/secrets/s3_tls", "-s3.key.file=/run/secrets/s3_tls", "-master.volumeSizeLimitMB=128", "-volume.max=64", "-s3.port.iceberg=0", "-filer.exposeDirectoryData=false"]
|
||||
secrets:
|
||||
@@ -148,6 +153,7 @@ services:
|
||||
memory: 512M
|
||||
|
||||
s3-tcp:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:s3
|
||||
depends_on:
|
||||
@@ -166,6 +172,7 @@ services:
|
||||
cpus: "0.25"
|
||||
|
||||
s3-init:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.bootstrap_s3"]
|
||||
@@ -187,6 +194,7 @@ services:
|
||||
cpus: "0.50"
|
||||
|
||||
postgres:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: postgres:17.6-alpine
|
||||
entrypoint: ["/bin/sh", "/usr/local/bin/postgres-tls-entrypoint.sh"]
|
||||
command: ["postgres", "-c", "track_commit_timestamp=on", "-c", "ssl=on", "-c", "ssl_cert_file=/tmp/postgres-tls/server.pem", "-c", "ssl_key_file=/tmp/postgres-tls/server.pem", "-c", "hba_file=/etc/postgresql/pg_hba.conf"]
|
||||
@@ -214,6 +222,7 @@ services:
|
||||
memory: 512M
|
||||
|
||||
migrate:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.migrate"]
|
||||
@@ -236,6 +245,7 @@ services:
|
||||
memory: 128M
|
||||
|
||||
db-provision:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.provision_db_roles"]
|
||||
@@ -254,6 +264,7 @@ services:
|
||||
cpus: "0.25"
|
||||
|
||||
reconcile:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
healthcheck:
|
||||
disable: true
|
||||
build:
|
||||
@@ -278,6 +289,8 @@ services:
|
||||
- s3_reconcile_access_key_id
|
||||
- s3_reconcile_secret_access_key
|
||||
depends_on:
|
||||
db-provision:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
s3:
|
||||
@@ -297,6 +310,7 @@ services:
|
||||
<<: *api
|
||||
|
||||
api-a-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:api-a
|
||||
depends_on:
|
||||
@@ -311,6 +325,7 @@ services:
|
||||
cpus: "0.25"
|
||||
|
||||
api-b-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:api-b
|
||||
depends_on:
|
||||
@@ -325,6 +340,7 @@ services:
|
||||
cpus: "0.25"
|
||||
|
||||
worker:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
restart: unless-stopped
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
@@ -384,6 +400,7 @@ services:
|
||||
stop_grace_period: 30s
|
||||
|
||||
outbox:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
mem_limit: 256m
|
||||
cpus: "0.50"
|
||||
cap_drop: [ALL]
|
||||
@@ -414,6 +431,8 @@ services:
|
||||
- broker_outbox_url
|
||||
- otel_outbox_cert
|
||||
depends_on:
|
||||
db-provision:
|
||||
condition: service_completed_successfully
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
broker:
|
||||
@@ -423,6 +442,7 @@ services:
|
||||
restart: unless-stopped
|
||||
|
||||
load_balancer:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
ports:
|
||||
- "127.0.0.1:${PUBLIC_HTTPS_PORT:-8443}:8443"
|
||||
@@ -453,6 +473,7 @@ services:
|
||||
memory: 128M
|
||||
|
||||
otel-collector:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: otel/opentelemetry-collector-contrib:0.120.0
|
||||
command: ["--config=/etc/otelcol/config.yaml"]
|
||||
volumes:
|
||||
@@ -462,6 +483,7 @@ services:
|
||||
cpus: "0.50"
|
||||
restart: unless-stopped
|
||||
otel-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:otel-collector
|
||||
depends_on: [otel-collector]
|
||||
@@ -473,6 +495,7 @@ services:
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
prometheus:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: prom/prometheus:v3.2.1
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
@@ -484,6 +507,7 @@ services:
|
||||
- prometheus_data:/prometheus
|
||||
restart: unless-stopped
|
||||
prometheus-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:prometheus
|
||||
depends_on: [prometheus]
|
||||
@@ -495,6 +519,7 @@ services:
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
loki:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: grafana/loki:3.4.2
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
@@ -504,6 +529,7 @@ services:
|
||||
- loki_data:/loki
|
||||
restart: unless-stopped
|
||||
loki-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:loki
|
||||
depends_on: [loki]
|
||||
@@ -515,6 +541,7 @@ services:
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
tempo:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: grafana/tempo:2.7.1
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
@@ -524,6 +551,7 @@ services:
|
||||
- tempo_data:/var/tempo
|
||||
restart: unless-stopped
|
||||
tempo-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:tempo
|
||||
depends_on: [tempo]
|
||||
@@ -535,6 +563,7 @@ services:
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
grafana:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: grafana/grafana:11.5.2
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"stopped": [
|
||||
"api-a"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/resilience.py --mode failover --action-script \"scripts/stop-one.sh\" --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nExecuting explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 90, \"failed_attempts\": 2, \"first_recovery_seconds\": 2.58}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.\n"
|
||||
},
|
||||
{
|
||||
"stopped": [
|
||||
"api-b"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/resilience.py --mode failover --action-script \"scripts/stop-one.sh\" --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nExecuting explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 108, \"failed_attempts\": 1, \"first_recovery_seconds\": 2.573}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.\n"
|
||||
}
|
||||
],
|
||||
"both_replicas_tested": true
|
||||
}
|
||||
@@ -3,40 +3,40 @@
|
||||
"command": "make test-persistence ACTION_SCRIPT=scripts/restart.sh",
|
||||
"services": {
|
||||
"postgres": {
|
||||
"before": "2026-11-07T11:21:11.514449215Z",
|
||||
"after": "2026-11-07T11:31:51.644584012Z"
|
||||
"before": "2026-11-07T18:37:40.342662055Z",
|
||||
"after": "2026-11-07T18:40:29.165485675Z"
|
||||
},
|
||||
"s3": {
|
||||
"before": "2026-11-07T11:21:14.448491467Z",
|
||||
"after": "2026-11-07T11:31:54.493811096Z"
|
||||
"before": "2026-11-07T18:37:40.258400055Z",
|
||||
"after": "2026-11-07T18:40:32.078899093Z"
|
||||
},
|
||||
"broker": {
|
||||
"before": "2026-11-07T11:21:12.477210382Z",
|
||||
"after": "2026-11-07T11:31:52.565561429Z"
|
||||
"before": "2026-11-07T18:37:40.181643097Z",
|
||||
"after": "2026-11-07T18:40:30.133283175Z"
|
||||
},
|
||||
"openbao": {
|
||||
"before": "2026-11-07T11:21:11.728365965Z",
|
||||
"after": "2026-11-07T11:31:51.983157637Z"
|
||||
"before": "2026-11-07T18:37:25.793975132Z",
|
||||
"after": "2026-11-07T18:40:29.375343008Z"
|
||||
},
|
||||
"prometheus": {
|
||||
"before": "2026-11-07T11:21:11.498290965Z",
|
||||
"after": "2026-11-07T11:31:51.625424303Z"
|
||||
"before": "2026-11-07T18:37:40.556532722Z",
|
||||
"after": "2026-11-07T18:40:29.121133508Z"
|
||||
},
|
||||
"loki": {
|
||||
"before": "2026-11-07T11:21:14.486210217Z",
|
||||
"after": "2026-11-07T11:31:53.332075471Z"
|
||||
"before": "2026-11-07T18:37:40.63945868Z",
|
||||
"after": "2026-11-07T18:40:30.996157426Z"
|
||||
},
|
||||
"tempo": {
|
||||
"before": "2026-11-07T11:21:13.305379716Z",
|
||||
"after": "2026-11-07T11:31:52.261244679Z"
|
||||
"before": "2026-11-07T18:37:40.724841472Z",
|
||||
"after": "2026-11-07T18:40:30.060878259Z"
|
||||
},
|
||||
"api-a": {
|
||||
"before": "2026-11-07T11:21:36.434313963Z",
|
||||
"after": "2026-11-07T11:32:15.545949676Z"
|
||||
"before": "2026-11-07T18:39:11.623110833Z",
|
||||
"after": "2026-11-07T18:40:53.924133089Z"
|
||||
},
|
||||
"api-b": {
|
||||
"before": "2026-11-07T11:21:36.45464788Z",
|
||||
"after": "2026-11-07T11:32:15.598332884Z"
|
||||
"before": "2026-11-07T18:39:11.708902667Z",
|
||||
"after": "2026-11-07T18:40:53.958697422Z"
|
||||
}
|
||||
},
|
||||
"test_output": "python3 tests/resilience.py --mode persistence --action-script \"scripts/restart.sh\" --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nExecuting explicit persistence hook; hook output suppressed to avoid leaking secrets.\nPASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence."
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
{
|
||||
"time": "2026-11-07T18:39:57.470382+00:00",
|
||||
"results": [
|
||||
{
|
||||
"test": "structure",
|
||||
"command": [
|
||||
"make",
|
||||
"check"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 scripts/check_contract.py\nPASS: offline skeleton structure, local refs and Python syntax; application NOT tested.\n"
|
||||
},
|
||||
{
|
||||
"test": "smoke",
|
||||
"command": [
|
||||
"make",
|
||||
"test"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/smoke.py --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nPASS: lab7 public API scenario; infrastructure and grading evidence remain separate.\n"
|
||||
},
|
||||
{
|
||||
"test": "external TLS",
|
||||
"command": [
|
||||
"make",
|
||||
"test-security"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/security.py --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nPASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.\n"
|
||||
},
|
||||
{
|
||||
"test": "mTLS",
|
||||
"command": [
|
||||
"sh",
|
||||
"scripts/test-internal-mtls.sh"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api-a: valid identity accepted; no cert, foreign CA and wrong role rejected; direct API closed\nPASS api-b: valid identity accepted; no cert, foreign CA and wrong role rejected; direct API closed\n"
|
||||
},
|
||||
{
|
||||
"test": "access log redaction",
|
||||
"command": [
|
||||
"python3",
|
||||
"student-tests/ingress_redaction.py"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: ingress/API access records present; query, path and header markers absent\n"
|
||||
},
|
||||
{
|
||||
"test": "ACL expiry hostname",
|
||||
"command": [
|
||||
"python3",
|
||||
"student-tests/lab7_security.py",
|
||||
"--base-url",
|
||||
"https://localhost:18443",
|
||||
"--ca-file",
|
||||
"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: wrong hostname rejected; cross-chat attachment denied; expired session rejected\n"
|
||||
},
|
||||
{
|
||||
"test": "api-a openbao_policy",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api: own path allowed; other path and policy write denied\n"
|
||||
},
|
||||
{
|
||||
"test": "api-a service_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api: DB identity and denied privilege; broker denied unauthorized operation\n"
|
||||
},
|
||||
{
|
||||
"test": "api-a s3_prefix_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api: allowed staging write; forbidden prefix denied\nPASS api: duplicate Authorization denied\n"
|
||||
},
|
||||
{
|
||||
"test": "worker openbao_policy",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS worker: own path allowed; other path and policy write denied\n"
|
||||
},
|
||||
{
|
||||
"test": "worker service_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS worker: DB identity and denied privilege; broker denied unauthorized operation\n"
|
||||
},
|
||||
{
|
||||
"test": "worker s3_prefix_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS worker: allowed staging write; forbidden prefix denied\nPASS worker: duplicate Authorization denied\n"
|
||||
},
|
||||
{
|
||||
"test": "postgres_tls",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: PostgreSQL TLS verified, plaintext and untrusted CA rejected\n"
|
||||
},
|
||||
{
|
||||
"test": "dependency_tls",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS s3: verified TLS; untrusted CA rejected\nPASS broker: verified TLS; untrusted CA rejected\nPASS openbao: verified TLS; untrusted CA rejected\nPASS: S3 internal and broker plaintext ports are closed\nPASS: S3 proxy blocks POST\n"
|
||||
},
|
||||
{
|
||||
"test": "telemetry_tls",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: Collector publisher accepted; no cert and wrong role rejected; local listener closed\n"
|
||||
},
|
||||
{
|
||||
"test": "lab7_limits",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "{\"timestamp\": \"2026-11-07T18:39:56.443007+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"ed16f2869c1055cfa8eba8a2c8ddcc26\", \"span_id\": \"3322ff50bd52d312\", \"request_id\": \"791140e4-e019-4902-8943-715409df0a3a\", \"method\": \"POST\", \"route\": \"unmatched\", \"status\": 413}\n.{\"timestamp\": \"2026-11-07T18:39:56.447785+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"8ee51e4ac84311da20f7e9bf76cd8dbc\", \"span_id\": \"5d24a10e81cf49e1\", \"request_id\": \"b009f765-9103-4510-b4a8-452388d746c1\", \"method\": \"POST\", \"route\": \"/api/v1/auth/sessions\", \"status\": 401}\n{\"timestamp\": \"2026-11-07T18:39:56.448485+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"7cf78e312d771b81e3296f8d0f396c72\", \"span_id\": \"76966e6c01b4dedf\", \"request_id\": \"1f2dc31e-17be-433b-b6eb-12a3d548b7cf\", \"method\": \"POST\", \"route\": \"/api/v1/auth/sessions\", \"status\": 429}\n.{\"timestamp\": \"2026-11-07T18:39:56.449173+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"efbb722e22211c38bd5772aab61a12a4\", \"span_id\": \"4d9aa2c1437a6693\", \"request_id\": \"c4a1c350-7dc3-456e-8415-5d0df3644b33\", \"method\": \"POST\", \"route\": \"/api/v1/auth/sessions\", \"status\": 401}\n..\n----------------------------------------------------------------------\nRan 4 tests in 0.026s\n\nOK\n"
|
||||
},
|
||||
{
|
||||
"test": "telemetry_unit",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "......\n----------------------------------------------------------------------\nRan 6 tests in 0.091s\n\nOK\n"
|
||||
},
|
||||
{
|
||||
"test": "observability",
|
||||
"command": [
|
||||
"python3",
|
||||
"student-tests/observability_tls.py"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: Grafana connected to prometheus; data present\nPASS: Grafana connected to loki; data present\nPASS: Grafana connected to tempo; data present\n"
|
||||
}
|
||||
],
|
||||
"additional_checks": {
|
||||
"linux_synthetic_DAC": "PASS: student-tests/secret_file_permissions.py, disposable Linux container; not a full native Linux deployment",
|
||||
"runtime_hardening": "PASS: student-tests/runtime_hardening.py",
|
||||
"validate": "PASS: make validate",
|
||||
"credential_scan": "PASS: current tracked files compared to local generated credentials and private-key markers; Git history and image layers not scanned"
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -4,7 +4,8 @@ global
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
# Never log raw URLs, query strings, headers or request bodies.
|
||||
log-format "ingress status=%ST bytes=%B backend=%b server=%s termination=%tsc"
|
||||
option forwardfor
|
||||
timeout connect 1s
|
||||
timeout client 30s
|
||||
|
||||
@@ -7,6 +7,8 @@ frontend s3_tls
|
||||
bind :8333 ssl crt /run/secrets/server.pem ssl-min-ver TLSv1.2
|
||||
# Multipart form POST is not used by this application; deny it at the boundary.
|
||||
http-request deny if { method POST }
|
||||
# Reject repeated Authorization fields; commas inside SigV4 are valid.
|
||||
http-request deny unless { req.fhdr_cnt(Authorization) eq 1 }
|
||||
# Only the four locally provisioned SigV4 identities may use this endpoint.
|
||||
acl admin_auth req.hdr(Authorization) -m reg -f /run/secrets/admin_acl
|
||||
acl api_auth req.hdr(Authorization) -m reg -f /run/secrets/api_acl
|
||||
|
||||
@@ -8,6 +8,7 @@ import secrets
|
||||
|
||||
root = Path(__file__).resolve().parents[1] / "secrets"
|
||||
root.mkdir(mode=0o700, exist_ok=True)
|
||||
root.chmod(0o700)
|
||||
|
||||
|
||||
def write(name, value):
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Give containers group-read access only to individually mounted secret files.
|
||||
|
||||
The host directory stays owner-only; CA and operator credentials stay 0600.
|
||||
Compose bind-mounted file secrets preserve host ownership on Linux.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
secret_dir = ROOT / 'secrets'
|
||||
if secret_dir.is_symlink():
|
||||
raise SystemExit('secrets directory must not be a symlink')
|
||||
secret_dir.chmod(0o700)
|
||||
compose = (ROOT / 'compose.yaml').read_text()
|
||||
names = set(re.findall(r'\./secrets/([A-Za-z0-9_.-]+)', compose))
|
||||
gid = os.getgid()
|
||||
for name in sorted(names):
|
||||
path = secret_dir / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise SystemExit('Missing or unsafe mounted secret: ' + name)
|
||||
os.chown(path, -1, gid)
|
||||
path.chmod(0o640)
|
||||
for name in ('ca.key', 'openbao-operator.json'):
|
||||
path = secret_dir / name
|
||||
if path.is_symlink():
|
||||
raise SystemExit('Operator credential must not be a symlink')
|
||||
if path.exists():
|
||||
path.chmod(0o600)
|
||||
env = ROOT / '.env'
|
||||
if env.is_symlink():
|
||||
raise SystemExit('.env must not be a symlink')
|
||||
text = env.read_text() if env.exists() else (ROOT / '.env.example').read_text()
|
||||
text = re.sub(r'^LAB_SECRET_GID=.*\n?', '', text, flags=re.M)
|
||||
with env.open('w') as stream:
|
||||
env.chmod(0o600)
|
||||
stream.write(text.rstrip() + '\nLAB_SECRET_GID=' + str(gid) + '\n')
|
||||
print('Mounted secrets: group-readable; host directory: 0700; operator files: 0600.')
|
||||
@@ -18,7 +18,8 @@
|
||||
| Сервис с чужой identity подключается напрямую к API | Только LB вызывает внутренний API | mTLS и проверка разрешённой identity | `sh scripts/test-internal-mtls.sh`: без сертификата, чужой CA, доверенный CA с неверной identity — отказ | Отзыв и ротация identity под нагрузкой не проверены |
|
||||
| Скомпрометированный worker читает чужой секрет | Каждому сервису доступен только нужный набор секретов | Отдельная identity и scoped policy OpenBao | Запросить разрешённый и чужой путь, попробовать изменить policy | Из разрешённых worker данных возможна утечка |
|
||||
| Автоматические попытки входа перегружают KDF | Вход ограничен по частоте | Лимит попыток с 429 и Retry-After | Превысить лимит и проверить ответ, затем дождаться окна | Текущий лимит локален процессу и общий для всех клиентов |
|
||||
| Загрузка чрезмерного файла исчерпывает память или диск | Размер и число пикселей ограничены | Потоковый лимит и проверка изображения | Отправить файл свыше лимита и изображение со слишком большим числом пикселей | Остальные лимиты ресурсов стенда нужно проверить |
|
||||
| Загрузка чрезмерного файла исчерпывает память или диск | Размер и число пикселей ограничены | Потоковый лимит и проверка изображения | Отправить файл свыше лимита и изображение со слишком большим числом пикселей | Лимиты контейнеров проверяются `student-tests/runtime_hardening.py`; устойчивость под произвольной нагрузкой не доказана |
|
||||
| Клиент передаёт секрет в URL, который попадает в access-log | Секреты не сохраняются в наблюдаемости | Ingress пишет только статус, размер и служебные поля; API пишет шаблон маршрута | `student-tests/ingress_redaction.py`: маркеры в path/query/headers отсутствуют в реальных логах | Тест не доказывает отсутствие всех каналов утечки |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Check that request-controlled secrets are absent from actual access logs."""
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from uuid import uuid4
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
ctx = ssl.create_default_context(cafile=str(root / 'secrets/ca.crt'))
|
||||
base = os.environ.get('BASE_URL', 'https://localhost:8443').rstrip('/')
|
||||
marker = 'audit-private-' + uuid4().hex
|
||||
since = datetime.now(timezone.utc).isoformat()
|
||||
for path in ('/health/ready?token=' + marker, '/missing/' + marker):
|
||||
request = urllib.request.Request(base + path, headers={
|
||||
'Authorization': 'Bearer ' + marker, 'X-Request-Id': marker})
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
|
||||
response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 404
|
||||
error.read()
|
||||
for attempt in range(20):
|
||||
logs = subprocess.check_output(['docker', 'compose', 'logs', '--since', since,
|
||||
'load_balancer', 'api-a', 'api-b'], cwd=root, text=True)
|
||||
assert marker not in logs, 'request secret leaked into container logs'
|
||||
if 'ingress status=200' in logs and 'ingress status=404' in logs and 'http.request' in logs:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
else:
|
||||
raise AssertionError('missing positive evidence of access logging')
|
||||
print('PASS: ingress/API access records present; query, path and header markers absent')
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Inspect actual container privileges, mounts, published ports and limits."""
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
ids = subprocess.check_output(['docker','compose','ps','-q'], text=True).split()
|
||||
assert ids, 'stack not running'
|
||||
containers = json.loads(subprocess.check_output(['docker','inspect',*ids], text=True))
|
||||
seen = set()
|
||||
for c in containers:
|
||||
role=c['Config']['Labels']['com.docker.compose.service']
|
||||
seen.add(role)
|
||||
host=c['HostConfig']
|
||||
assert not host['Privileged'], role
|
||||
assert host['NetworkMode'] != 'host', role
|
||||
assert host['Memory'] > 0 and host['NanoCpus'] > 0, role
|
||||
for mount in c['Mounts']:
|
||||
assert 'docker.sock' not in mount['Source'] and 'docker.sock' not in mount['Destination'], role
|
||||
assert not mount['Source'].endswith(('/ca.key','/openbao-operator.json')), role
|
||||
for ports in (c['NetworkSettings'].get('Ports') or {}).values():
|
||||
for port in ports or []:
|
||||
assert role in {'load_balancer','openbao','grafana'}, role
|
||||
assert port['HostIp']=='127.0.0.1', role
|
||||
if role in {'api-a','api-b','worker'}:
|
||||
assert c['Config']['User'].split(':')[0] not in {'','0','root'}, role
|
||||
assert 'ALL' in host['CapDrop'], role
|
||||
assert not host['CapAdd'], role
|
||||
assert 'no-new-privileges:true' in host['SecurityOpt'], role
|
||||
assert {'api-a','api-b','worker','load_balancer'} <= seen
|
||||
print('PASS runtime: scoped ports, no privileged/host/socket/operator keys; resource limits; non-root app/worker')
|
||||
@@ -1,5 +1,10 @@
|
||||
"""Check allowed and denied S3 prefixes using the current service identity."""
|
||||
import json
|
||||
import http.client
|
||||
import urllib.parse
|
||||
from botocore.auth import S3SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
import os
|
||||
import ssl
|
||||
import urllib.request
|
||||
@@ -38,3 +43,24 @@ else:
|
||||
finally:
|
||||
client.close()
|
||||
print(f'PASS {role}: allowed staging write; forbidden prefix denied')
|
||||
|
||||
# Repeated Authorization fields must fail even for an otherwise allowed read.
|
||||
endpoint = urllib.parse.urlsplit(os.environ['S3_ENDPOINT'])
|
||||
path = '/' + bucket + '/' + allowed
|
||||
req = AWSRequest(method='GET', url=os.environ['S3_ENDPOINT'] + path)
|
||||
S3SigV4Auth(Credentials(values['S3_ACCESS_KEY_ID'], values['S3_SECRET_ACCESS_KEY']),
|
||||
's3', 'us-east-1').add_auth(req)
|
||||
conn = http.client.HTTPSConnection(endpoint.hostname, endpoint.port,
|
||||
context=ssl.create_default_context(cafile=os.environ['AWS_CA_BUNDLE']), timeout=10)
|
||||
try:
|
||||
conn.putrequest('GET', path)
|
||||
for key, value in req.headers.items():
|
||||
conn.putheader(key, value)
|
||||
conn.putheader('Authorization', req.headers['Authorization'])
|
||||
conn.endheaders()
|
||||
response = conn.getresponse()
|
||||
assert response.status == 403, 'duplicate Authorization not denied'
|
||||
response.read()
|
||||
finally:
|
||||
conn.close()
|
||||
print(f'PASS {role}: duplicate Authorization denied')
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Linux DAC regression; run as root in a disposable container with synthetic data."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
root.chmod(0o755)
|
||||
mounted = root / 'mounted'
|
||||
mounted.write_text('synthetic-secret')
|
||||
os.chown(mounted, 1000, 12345)
|
||||
mounted.chmod(0o640)
|
||||
host = root / 'operator'
|
||||
host.mkdir(mode=0o700)
|
||||
os.chown(host, 1000, 12345)
|
||||
protected = host / 'secret'
|
||||
protected.write_text('synthetic-secret')
|
||||
os.chown(protected, 1000, 12345)
|
||||
protected.chmod(0o640)
|
||||
def can_read(path, groups):
|
||||
def identity():
|
||||
os.setgroups(groups)
|
||||
os.setgid(65534)
|
||||
os.setuid(65534)
|
||||
return subprocess.run([sys.executable, '-c',
|
||||
'from pathlib import Path; import sys; Path(sys.argv[1]).read_bytes()', str(path)],
|
||||
preexec_fn=identity, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
|
||||
assert not can_read(mounted, [])
|
||||
assert can_read(mounted, [12345])
|
||||
assert not can_read(protected, [12345])
|
||||
mounted.chmod(0o600)
|
||||
assert not can_read(mounted, [12345])
|
||||
print('PASS Linux DAC: original failure reproduced; group access works; host directory protected')
|
||||
Reference in New Issue
Block a user