From b6c71fd96a2f032764268c313ee10302cc340470 Mon Sep 17 00:00:00 2001 From: da1zy3r Date: Fri, 27 Nov 2026 21:55:47 +0300 Subject: [PATCH] Grade 4 --- .env.example | 61 +- .github/pull_request_template.md | 43 +- .gitignore | 1 + Dockerfile | 2 +- README.md | 6 + REPORT.md | 113 ++- compose.yaml | 898 +++++++++++++----- contracts/trust-matrix.md | 60 +- evidence/README.md | 20 +- evidence/environment.json | 379 ++++++++ evidence/internal.json | 514 ++++++++++ evidence/internal.txt | 115 +++ evidence/lifecycle.json | 72 ++ evidence/scan-findings.csv | 398 ++++++++ evidence/scan-summary.json | 40 + evidence/security.txt | 1 + evidence/smoke.txt | 1 + evidence/telemetry.json | 9 + evidence/verification.txt | 17 + .../provisioning/datasources/sources.yaml | 90 +- infra/nginx.conf | 38 - infra/openbao/README.md | 10 +- infra/openbao/api.hcl | 2 + infra/openbao/cleanup.hcl | 2 + infra/openbao/config.hcl | 11 + infra/openbao/dispatcher.hcl | 2 + infra/openbao/worker.hcl | 2 + infra/otel/collector.yaml | 59 +- infra/otel/loki.yaml | 23 +- infra/otel/prometheus.yaml | 26 +- infra/otel/tempo.yaml | 6 +- infra/postgres/pg_hba.conf | 3 + infra/postgres/start.sh | 6 + infra/readiness.sh | 38 - infra/s3-api-policy.json | 1 + infra/s3-bootstrap.sh | 9 - infra/s3-cleanup-policy.json | 1 + infra/s3-policy.json | 17 - infra/s3-worker-policy.json | 1 + infra/tls/api1.cfg | 20 + infra/tls/api2.cfg | 20 + infra/tls/broker.cfg | 20 + infra/tls/grafana.cfg | 19 + infra/tls/lb.cfg | 34 + infra/tls/loki.cfg | 24 + infra/tls/otel-collector.cfg | 30 + infra/tls/prometheus.cfg | 24 + infra/tls/redis.cfg | 19 + infra/tls/s3.cfg | 19 + infra/tls/tempo.cfg | 29 + requirements-operator.txt | 3 + requirements.txt | 2 +- scripts/lab7.py | 328 +++++++ security/OPERATIONS.md | 86 ++ security/SCAN_TRIAGE.md | 38 + security/THREAT_MODEL.md | 39 +- src/auth.py | 40 +- src/image_processor.py | 2 +- src/jobs.py | 6 +- src/object_storage.py | 1 + src/secure_run.py | 82 ++ src/store.py | 9 +- src/telemetry.py | 13 +- src/worker.py | 2 +- student-tests/internal.py | 185 ++++ student-tests/lifecycle.py | 127 +++ student-tests/telemetry.py | 47 + 67 files changed, 3770 insertions(+), 595 deletions(-) create mode 100644 evidence/environment.json create mode 100644 evidence/internal.json create mode 100644 evidence/internal.txt create mode 100644 evidence/lifecycle.json create mode 100644 evidence/scan-findings.csv create mode 100644 evidence/scan-summary.json create mode 100644 evidence/security.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/telemetry.json create mode 100644 evidence/verification.txt delete mode 100644 infra/nginx.conf create mode 100644 infra/openbao/api.hcl create mode 100644 infra/openbao/cleanup.hcl create mode 100644 infra/openbao/config.hcl create mode 100644 infra/openbao/dispatcher.hcl create mode 100644 infra/openbao/worker.hcl create mode 100644 infra/postgres/pg_hba.conf create mode 100644 infra/postgres/start.sh delete mode 100644 infra/readiness.sh create mode 100644 infra/s3-api-policy.json delete mode 100644 infra/s3-bootstrap.sh create mode 100644 infra/s3-cleanup-policy.json delete mode 100644 infra/s3-policy.json create mode 100644 infra/s3-worker-policy.json create mode 100644 infra/tls/api1.cfg create mode 100644 infra/tls/api2.cfg create mode 100644 infra/tls/broker.cfg create mode 100644 infra/tls/grafana.cfg create mode 100644 infra/tls/lb.cfg create mode 100644 infra/tls/loki.cfg create mode 100644 infra/tls/otel-collector.cfg create mode 100644 infra/tls/prometheus.cfg create mode 100644 infra/tls/redis.cfg create mode 100644 infra/tls/s3.cfg create mode 100644 infra/tls/tempo.cfg create mode 100644 requirements-operator.txt create mode 100644 scripts/lab7.py create mode 100644 security/OPERATIONS.md create mode 100644 security/SCAN_TRIAGE.md create mode 100644 src/secure_run.py create mode 100644 student-tests/internal.py create mode 100644 student-tests/lifecycle.py create mode 100644 student-tests/telemetry.py diff --git a/.env.example b/.env.example index 4e32d2a..d62e419 100644 --- a/.env.example +++ b/.env.example @@ -1,57 +1,4 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 -APP_PORT=8080 -APP_ENV=lab -SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url -API_REPLICAS=2 -IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=https://s3:9000 -S3_REGION=us-east-1 -S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key -MAX_UPLOAD_BYTES=10485760 -MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 -JOB_MAX_ATTEMPTS=5 -JOB_TIMEOUT_SECONDS=60 -STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 -OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab -# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. -PUBLIC_BASE_URL=https://localhost:8443 -TLS_CA_FILE=/run/secrets/ca.crt -TLS_CERT_FILE=/run/secrets/service.crt -TLS_KEY_FILE=/run/secrets/service.key -BAO_ADDR=https://openbao:8200 -BAO_CACERT=/run/secrets/bao-ca.crt -# No root token here. Bootstrap operator -> short-lived service auth -> scoped token. -ARGON2_MEMORY_KIB=19456 -ARGON2_ITERATIONS=2 -ARGON2_PARALLELISM=1 - -# Settings for the application carried over from lab 6 (compose.yaml). -MAX_PENDING_ATTACHMENTS=64 -JOB_MEMORY_MB=768 -POSTGRES_DB=messenger -POSTGRES_USER=messenger -POSTGRES_PASSWORD=replace-with-local-password -CACHE_TTL_SECONDS=30 -MAX_REQUEST_BYTES=65536 -MAX_INFLIGHT=32 -MINIO_ROOT_USER=local-admin -MINIO_ROOT_PASSWORD=replace-with-admin-password -S3_ACCESS_KEY_ID=messenger-api -S3_SECRET_ACCESS_KEY=replace-with-api-password -OTEL_SDK_DISABLED=false -GRAFANA_ADMIN_PASSWORD=replace-with-grafana-password +# Runtime secrets are generated by: python scripts/lab7.py bootstrap +# Do not put service passwords here; applications read scoped KV paths from OpenBao. +# Non-secret runtime settings and resource limits are explicit in compose.yaml. +# Operator instructions: security/OPERATIONS.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8aef0ff..ab5959f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,33 @@ ## Лабораторная 7 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор / группа: Ромашко Владимир, БВТ2301. -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Целевая оценка (3/4/5): **4**. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +Трек 5, если заявлен: не заявляется. + +Что реализовано и что перенесено: из lab6 перенесено основное приложение — API мессенджера, миграции, sessions/cache, outbox и обработка вложений, telemetry. В lab7 добавлены HTTPS, обязательное mTLS LB → обе API и сервисов → broker/Collector, TLS остальных связей, отдельные service identities и ACL, persistent OpenBao с cert auth/scoped KV/TTL, Argon2id rehash и общий rate limit. Показаны ротация DB secret и LB leaf без rebuild, отзыв старых credentials, expiry/sealed recovery, container hardening и разбор CVE. Лишних функций уровня 5 нет. + +Команды запуска из чистого clone (Windows, Python 3.12+, Docker Desktop Linux containers/Compose v2): + +```powershell +python -m pip install -r requirements-operator.txt +python scripts/check_contract.py +python scripts/lab7.py bootstrap +python scripts/lab7.py verify +``` + +Bootstrap выполняет локальную генерацию secrets/CA, init/unseal, policies, миграции, build/up и ожидание readiness. API: https://localhost:8443, CA: secrets/ca.crt. .env не требуется. Остановка без удаления данных: docker compose stop. Leaf certificates действуют 24 часа; продление: python scripts/lab7.py renew-leaves. Подробности и намеренное удаление данных описаны в отчёте. + +Результаты проверок и ссылка на REPORT.md: [REPORT.md](../REPORT.md), [evidence](../evidence/README.md). Публичные smoke/security по HTTPS прошли; 114 внутренних и 16 lifecycle проверок завершены. Проверены остановка каждой API, полный restart с сохранностью sessions/messages/original/thumbnail, старые secret/cert, expiry/sealed OpenBao и telemetry. Структура/контракт и синтаксис проверены отдельно. На Windows без make выполнены его эквиваленты: check_contract.py и неизменённый tests/smoke.py внутри verify. + +Ограничения / известные ошибки: один Docker-host и одиночные stateful зависимости; ручные unseal и renewal; краткий перерыв при ротации допустим. Остаточные CVE разобраны в [SCAN_TRIAGE.md](../security/SCAN_TRIAGE.md); нулевой scan и production readiness не заявляются. Полные scan JSON сохранены локально вне Git, все текущие findings и сводка включены в evidence. Последний повторный запуск сохранял существующие volumes; data wipe не выполнялся. Linux bind-mount permissions отдельно не проверялись. + +Источники и использование ИИ: материалы задания OWASP/OpenBao/Docker, документация используемых библиотек и приложение lab6; ссылки и версии приведены в REPORT.md. Codex использован для реализации, проверки и документации; evidence получены реальным запуском стенда. + +- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены. +- [x] make check и make test выполнены через указанные выше эквиваленты без make; приложен реальный вывод. +- [x] Сценарии отказов/безопасности своего уровня воспроизведены. +- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.gitignore b/.gitignore index b5a7189..85a76b0 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,5 @@ coverage/ .idea/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. +evidence/raw/ # Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/Dockerfile b/Dockerfile index 564995c..b4f8238 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.12.8-slim-bookworm +FROM python:3.12.16-slim-bookworm ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ diff --git a/README.md b/README.md index b329f91..48515c8 100644 --- a/README.md +++ b/README.md @@ -110,3 +110,9 @@ Threat model, заполненная trust matrix, TLS/mTLS конфигурац - [OpenBao policies](https://openbao.org/docs/concepts/policies/) - [OpenBao production hardening](https://openbao.org/docs/internals/security/) - [Docker security](https://docs.docker.com/engine/security/) + +## Запуск реализации + +Инструкция и команды bootstrap/verify: [security/OPERATIONS.md](security/OPERATIONS.md). +Модель угроз: [security/THREAT_MODEL.md](security/THREAT_MODEL.md). +Фактические результаты проверки сохраняются в `evidence/`. diff --git a/REPORT.md b/REPORT.md index 9801db4..c61565a 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,120 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Ромашко Владимир, БВТ2301. +- Целевая оценка: **4**, все обязательные пункты уровней 3 и 4. Трек на 5 не заявляется. +- Commit/PR: изменения подготовлены к сдаче в индексе Git; коммит и PR пока не созданы. +- Использованные источники, библиотеки и помощь ИИ: основное приложение перенесено из lab6; FastAPI, SQLAlchemy/psycopg, Redis, boto3, argon2-cffi, Pillow и OpenTelemetry. Версии закреплены в requirements.txt и compose.yaml. Использованы материалы задания: [OWASP Password Storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), [OWASP File Upload](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html), [OpenBao cert auth](https://openbao.org/docs/auth/cert/), [OpenBao policies](https://openbao.org/docs/concepts/policies/), [Docker security](https://docs.docker.com/engine/security/). Codex помог с переносом, реализацией TLS/OpenBao, проверками, разбором scan и подготовкой отчёта; результаты ниже получены запуском команд на стенде. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Проверенное окружение: Windows, Python 3.14 у оператора, Docker Desktop (Engine 28.5.1) с Linux containers и Compose 2.40.0, 8 доступных Docker CPU и 8 328 019 968 байт RAM. Нужны доступ к Docker Engine, свободные локальные порты 8443/3443/8200 и интернет для первой загрузки образов/пакетов. Python оператора — 3.12 или новее. Проверки выполняются из корня репозитория. + +```powershell +python -m pip install -r requirements-operator.txt +python scripts/check_contract.py +python scripts/lab7.py bootstrap +python scripts/lab7.py verify +``` + +Bootstrap создаёт локальные ключи, CA и credentials в игнорируемом secrets/, подготавливает volumes, запускает зависимости, выполняет init/unseal OpenBao, применяет KV/DB/S3 policies, SQL migrations по schema_migrations, собирает app image и ждёт HTTPS readiness. Он сохраняет существующие данные при повторном запуске. .env создавать не требуется: [.env.example](.env.example) объясняет переход на OpenBao; несекретные настройки находятся в compose.yaml, DATABASE_URL/REDIS_URL/BROKER_URL и S3 credentials выдаются из KV соответствующей роли. + +Приложение: https://localhost:8443, Grafana: https://localhost:3443, OpenBao оператора: https://127.0.0.1:8200. CA для клиентов — secrets/ca.crt. Grafana: пользователь admin, пароль из локального secrets/grafana-admin/password. Пароли и ключи не нужно копировать в отчёт или Git. + +Проверить готовность отдельно: + +```powershell +python -c "import requests; r=requests.get('https://localhost:8443/health/ready',verify='secrets/ca.crt',timeout=5); r.raise_for_status(); print(r.status_code,r.text)" +``` + +Runtime приложения: python:3.12.16-slim-bookworm, FastAPI 0.115.6, Argon2 23.1.0, Pillow 13.0.0. Инфраструктура: HAProxy 3.0.12-alpine, PostgreSQL 17.4-bookworm, Redis 7.4.2-bookworm, OpenBao 2.4.4, Collector 0.136.0, Prometheus 3.6.0, Loki 3.5.7, Tempo 2.9.0, Grafana 12.2.0; MinIO закреплён digest в compose.yaml. Полный перечень и лимиты — [environment.json](evidence/environment.json). + +verify запускает неизменённые публичные smoke/security в audit-контейнере, затем student-tests/lifecycle.py и внутренние mTLS/ACL проверки. make на проверенном Windows-host не установлен: python scripts/check_contract.py эквивалентен make check, а smoke.py внутри verify — make test с CA и адресом https://lb:8443. При установленном make можно использовать make check PYTHON=python и make test PYTHON=python CA_FILE=secrets/ca.crt. + +Операторские действия и безопасная остановка: + +```powershell +python scripts/lab7.py rotate-secret +python scripts/lab7.py rotate-leaf +python scripts/lab7.py renew-leaves +python scripts/lab7.py restart +docker compose stop +# После остановки снова запустить, сохранить данные и дождаться readiness: +python scripts/lab7.py bootstrap +``` + +rotate-secret меняет рабочий пароль API в PostgreSQL и KV, разрывая старые DB-соединения. rotate-leaf заменяет сертификат LB и отзывает старый serial через CRL. renew-leaves нужен до истечения 24 часов; CA живёт 30 дней. После отдельного restart OpenBao оператор выполняет python scripts/lab7.py unseal. Полный restart нужно делать скриптом: сначала владельцы network namespace, затем их TLS sidecars. Ключ CA, root token и unseal share доступны только оператору; учебный init использует один share с threshold=1. Подробнее: [OPERATIONS.md](security/OPERATIONS.md). + +**Намеренное удаление всех учебных данных**, включая БД, S3, сессии, OpenBao и telemetry: docker compose down --volumes. Эта команда не нужна для обычной остановки и при проверке не выполнялась. Локальные secrets/ сохраняются; следующий bootstrap заново инициализирует пустой OpenBao и данные. Потеря secrets/operator-private при сохранённом sealed OpenBao не имеет автоматического восстановления. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +```text +Клиент --HTTPS--> LB --mTLS--> API1 / API2 + |--TLS + SCRAM--> PostgreSQL + |--TLS + ACL----> Redis (sessions/cache/rate) + |--TLS + SigV4--> S3 +API/dispatcher/worker --mTLS + ACL--> Redis Streams broker +API/worker/dispatcher --mTLS--> OTel Collector +Collector --mTLS--> Loki / Tempo; Prometheus --mTLS--> Collector metrics +Grafana --mTLS, read/query--> Prometheus / Loki / Tempo +API/worker/dispatcher/cleanup --TLS + cert auth--> OpenBao (свой KV) +``` + +Из lab6 перенесены бизнес-API, миграции, Redis sessions/cache, PostgreSQL outbox, асинхронная обработка вложений, dispatcher/worker/cleanup и telemetry. PostgreSQL — источник истины для пользователей, ACL, сообщений и состояния заданий. Redis хранит сессии/кеш и отдельно очередь; S3 — байты приватных вложений. Создание сообщения, idempotency record и изменение версии истории происходят в одной DB-транзакции. Создание metadata вложения и outbox job также атомарно в БД. S3/Redis не включены в SQL-транзакцию: используются устойчивые object keys, повторная доставка/lease и cleanup, а не обещание exactly-once. + +В lab7 добавлены TLS, проверка CA/hostname и ролей, ограниченные DB/S3/broker/KV права, OpenBao supervisor, rehash/rate limit и hardening. Password hash — Argon2id m=19456 KiB, t=2, p=1 со случайной солью. При успешном входе старый hash обновляется условным UPDATE; сессии имеют TTL 3600s, в Redis используется SHA-256 ключа bearer token. Username/global rate budget проверяется до hash: 8 попыток за 10s на имя и 32/s суммарно на обе реплики, плюс не более двух hash operations на API. + +Для продуктов без подходящего native TLS используется одинаковый HAProxy sidecar. Plaintext доступен только на 127.0.0.1 внутри общего network namespace; все межконтейнерные связи из [матрицы доверия](contracts/trust-matrix.md) защищены TLS. PostgreSQL использует native TLS verify-full. Проверка разрешённого CN роли дополняет доверие CA. API/worker/dispatcher имеют разные клиентские identities; серверные identities API1/API2 отдельные. Наружу опубликованы только три loopback TLS-порта. В OpenBao сервис читает только secret/data/своя-роль, получает token TTL/maxTTL 60s и отзывает его после чтения. Supervisor обновляет конфигурацию каждые 10s, останавливает child после исчерпания ограниченного кеша и восстанавливает его после unseal. + +API: 1 CPU/384 MiB на реплику. Worker: 2 CPU/2 GiB, два subprocess, до 768 MiB адресного пространства и 60s на задачу. Upload: до 10 MiB и 40 млн пикселей, только PNG/JPEG; JSON body до 64 KiB. read_only, no-new-privileges, cap_drop ALL и tmpfs заданы всем контейнерам. Stateful volumes остаются writable; PostgreSQL entrypoint получает только необходимые capabilities для подготовки файлов, затем работает как postgres. Операторский audit имеет доступ к тестовым identities/credentials для отрицательных проверок и не запускается как постоянный сервис. + +Решение ограничено Compose, статическими policy-файлами и одним операторским скриптом. Автоматическая PKI, CA rollover, Kubernetes и исследовательские сценарии уровня 5 не добавлялись. ## Доказательства критериев +Все сценарии в таблице выполняются python scripts/lab7.py verify после bootstrap, кроме offline check и Trivy. Результаты последнего полного прогона: публичные smoke/security, 114 внутренних проверок и 16 lifecycle проверок. Финальная запись lifecycle — Complete lifecycle suite. + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Offline структура и сохранность контракта | python scripts/check_contract.py; сравнение tests/ и OpenAPI с HEAD | Структура/refs/Python syntax PASS, публичные тесты и контракт не изменены | [verification.txt](evidence/verification.txt) | +| Публичный smoke; 3.1 HTTPS и прежний API | verify: tests/smoke.py и tests/security.py с CA | Пользователи, сессии, чаты, сообщения, ACL и обработка вложений работают; недоверенный CA отклонён | [smoke.txt](evidence/smoke.txt), [security.txt](evidence/security.txt) | +| 3.1 Argon2id и измеренные параметры | internal: Measured Argon2 budget, Password rehashed | m=19456, t=2, p=1; реальные 20 измерений verify hash | [internal.json](evidence/internal.json) | +| 3.2 Обязательное mTLS LB → обе API | internal: allowed/no cert/foreign/outsider/expired/revoked и plaintext ports | Разрешён LB; отсутствующий, чужой, просроченный и отозванный cert отклонены; :8080 закрыт снаружи namespace | [internal.json](evidence/internal.json) | +| 3.3 TLS остальных связей и least privilege | internal: TLS/hostname, DB/S3/broker/KV ACL; telemetry | TLS соединения успешны, неверный hostname/роль и запрещённые операции отвергнуты; plaintext backends недоступны | [internal.json](evidence/internal.json), [trust-matrix.md](contracts/trust-matrix.md) | +| 3.4 Persistent non-dev OpenBao и scoped auth | bootstrap; internal own/other KV и policy write; lifecycle full restart | Сервис получает только свой KV, чужой path/policy write дают 403; init/state переживают restart, требуется unseal | [internal.json](evidence/internal.json), [lifecycle.json](evidence/lifecycle.json), [config.hcl](infra/openbao/config.hcl) | +| 3.5 Non-root, порты, capabilities, limits, secrets | lifecycle hardening и поиск canaries; проверка Git/build context | Hardening настроен всем сервисам; app/worker non-root; секретов/ключей в сдаваемых файлах нет | [environment.json](evidence/environment.json), [verification.txt](evidence/verification.txt), [.dockerignore](.dockerignore) | +| 3.6 Rate/size/ACL/logout/expiry/CA | smoke; internal shared rate/expiry; lifecycle cross-chat/oversize | 8×401 и 4×429 на обеих API, Retry-After; logout/expiry → 401; чужое вложение → 404, большой body → 413 | [internal.json](evidence/internal.json), [lifecycle.json](evidence/lifecycle.json), [smoke.txt](evidence/smoke.txt) | +| 4.1 mTLS broker и Collector, разные роли | internal: CA-trusted outsider и allowed service identities | Чужая роль с тем же CA отклонена; worker не может XADD, dispatcher не может читать consumer group | [internal.json](evidence/internal.json) | +| 4.2 Hashes, rehash, ошибки и login DoS | internal: old hash login, SQL hash, session digest, общий rate и timing | Старый hash заменён после успешного login; token не хранится открытым в ключе; лимит общий, дорогие операции ограничены | [internal.json](evidence/internal.json), [lifecycle.json](evidence/lifecycle.json) | +| 4.3 Secret/leaf rotation, отзыв, expiry/sealed | lifecycle вызывает rotate-secret, rotate-leaf, seal/unseal | Старый DB password и LB serial отвергнуты; image ID не изменился; token истёк; sealed остановил API и consumers; unseal восстановил работу | [lifecycle.json](evidence/lifecycle.json), [OPERATIONS.md](security/OPERATIONS.md) | +| 4.4 read_only/tmpfs/caps и scan с применимостью | lifecycle hardening; Trivy 0.76.2 по команде в SCAN_TRIAGE | Все сервисы ограничены; Python/Pillow обновлены; оставшиеся CVE разобраны по используемым путям | [environment.json](evidence/environment.json), [scan-summary.json](evidence/scan-summary.json), [scan-findings.csv](evidence/scan-findings.csv), [SCAN_TRIAGE.md](security/SCAN_TRIAGE.md) | +| 4.5 Модель ≥6 угроз, worker budget, TLS/ACL/telemetry audit | 12 путей угроз; internal/lifecycle/telemetry; просмотр worker limits | Все заявленные связи проверены; живые metrics/logs/traces, canaries отсутствуют, Grafana ingest запрещён; worker CPU/RAM/timeout заданы | [THREAT_MODEL.md](security/THREAT_MODEL.md), [internal.json](evidence/internal.json), [telemetry.json](evidence/telemetry.json), [environment.json](evidence/environment.json) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Проверка выполнена 27.11.2026. Гипотеза: минимальные параметры Argon2id дают приемлемую задержку на этом стенде, а общий rate limit и два hash slots ограничивают расход ресурсов независимо от выбранной API-реплики. Методика: audit container 0.5 CPU/256 MiB, один синтетический hash/password, один прогрев, 20 последовательных verify (concurrency=1, без заданного arrival rate). В [internal.json](evidence/internal.json) сохранены все samples_ms, p50/median, p95, p99, длительность, CPU seconds и peak RSS процесса. При 20 наблюдениях p99 принят равным максимуму. Peak RSS относится ко всему процессу аудита, а не только Argon2. Последний результат: p50 **72.59 ms**, p95 **93.82 ms**, p99 **100.27 ms**; 20/20 успешных verify за **1.144s**, CPU **0.592s**, peak RSS **102728 KiB**. Это около 17.48 hash verify/s при последовательном исполнении в ограниченном audit-контейнере, не HTTP RPS. + +Отдельный HTTP эксперимент переключается между двумя API и делает 12 последовательных неверных входов одного пользователя: 8 ответов 401 и 4 ответа 429. Это ожидаемые отказы защиты, не ошибки теста. Успешные API RPS и p50/p95/p99 под конкурентной нагрузкой здесь не измерялись: пропускная способность не является результатом этой лабораторной. 32/s — верхний лимит попыток, а не гарантированный throughput. Один hash использует 19 MiB; два слота дают около 38 MiB рабочей памяти Argon2 на API, дополнительно к Python и приложению. + +Lifecycle создаёт трёх синтетических пользователей, два чата, сообщение-canary и один sample.png с thumbnail. Публичный smoke создаёт свой набор данных. Каждый verify добавляет записи; стенд не очищается перед прогоном, размеры всей БД не используются как база performance-выводов. После каждого отказа сравниваются исходное сообщение, действующая сессия и байты оригинала/thumbnail. Тесты последовательные; отказ каждой API проверяется один раз за полный прогон, не является статистическим SLA. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| docker compose stop api1, затем api2 по очереди | LB направляет запросы на оставшуюся API | Для каждой остановки получено 5 последовательных ответов surviving instance; сессия, сообщение и оба файла сохранены | **api1: 1.67s, 1 неуспешная попытка; api2: 1.25s, 0**; измерение включает контрольные чтения, потери проверенных данных нет | +| Полный restart владельцев namespace и TLS sidecars | Volumes и приложение переживают restart; OpenBao требует unseal | PostgreSQL, Redis, broker, S3, OpenBao и telemetry перезапущены; saved checks проходят после operator unseal | Readiness в пределах тестового ожидания 90s; потери проверенных данных нет | +| Ротация API DB secret | Старое подключение закрыто, новый пароль применяется | Старый пароль отвергнут новым PostgreSQL connection, API продолжает чтение | Проверка через 12s и ожидание readiness; точная latency ротации не измерялась | +| Ротация LB leaf | Новый cert работает, старый serial отвергнут обеими API | Negative tests старого cert проходят; image ID до/после одинаков | Короткий restart трёх TLS listeners; данные сохранены | +| Истечение OpenBao token | После TTL чтение KV запрещено | После lease_duration + 2s ответ 403 | TTL 60s; приложение получает новые tokens cert auth | +| Seal OpenBao, затем unseal | Нет бесконечной работы на старых secrets; восстановление после оператора | Через 70s API not ready, worker/dispatcher/cleanup child остановлены; после unseal saved checks проходят | Cache до 60s плюс poll/request/stop задержки; проверка восстановления в пределах 45s, без потери проверенных данных | +| Недоверенная/чужая TLS identity, запрещённые ACL операции | Отказ без plaintext fallback | Отрицательные проверки проходят во всей матрице | Данные не изменены | + +Scan приложения до/после обновления Python/Pillow: Debian CRITICAL 9 → 2, HIGH 145 → 100; Python CRITICAL 5 → 0, HIGH 40 → 3. Сохранены все оставшиеся находки в CSV и разбор применимости. Полные Trivy JSON сохранены локально в evidence/raw/ и исключены из Git как объёмный дубликат; сводка/CSV входят в сдачу. Scan не означает отсутствие уязвимостей. Проверка telemetry читает живые metrics/logs и до 20 trace bodies, ищет реальные service credentials и синтетические secrets/canary, не записывая их в evidence. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Переживается отказ одной API и управляемый restart стенда с сохранёнными volumes. PostgreSQL, LB, Redis, S3, OpenBao и Docker-host остаются единичными точками отказа; backup/HA не заявляются. +- TLS sidecars и локальные hops доверяют владельцу host/namespace. Операторские CA/root/unseal материалы хранятся локально; автоматического renewal/CA rollover нет. Перед повторной демонстрацией через сутки нужно renew-leaves. +- При недоступном Redis login закрывается с 503; sealed OpenBao после ограниченного кеша останавливает работу. Это выбранное fail-closed поведение с потерей доступности. +- Rate limit ограничивает общий ресурс, но атакующий может исчерпать бюджет законных пользователей. Полноценный нагрузочный login-DoS эксперимент и tuning сверх измерения hash не проводились. +- В app image остаются CVE; применимость/mitigation и принятые учебные риски перечислены в SCAN_TRIAGE. Образы сторонней инфраструктуры этим scan не охвачены. Перед внешним развёртыванием нужен отдельный patch review, особенно реально используемых библиотек; это следующий шаг, а не выполненная работа. +- Проверки показывают выбранные негативные сценарии и отсутствие заданных canaries в выборке telemetry, но не доказывают отсутствие любых утечек. Последний повторный bootstrap выполнен на существующих volumes; полное удаление данных ради повторной проверки чистого clone не выполнялось. Запуск и файловые права проверены на Windows Docker Desktop; Linux host требует отдельной проверки прав bind mounts. diff --git a/compose.yaml b/compose.yaml index f16ee99..2cf6ad0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,313 +1,685 @@ -x-api: &api - image: mtusi2026lab7-api:local - pull_policy: never - dns_opt: - - timeout:1 - - attempts:1 - environment: &app-env - APP_HOST: 0.0.0.0 - APP_PORT: 8080 - POSTGRES_HOST: postgres - POSTGRES_DB: ${POSTGRES_DB:-messenger} - POSTGRES_USER: ${POSTGRES_USER:-messenger} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} - REDIS_URL: redis://redis:6379/0 - SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} - CACHE_TTL_SECONDS: ${CACHE_TTL_SECONDS:-30} - MAX_REQUEST_BYTES: ${MAX_REQUEST_BYTES:-65536} - MAX_INFLIGHT: ${MAX_INFLIGHT:-32} - S3_ENDPOINT: http://s3:9000 - S3_REGION: us-east-1 - S3_BUCKET: messenger-attachments - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} - MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} - MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} - MAX_PENDING_ATTACHMENTS: ${MAX_PENDING_ATTACHMENTS:-64} - BROKER_URL: redis://broker:6379/0 - WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} - JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} - JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} - JOB_MEMORY_MB: ${JOB_MEMORY_MB:-768} - STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} - OTEL_SERVICE_NAME: messenger-api - OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 - OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} - networks: [backend] - cpus: 1.0 - mem_limit: 512m - stop_grace_period: 10s - +name: mtusi2026lab7 services: - broker: - image: redis:7.4.2-bookworm - command: [redis-server, --appendonly, 'yes', --appendfsync, always, --maxmemory, 128mb, --maxmemory-policy, noeviction] - volumes: - - broker_data:/data - networks: [backend] - healthcheck: - test: [CMD, redis-cli, ping] - interval: 2s - timeout: 2s - retries: 30 - cpus: 0.5 - mem_limit: 256m - - dispatcher: - <<: *api - environment: - <<: *app-env - OTEL_SERVICE_NAME: messenger-dispatcher - command: [python, -m, src.jobs, dispatch] - healthcheck: - disable: true - depends_on: - migrate: - condition: service_completed_successfully - broker: - condition: service_healthy + api1: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: &drop_all_capabilities + - ALL + security_opt: &no_new_privileges + - no-new-privileges:true + tmpfs: &runtime_tmpfs + - /tmp:rw,noexec,nosuid,size=64m restart: unless-stopped - mem_limit: 128m - - worker: - <<: *api + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src environment: - <<: *app-env - OTEL_SERVICE_NAME: messenger-worker - command: [python, -m, src.worker] + SERVICE_ROLE: api + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + volumes: + - ./secrets/api:/run/identity:ro init: true healthcheck: disable: true - depends_on: - migrate: - condition: service_completed_successfully - broker: - condition: service_healthy - s3-init: - condition: service_completed_successfully + pids_limit: 64 + stop_grace_period: 15s + api1-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/api1:/run/identity:ro + - ./infra/tls/api1.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:api1 + depends_on: + - api1 + api2: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src + environment: + SERVICE_ROLE: api + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + volumes: + - ./secrets/api:/run/identity:ro + init: true + healthcheck: + disable: true + pids_limit: 64 + stop_grace_period: 15s + api2-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/api2:/run/identity:ro + - ./infra/tls/api2.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:api2 + depends_on: + - api2 + worker: + image: mtusi2026lab7-api:local + networks: + - backend cpus: 2.0 mem_limit: 2g - pids_limit: 64 - - api: - <<: *api - build: . - deploy: - replicas: 2 - depends_on: - migrate: - condition: service_completed_successfully - redis: - condition: service_healthy - s3-init: - condition: service_completed_successfully - healthcheck: - test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=1).read()"] - interval: 2s - timeout: 2s - start_period: 5s - retries: 2 - - migrate: - <<: *api - environment: - <<: *app-env - OTEL_SDK_DISABLED: 'true' - command: [python, -m, src.database] - healthcheck: - disable: true - restart: 'no' - depends_on: - postgres: - condition: service_healthy - - s3: - # RELEASE.2025-09-07T16-13-09Z, pinned by immutable image digest. - image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e - command: [server, /data, --console-address, '127.0.0.1:9001'] - environment: - MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} - MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} - MINIO_BROWSER: 'off' - volumes: - - s3_data:/data - networks: [backend] - healthcheck: - test: [CMD, curl, -f, http://127.0.0.1:9000/minio/health/live] - interval: 2s - timeout: 2s - retries: 30 - cpus: 1.0 - mem_limit: 512m - - s3-init: - # The pinned server image also contains mc; no second image is needed. - image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e - entrypoint: [sh, /bootstrap.sh] - environment: - MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} - MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} - volumes: - - ./infra/s3-bootstrap.sh:/bootstrap.sh:ro - - ./infra/s3-policy.json:/policy.json:ro - depends_on: - s3: - condition: service_healthy - networks: [backend] - restart: 'no' - cpus: 0.25 - mem_limit: 128m - - cleanup: - <<: *api - environment: - <<: *app-env - OTEL_SDK_DISABLED: 'true' - command: [python, -m, src.cleanup] - healthcheck: - disable: true - depends_on: - migrate: - condition: service_completed_successfully - s3-init: - condition: service_completed_successfully + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - cpus: 0.25 - mem_limit: 128m - - nginx: - image: nginx:1.28.0-alpine - entrypoint: [sh, /etc/nginx/readiness.sh] - dns_opt: - - timeout:1 - - attempts:1 - ports: - - '127.0.0.1:${APP_PORT:-8080}:8080' + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src.worker + environment: + SERVICE_ROLE: worker + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-worker + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' volumes: - - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro - - ./infra/readiness.sh:/etc/nginx/readiness.sh:ro - networks: [edge, backend] - depends_on: - api: - condition: service_healthy + - ./secrets/worker:/run/identity:ro + init: true healthcheck: - test: [CMD-SHELL, 'wget -q -O /dev/null http://127.0.0.1:8080/health/ready'] - interval: 2s - timeout: 2s - retries: 3 + disable: true + pids_limit: 64 + stop_grace_period: 15s + dispatcher: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src.jobs + - dispatch + environment: + SERVICE_ROLE: dispatcher + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-dispatcher + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + volumes: + - ./secrets/dispatcher:/run/identity:ro + init: true + healthcheck: + disable: true + pids_limit: 64 + stop_grace_period: 15s + cleanup: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src.cleanup + environment: + SERVICE_ROLE: cleanup + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-cleanup + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + OTEL_SDK_DISABLED: 'true' + volumes: + - ./secrets/cleanup:/run/identity:ro + init: true + healthcheck: + disable: true + pids_limit: 64 + stop_grace_period: 15s + lb: + image: haproxy:3.0.12-alpine + networks: + - edge + - backend cpus: 0.5 - mem_limit: 128m - stop_grace_period: 10s - + mem_limit: 96m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + ports: + - 127.0.0.1:8443:8443 + volumes: + - ./secrets/lb:/run/identity:ro + - ./infra/tls/lb.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro postgres: image: postgres:17.4-bookworm - environment: - POSTGRES_DB: ${POSTGRES_DB:-messenger} - POSTGRES_USER: ${POSTGRES_USER:-messenger} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} - volumes: - - postgres_data:/var/lib/postgresql/data - networks: [backend] - healthcheck: - test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] - interval: 2s - timeout: 2s - retries: 30 + networks: + - backend cpus: 1.0 mem_limit: 512m - + read_only: true + cap_drop: + - ALL + security_opt: *no_new_privileges + tmpfs: + - /tmp:rw,nosuid,size=16m + - /var/run/postgresql:rw,nosuid,size=16m + restart: unless-stopped + cap_add: + - CHOWN + - DAC_OVERRIDE + - FOWNER + - SETGID + - SETUID + environment: + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/admin/postgres-password + volumes: + - type: volume + source: postgres_data + target: /var/lib/postgresql/data + volume: + nocopy: true + - ./secrets/postgres:/run/identity:ro + - ./secrets/postgres-admin:/run/admin:ro + - ./infra/postgres/pg_hba.conf:/etc/pg_hba.conf:ro + - ./infra/postgres/start.sh:/start.sh:ro + entrypoint: + - sh + - /start.sh redis: image: redis:7.4.2-bookworm - command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always", "--maxmemory", "128mb", "--maxmemory-policy", "noeviction"] - volumes: - - redis_data:/data - networks: [backend] - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 2s - timeout: 2s - retries: 30 + networks: + - backend cpus: 0.5 mem_limit: 256m - + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 999:999 + command: + - redis-server + - /run/config/redis.conf + volumes: + - type: volume + source: redis_data + target: /data + volume: + nocopy: true + - ./secrets/redis-config:/run/config:ro + redis-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/redis:/run/identity:ro + - ./infra/tls/redis.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:redis + depends_on: + - redis + broker: + image: redis:7.4.2-bookworm + networks: + - backend + cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 999:999 + command: + - redis-server + - /run/config/redis.conf + volumes: + - type: volume + source: broker_data + target: /data + volume: + nocopy: true + - ./secrets/broker-config:/run/config:ro + broker-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/broker:/run/identity:ro + - ./infra/tls/broker.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:broker + depends_on: + - broker + s3: + image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + networks: + - backend + cpus: 1.0 + mem_limit: 512m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 1000:1000 + entrypoint: + - sh + - -c + command: + - export MINIO_ROOT_USER=$$(cat /run/admin/user); export MINIO_ROOT_PASSWORD=$$(cat + /run/admin/password); exec minio server /data --address 127.0.0.1:9000 --console-address + 127.0.0.1:9001 + environment: + MINIO_BROWSER: 'off' + volumes: + - type: volume + source: s3_data + target: /data + volume: + nocopy: true + - ./secrets/s3-admin:/run/admin:ro + s3-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/s3:/run/identity:ro + - ./infra/tls/s3.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:s3 + depends_on: + - s3 + openbao: + image: openbao/openbao:2.4.4 + networks: + - edge + - backend + cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 100:1000 + entrypoint: + - bao + command: + - server + - -config=/etc/bao/config.hcl + volumes: + - type: volume + source: bao_data + target: /bao/data + volume: + nocopy: true + - ./secrets/openbao:/run/identity:ro + - ./infra/openbao/config.hcl:/etc/bao/config.hcl:ro + ports: + - 127.0.0.1:8200:8200 otel-collector: image: otel/opentelemetry-collector-contrib:0.136.0 - command: [--config=/etc/otel/collector.yaml] - volumes: - - ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro - networks: [backend] - mem_limit: 256m + networks: + - backend cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 1000:1000 + command: + - --config=/etc/otel/config.yaml + volumes: + - ./secrets/otel-collector:/run/identity:ro + - ./infra/otel/collector.yaml:/etc/otel/config.yaml:ro + otel-collector-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/otel-collector:/run/identity:ro + - ./infra/tls/otel-collector.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:otel-collector + depends_on: + - otel-collector prometheus: image: prom/prometheus:v3.6.0 - command: [--config.file=/etc/prometheus/prometheus.yaml, --storage.tsdb.retention.time=3d] - volumes: - - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro - - ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro - - prometheus_data:/prometheus - ports: ['127.0.0.1:9090:9090'] - networks: [edge, backend] - mem_limit: 512m + networks: + - backend cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 65534:65534 + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.retention.time=3d + - --web.listen-address=127.0.0.1:9090 + volumes: + - type: volume + source: prometheus_data + target: /prometheus + volume: + nocopy: true + - ./secrets/prometheus:/run/identity:ro + - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro + - ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro + prometheus-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/prometheus:/run/identity:ro + - ./infra/tls/prometheus.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:prometheus + depends_on: + - prometheus loki: image: grafana/loki:3.5.7 - command: [-config.file=/etc/loki/local.yaml] - volumes: - - ./infra/otel/loki.yaml:/etc/loki/local.yaml:ro - - loki_data:/loki - ports: ['127.0.0.1:3100:3100'] - networks: [edge, backend] - mem_limit: 384m + networks: + - backend cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 1000:1000 + command: + - -config.file=/etc/config.yaml + volumes: + - type: volume + source: loki_data + target: /loki + volume: + nocopy: true + - ./infra/otel/loki.yaml:/etc/config.yaml:ro + loki-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/loki:/run/identity:ro + - ./infra/tls/loki.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:loki + depends_on: + - loki tempo: image: grafana/tempo:2.9.0 - command: [-config.file=/etc/tempo.yaml] - volumes: - - ./infra/otel/tempo.yaml:/etc/tempo.yaml:ro - - tempo_data:/var/tempo - ports: ['127.0.0.1:3200:3200'] - networks: [edge, backend] - mem_limit: 384m + networks: + - backend cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 1000:1000 + command: + - -config.file=/etc/config.yaml + volumes: + - type: volume + source: tempo_data + target: /var/tempo + volume: + nocopy: true + - ./infra/otel/tempo.yaml:/etc/config.yaml:ro + tempo-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/tempo:/run/identity:ro + - ./infra/tls/tempo.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:tempo + depends_on: + - tempo grafana: image: grafana/grafana:12.2.0 + networks: + - edge + - backend + cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 472:472 environment: + GF_SERVER_HTTP_ADDR: 127.0.0.1 GF_SECURITY_ADMIN_USER: admin - GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env} + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/admin/password GF_USERS_ALLOW_SIGN_UP: 'false' + GF_AUTH_ANONYMOUS_ENABLED: 'false' GF_ANALYTICS_REPORTING_ENABLED: 'false' GF_ANALYTICS_CHECK_FOR_UPDATES: 'false' + GF_PLUGINS_PREINSTALL_DISABLED: 'true' volumes: - - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro - - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro - - grafana_data:/var/lib/grafana - ports: ['127.0.0.1:3000:3000'] - networks: [edge, backend] - mem_limit: 384m - cpus: 0.5 + - type: volume + source: grafana_data + target: /var/lib/grafana + volume: + nocopy: true + - ./secrets/grafana-admin:/run/admin:ro + - ./secrets/grafana-datasources:/etc/grafana/provisioning/datasources:ro + - ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + ports: + - 127.0.0.1:3443:3443 + grafana-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 65532:65532 + volumes: + - ./secrets/grafana:/run/identity:ro + - ./infra/tls/grafana.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:grafana + depends_on: + - grafana + audit: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: 'no' + profiles: + - tools + user: 1000:1000 + entrypoint: + - python + command: + - /audit/internal.py + volumes: + - ./student-tests:/audit:ro + - ./secrets:/audit-secrets:ro + - ./evidence:/evidence + - ./tests:/tests:ro + - ./contracts:/contracts:ro + - ./lab.json:/lab.json:ro + healthcheck: + disable: true networks: - edge: backend: internal: true + edge: {} volumes: - broker_data: - postgres_data: - redis_data: - s3_data: - prometheus_data: - loki_data: - tempo_data: - grafana_data: + postgres_data: {} + redis_data: {} + broker_data: {} + s3_data: {} + bao_data: {} + prometheus_data: {} + loki_data: {} + tempo_data: {} + grafana_data: {} diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..3ac869f 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,33 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +CA: secrets/ca.crt, 30 дней. Leaf: 24 часа; DNS SAN равен имени сервиса, публичные +сертификаты также содержат localhost и 127.0.0.1. HAProxy проверяет цепочку, срок, +CRL и разрешённый CN (роль, выпускаемую оператором); одного доверенного CA недостаточно. +Конфиги: infra/tls/*.cfg, compose.yaml, infra/openbao/*.hcl. -| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | +| Связь | Transport/identity | Права и lifecycle | Проверка | | --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | -| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | -| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | -| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | -| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | -| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | -| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | +| Клиент → LB | https://localhost:8443, CA+SAN, Bearer | Redis sessions 3600s, hash ключа, logout; общий login budget | smoke/security, internal expiry/rate | +| LB → API1/API2 | mTLS :8443, client CN=lb; verifyhost api1/api2 | CRL; leaf 24h | internal negatives на каждой реплике, lifecycle rotation | +| API/worker/dispatcher/cleanup → PostgreSQL | postgres:5432 native TLS verify-full, SCRAM, отдельные roles | API DML; worker/dispatcher SELECT/UPDATE attachments/jobs; cleanup attachments; без DDL/superuser | internal DB grants; lifecycle password rotation | +| API/worker/cleanup → S3 | https://s3:9443, CA/SAN + отдельные SigV4 users | API пишет staging, читает originals/variants; worker читает staging, пишет originals/variants; cleanup читает/удаляет; без admin | internal denied prefixes, smoke | +| API/dispatcher/worker → broker | broker:6380, mTLS CN api/dispatcher/worker + Redis ACL | API ping; dispatcher XADD/XGROUP CREATE; worker consume/ack/delete/XGROUP CREATE; ключ attachment-jobs | internal mTLS и запрещённые команды | +| API/worker/dispatcher → Collector | https://otel-collector:44318, mTLS CN api/worker/dispatcher | Только OTLP ingest; разные leaf keys | internal negatives и положительные пробы всех ролей | +| Collector → Loki/Tempo | https://loki:13100/otlp и https://tempo:14318, mTLS CN otel-collector | POST ingest paths | internal TLS; lifecycle живые сигналы | +| Prometheus → Collector | HTTPS :18889 и :18888 /metrics, mTLS CN prometheus | Metrics scrape | internal TLS и запрет plaintext обхода | +| Grafana → sources | https://prometheus:19090, loki:13100, tempo:13200, mTLS CN grafana | GET/HEAD + query POST Prometheus; TLS SAN; private key в generated secret provisioning | internal outsider; lifecycle запрещённый POST | +| API/worker/dispatcher/cleanup → OpenBao | https://openbao:8200, TLS + cert auth с CN/DNS SAN роли | Только secret/data/своя-роль; token TTL/maxTTL 60s, новый cert auth каждые 10s | internal own/other KV, lifecycle expiry/sealed | +| Оператор → OpenBao | https://127.0.0.1:8200, CA + operator token | Root только у оператора; init/unseal не в app | bootstrap, mounts | +| Оператор → Grafana | https://localhost:3443, CA/SAN + отдельный admin password | Host loopback; login обязателен | HTTPS/login | +| Оператор → S3 admin | Docker exec → локальный 127.0.0.1:9000 + admin auth | Не сетевой канал; Docker-host доверенный, console не опубликована | bootstrap, inspect ports | +| API → Redis | rediss://redis:6380, CA/SAN + ACL user api | session:*, history-v4:*, login:*; без CONFIG/FLUSHALL/ACL | internal TLS/session digest/expiry | +| Replication | N/A: один PostgreSQL, Redis и S3; два API без peer-to-peer | HA host/DB/LB не заявляется | Failover только API | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +Plaintext HAProxy→service находится только на 127.0.0.1 в одном network namespace +(network_mode: service:...), без публикации. Internal тест проверяет каждый такой порт +снаружи namespace. PostgreSQL не допускает hostnossl. LB readiness использует mTLS. +SQL bootstrap — Unix socket, S3 bootstrap — docker exec loopback, только оператор. +Внешний /health не предоставляет обхода бизнес-API. Кластерные каналы не используются. -## Обязательные отрицательные проверки - -1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». -2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. -3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. -4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. -5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. -6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. - -## Bootstrap и эксплуатация - -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. - -OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. - -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +Проверка: python scripts/lab7.py verify. Evidence содержит команды/результаты. +Ротация: rotate-leaf, rotate-secret. Эксплуатация: security/OPERATIONS.md. diff --git a/evidence/README.md b/evidence/README.md index 8df7001..e6836e0 100644 --- a/evidence/README.md +++ b/evidence/README.md @@ -1,5 +1,19 @@ -# Доказательства +# Evidence lab7 -Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. +Команда проверки: `python scripts/lab7.py verify` после `bootstrap`. -Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. +- `smoke.txt`, `security.txt`: неизменённые публичные tests через HTTPS. +- `internal.json`, `internal.txt`: фактические mTLS/ACL/rehash/expiry/rate/Argon2 проверки. +- `lifecycle.json`: отказ каждой API, сохранность после restart, secret/leaf rotation, + отзыв старых credentials, OpenBao expiry/sealed/recovery, telemetry и hardening. +- `telemetry.json`: живые сигналы, проверка утечек и доступ Grafana к TLS sources. +- `environment.json`: CPU/RAM стенда, image ID и лимиты каждого сервиса. +- `verification.txt`: offline contract check и синтаксис Python. +- `scan-summary.json`, `scan-findings.csv`: сводка до/после и все находки повторного scan. +- `raw/image-scan.json`, `raw/image-scan-updated.json`: полные локальные Trivy reports + до/после; сохранены у оператора, исключены из Git из-за объёма и дублирования CSV. +- `security/SCAN_TRIAGE.md` в корне проекта: применимость и остаточные риски. + +JSON тестов содержит только реально пройденные проверки. При неуспешном запуске +lifecycle сохраняет промежуточный результат; признак полного успеха — последняя запись +`Complete lifecycle suite`. Tokens/passwords/keys не включаются в результаты. diff --git a/evidence/environment.json b/evidence/environment.json new file mode 100644 index 0000000..807af98 --- /dev/null +++ b/evidence/environment.json @@ -0,0 +1,379 @@ +{ + "cpus": 8, + "memory_bytes": 8328019968, + "os": "Docker Desktop", + "architecture": "x86_64", + "app_image": "sha256:8ce282347ac73e6fd187038941b84d16df7cceede5a47e8310f381ae0275e3f6", + "services": { + "api1": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "api1-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "api2": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "api2-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "broker": { + "image": "redis:7.4.2-bookworm", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "999:999", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "broker-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "cleanup": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "dispatcher": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "grafana": { + "image": "grafana/grafana:12.2.0", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "472:472", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "grafana-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "lb": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.5, + "mem_limit": "100663296", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "loki": { + "image": "grafana/loki:3.5.7", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "loki-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "openbao": { + "image": "openbao/openbao:2.4.4", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "100:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "otel-collector": { + "image": "otel/opentelemetry-collector-contrib:0.136.0", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "otel-collector-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "postgres": { + "image": "postgres:17.4-bookworm", + "cpus": 1, + "mem_limit": "536870912", + "user": null, + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": [ + "CHOWN", + "DAC_OVERRIDE", + "FOWNER", + "SETGID", + "SETUID" + ], + "security_opt": [ + "no-new-privileges:true" + ] + }, + "prometheus": { + "image": "prom/prometheus:v3.6.0", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "65534:65534", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "prometheus-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "redis": { + "image": "redis:7.4.2-bookworm", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "999:999", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "redis-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "s3": { + "image": "minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e", + "cpus": 1, + "mem_limit": "536870912", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "s3-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "tempo": { + "image": "grafana/tempo:2.9.0", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "tempo-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "worker": { + "image": "mtusi2026lab7-api:local", + "cpus": 2, + "mem_limit": "2147483648", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + } + } +} \ No newline at end of file diff --git a/evidence/internal.json b/evidence/internal.json new file mode 100644 index 0000000..035f5da --- /dev/null +++ b/evidence/internal.json @@ -0,0 +1,514 @@ +{ + "checks": [ + { + "test": "Oversized HTTP/JSON trace context has bounded parsing cost", + "passed": true + }, + { + "test": "Valid trace context remains supported", + "passed": true + }, + { + "test": "api1 accepts allowed identity", + "passed": true + }, + { + "test": "api1 rejects None", + "passed": true + }, + { + "test": "api1 rejects foreign-lb", + "passed": true + }, + { + "test": "api1 rejects outsider", + "passed": true + }, + { + "test": "api1 rejects expired-lb", + "passed": true + }, + { + "test": "api1 rejects revoked LB serial", + "passed": true + }, + { + "test": "api2 accepts allowed identity", + "passed": true + }, + { + "test": "api2 rejects None", + "passed": true + }, + { + "test": "api2 rejects foreign-lb", + "passed": true + }, + { + "test": "api2 rejects outsider", + "passed": true + }, + { + "test": "api2 rejects expired-lb", + "passed": true + }, + { + "test": "api2 rejects revoked LB serial", + "passed": true + }, + { + "test": "broker accepts allowed identity", + "passed": true + }, + { + "test": "broker rejects None", + "passed": true + }, + { + "test": "broker rejects foreign-worker", + "passed": true + }, + { + "test": "broker rejects outsider", + "passed": true + }, + { + "test": "broker rejects expired-worker", + "passed": true + }, + { + "test": "otel-collector accepts allowed identity", + "passed": true + }, + { + "test": "otel-collector rejects None", + "passed": true + }, + { + "test": "otel-collector rejects foreign-api", + "passed": true + }, + { + "test": "otel-collector rejects outsider", + "passed": true + }, + { + "test": "otel-collector rejects expired-api", + "passed": true + }, + { + "test": "Collector accepts worker", + "passed": true + }, + { + "test": "Collector accepts dispatcher", + "passed": true + }, + { + "test": "lb server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "lb rejects wrong hostname", + "passed": true + }, + { + "test": "redis server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "redis rejects wrong hostname", + "passed": true + }, + { + "test": "s3 server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "s3 rejects wrong hostname", + "passed": true + }, + { + "test": "grafana server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "grafana rejects wrong hostname", + "passed": true + }, + { + "test": "openbao server TLS verified", + "passed": true, + "protocol": "TLSv1.2" + }, + { + "test": "openbao rejects wrong hostname", + "passed": true + }, + { + "test": "prometheus:19090 trusted identity", + "passed": true + }, + { + "test": "prometheus:19090 rejects outsider", + "passed": true + }, + { + "test": "loki:13100 trusted identity", + "passed": true + }, + { + "test": "loki:13100 rejects outsider", + "passed": true + }, + { + "test": "tempo:13200 trusted identity", + "passed": true + }, + { + "test": "tempo:13200 rejects outsider", + "passed": true + }, + { + "test": "otel-collector:18889 trusted identity", + "passed": true + }, + { + "test": "otel-collector:18889 rejects outsider", + "passed": true + }, + { + "test": "otel-collector:18888 trusted identity", + "passed": true + }, + { + "test": "otel-collector:18888 rejects outsider", + "passed": true + }, + { + "test": "tempo:14318 trusted identity", + "passed": true + }, + { + "test": "tempo:14318 rejects outsider", + "passed": true + }, + { + "test": "No plaintext bypass api1:8080", + "passed": true + }, + { + "test": "No plaintext bypass api2:8080", + "passed": true + }, + { + "test": "No plaintext bypass broker:6379", + "passed": true + }, + { + "test": "No plaintext bypass redis:6379", + "passed": true + }, + { + "test": "No plaintext bypass s3:9000", + "passed": true + }, + { + "test": "No plaintext bypass otel-collector:4318", + "passed": true + }, + { + "test": "No plaintext bypass otel-collector:8888", + "passed": true + }, + { + "test": "No plaintext bypass otel-collector:8889", + "passed": true + }, + { + "test": "No plaintext bypass prometheus:9090", + "passed": true + }, + { + "test": "No plaintext bypass loki:3100", + "passed": true + }, + { + "test": "No plaintext bypass loki:9095", + "passed": true + }, + { + "test": "No plaintext bypass tempo:3200", + "passed": true + }, + { + "test": "No plaintext bypass tempo:4318", + "passed": true + }, + { + "test": "No plaintext bypass tempo:9095", + "passed": true + }, + { + "test": "No plaintext bypass grafana:3000", + "passed": true + }, + { + "test": "PostgreSQL TLS api", + "passed": true + }, + { + "test": "DB no DDL api", + "passed": true + }, + { + "test": "OpenBao cert auth api", + "passed": true + }, + { + "test": "OpenBao short TTL api", + "passed": true + }, + { + "test": "OpenBao own KV api", + "passed": true + }, + { + "test": "OpenBao other KV denied api", + "passed": true + }, + { + "test": "OpenBao policy write denied api", + "passed": true + }, + { + "test": "PostgreSQL TLS worker", + "passed": true + }, + { + "test": "DB no DDL worker", + "passed": true + }, + { + "test": "DB password hashes denied worker", + "passed": true + }, + { + "test": "OpenBao cert auth worker", + "passed": true + }, + { + "test": "OpenBao short TTL worker", + "passed": true + }, + { + "test": "OpenBao own KV worker", + "passed": true + }, + { + "test": "OpenBao other KV denied worker", + "passed": true + }, + { + "test": "OpenBao policy write denied worker", + "passed": true + }, + { + "test": "PostgreSQL TLS dispatcher", + "passed": true + }, + { + "test": "DB no DDL dispatcher", + "passed": true + }, + { + "test": "DB password hashes denied dispatcher", + "passed": true + }, + { + "test": "OpenBao cert auth dispatcher", + "passed": true + }, + { + "test": "OpenBao short TTL dispatcher", + "passed": true + }, + { + "test": "OpenBao own KV dispatcher", + "passed": true + }, + { + "test": "OpenBao other KV denied dispatcher", + "passed": true + }, + { + "test": "OpenBao policy write denied dispatcher", + "passed": true + }, + { + "test": "PostgreSQL TLS cleanup", + "passed": true + }, + { + "test": "DB no DDL cleanup", + "passed": true + }, + { + "test": "DB password hashes denied cleanup", + "passed": true + }, + { + "test": "OpenBao cert auth cleanup", + "passed": true + }, + { + "test": "OpenBao short TTL cleanup", + "passed": true + }, + { + "test": "OpenBao own KV cleanup", + "passed": true + }, + { + "test": "OpenBao other KV denied cleanup", + "passed": true + }, + { + "test": "OpenBao policy write denied cleanup", + "passed": true + }, + { + "test": "OpenBao outsider denied", + "passed": true + }, + { + "test": "Broker authenticated api", + "passed": true + }, + { + "test": "Broker ACL denied api", + "passed": true + }, + { + "test": "Broker authenticated worker", + "passed": true + }, + { + "test": "Broker ACL denied worker", + "passed": true + }, + { + "test": "Broker authenticated dispatcher", + "passed": true + }, + { + "test": "Broker ACL denied dispatcher", + "passed": true + }, + { + "test": "S3 denied write prefix api", + "passed": true + }, + { + "test": "S3 denied write prefix worker", + "passed": true + }, + { + "test": "S3 denied write prefix cleanup", + "passed": true + }, + { + "test": "Old Argon2 login succeeds", + "passed": true + }, + { + "test": "Password rehashed", + "passed": true + }, + { + "test": "Session stores digest key, no credential", + "passed": true + }, + { + "test": "Expired session rejected", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit shared across replicas", + "passed": true, + "instances": 2, + "statuses": [ + 401, + 401, + 401, + 401, + 401, + 401, + 401, + 401, + 429, + 429, + 429, + 429 + ] + }, + { + "test": "Measured Argon2 budget", + "passed": true, + "memory_kib": 19456, + "time_cost": 2, + "parallelism": 1, + "median_ms": 72.59, + "p95_ms": 93.82, + "p99_ms": 100.27, + "samples_ms": [ + 39.139, + 70.695, + 22.805, + 79.572, + 26.963, + 82.623, + 100.27, + 85.038, + 25.732, + 77.702, + 26.895, + 77.439, + 26.264, + 74.49, + 24.908, + 75.369, + 93.821, + 31.636, + 79.445, + 23.472 + ], + "duration_seconds": 1.144, + "cpu_seconds": 0.592, + "process_peak_rss_kib": 102728, + "global_limit_per_second": 32, + "account_limit_per_10seconds": 8, + "hash_concurrency_per_api": 2 + } + ] +} \ No newline at end of file diff --git a/evidence/internal.txt b/evidence/internal.txt new file mode 100644 index 0000000..7f973bc --- /dev/null +++ b/evidence/internal.txt @@ -0,0 +1,115 @@ +PASS: Oversized HTTP/JSON trace context has bounded parsing cost +PASS: Valid trace context remains supported +PASS: api1 accepts allowed identity +PASS: api1 rejects None +PASS: api1 rejects foreign-lb +PASS: api1 rejects outsider +PASS: api1 rejects expired-lb +PASS: api1 rejects revoked LB serial +PASS: api2 accepts allowed identity +PASS: api2 rejects None +PASS: api2 rejects foreign-lb +PASS: api2 rejects outsider +PASS: api2 rejects expired-lb +PASS: api2 rejects revoked LB serial +PASS: broker accepts allowed identity +PASS: broker rejects None +PASS: broker rejects foreign-worker +PASS: broker rejects outsider +PASS: broker rejects expired-worker +PASS: otel-collector accepts allowed identity +PASS: otel-collector rejects None +PASS: otel-collector rejects foreign-api +PASS: otel-collector rejects outsider +PASS: otel-collector rejects expired-api +PASS: Collector accepts worker +PASS: Collector accepts dispatcher +PASS: lb server TLS verified +PASS: lb rejects wrong hostname +PASS: redis server TLS verified +PASS: redis rejects wrong hostname +PASS: s3 server TLS verified +PASS: s3 rejects wrong hostname +PASS: grafana server TLS verified +PASS: grafana rejects wrong hostname +PASS: openbao server TLS verified +PASS: openbao rejects wrong hostname +PASS: prometheus:19090 trusted identity +PASS: prometheus:19090 rejects outsider +PASS: loki:13100 trusted identity +PASS: loki:13100 rejects outsider +PASS: tempo:13200 trusted identity +PASS: tempo:13200 rejects outsider +PASS: otel-collector:18889 trusted identity +PASS: otel-collector:18889 rejects outsider +PASS: otel-collector:18888 trusted identity +PASS: otel-collector:18888 rejects outsider +PASS: tempo:14318 trusted identity +PASS: tempo:14318 rejects outsider +PASS: No plaintext bypass api1:8080 +PASS: No plaintext bypass api2:8080 +PASS: No plaintext bypass broker:6379 +PASS: No plaintext bypass redis:6379 +PASS: No plaintext bypass s3:9000 +PASS: No plaintext bypass otel-collector:4318 +PASS: No plaintext bypass otel-collector:8888 +PASS: No plaintext bypass otel-collector:8889 +PASS: No plaintext bypass prometheus:9090 +PASS: No plaintext bypass loki:3100 +PASS: No plaintext bypass loki:9095 +PASS: No plaintext bypass tempo:3200 +PASS: No plaintext bypass tempo:4318 +PASS: No plaintext bypass tempo:9095 +PASS: No plaintext bypass grafana:3000 +PASS: PostgreSQL TLS api +PASS: DB no DDL api +PASS: OpenBao cert auth api +PASS: OpenBao short TTL api +PASS: OpenBao own KV api +PASS: OpenBao other KV denied api +PASS: OpenBao policy write denied api +PASS: PostgreSQL TLS worker +PASS: DB no DDL worker +PASS: DB password hashes denied worker +PASS: OpenBao cert auth worker +PASS: OpenBao short TTL worker +PASS: OpenBao own KV worker +PASS: OpenBao other KV denied worker +PASS: OpenBao policy write denied worker +PASS: PostgreSQL TLS dispatcher +PASS: DB no DDL dispatcher +PASS: DB password hashes denied dispatcher +PASS: OpenBao cert auth dispatcher +PASS: OpenBao short TTL dispatcher +PASS: OpenBao own KV dispatcher +PASS: OpenBao other KV denied dispatcher +PASS: OpenBao policy write denied dispatcher +PASS: PostgreSQL TLS cleanup +PASS: DB no DDL cleanup +PASS: DB password hashes denied cleanup +PASS: OpenBao cert auth cleanup +PASS: OpenBao short TTL cleanup +PASS: OpenBao own KV cleanup +PASS: OpenBao other KV denied cleanup +PASS: OpenBao policy write denied cleanup +PASS: OpenBao outsider denied +PASS: Broker authenticated api +PASS: Broker ACL denied api +PASS: Broker authenticated worker +PASS: Broker ACL denied worker +PASS: Broker authenticated dispatcher +PASS: Broker ACL denied dispatcher +PASS: S3 denied write prefix api +PASS: S3 denied write prefix worker +PASS: S3 denied write prefix cleanup +PASS: Old Argon2 login succeeds +PASS: Password rehashed +PASS: Session stores digest key, no credential +PASS: Expired session rejected +PASS: Rate limit carries Retry-After +PASS: Rate limit carries Retry-After +PASS: Rate limit carries Retry-After +PASS: Rate limit carries Retry-After +PASS: Rate limit shared across replicas +PASS: Measured Argon2 budget +PASS: 114 internal checks diff --git a/evidence/lifecycle.json b/evidence/lifecycle.json new file mode 100644 index 0000000..33de649 --- /dev/null +++ b/evidence/lifecycle.json @@ -0,0 +1,72 @@ +[ + { + "test": "Cannot attach another chat file", + "passed": true + }, + { + "test": "Request size is bounded", + "passed": true + }, + { + "test": "Replica failover api1", + "passed": true, + "recovery_seconds": 1.67, + "failed_attempts": 1 + }, + { + "test": "Replica failover api2", + "passed": true, + "recovery_seconds": 1.25, + "failed_attempts": 0 + }, + { + "test": "Full restart preserves sessions, messages, original and processed attachment", + "passed": true + }, + { + "test": "Working DB secret rotated; old password rejected on new connection", + "passed": true + }, + { + "test": "Leaf rotated and old LB identity revoked on both replicas", + "passed": true + }, + { + "test": "Rotations do not rebuild image", + "passed": true, + "image": "sha256:8ce282347ac73e6fd187038941b84d16df7cceede5a47e8310f381ae0275e3f6" + }, + { + "test": "Expired OpenBao token denied", + "passed": true + }, + { + "test": "Sealed OpenBao stops API within bounded secret cache", + "passed": true, + "elapsed_seconds": 70.01 + }, + { + "test": "Sealed OpenBao stops background consumers too", + "passed": true + }, + { + "test": "Unseal recovers without baked-in fallback secret", + "passed": true + }, + { + "test": "Container logs do not expose credentials or private message", + "passed": true + }, + { + "test": "Live metrics/logs/traces have no credential leaks; datasource writes denied", + "passed": true + }, + { + "test": "All services have read_only, no-new-privileges, cap_drop and limits", + "passed": true + }, + { + "test": "Complete lifecycle suite", + "passed": true + } +] \ No newline at end of file diff --git a/evidence/scan-findings.csv b/evidence/scan-findings.csv new file mode 100644 index 0000000..bc1effb --- /dev/null +++ b/evidence/scan-findings.csv @@ -0,0 +1,398 @@ +type,package,installed,CVE,severity,fixed,status,title,url +debian,apt,2.6.2,CVE-2011-3374,LOW,,affected,"It was found that apt-key in apt, all versions, do not correctly valid ...",https://avd.aquasec.com/nvd/cve-2011-3374 +debian,bash,5.2.15-2+b13,TEMP-0841856-B18BAF,LOW,,affected,[Privilege escalation possible to other user than root],https://security-tracker.debian.org/tracker/TEMP-0841856-B18BAF +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,coreutils,9.1-1,CVE-2016-2781,LOW,,will_not_fix,coreutils: Non-privileged session can escape to the parent session in chroot,https://avd.aquasec.com/nvd/cve-2016-2781 +debian,coreutils,9.1-1,CVE-2017-18018,LOW,,affected,coreutils: race condition vulnerability in chown and chgrp,https://avd.aquasec.com/nvd/cve-2017-18018 +debian,coreutils,9.1-1,CVE-2025-5278,LOW,,affected,coreutils: Heap Buffer Under-Read in GNU Coreutils sort via Key Specification,https://avd.aquasec.com/nvd/cve-2025-5278 +debian,coreutils,9.1-1,CVE-2026-56391,LOW,,affected,coreutils: GNU coreutils uniq: Denial of Service and information disclosure via out-of-bounds read with multibyte input,https://avd.aquasec.com/nvd/cve-2026-56391 +debian,coreutils,9.1-1,CVE-2026-56392,LOW,,affected,coreutils: GNU coreutils unexpand: Denial of Service via crafted tab stop values,https://avd.aquasec.com/nvd/cve-2026-56392 +debian,dash,0.5.12-2,CVE-2026-102473,LOW,,affected,dash: dash: Super-polynomial backtracking in pmatch when libc fnmatch is disabled,https://avd.aquasec.com/nvd/cve-2026-102473 +debian,dash,0.5.12-2,CVE-2026-102474,LOW,,affected,dash: dash: Heap out-of-bounds write in conv_escape via undersized Unicode escape reservation,https://avd.aquasec.com/nvd/cve-2026-102474 +debian,diffutils,1:3.8-4,CVE-2026-53910,LOW,,affected,diffutils: heap‑based buffer overflow due to multiple signed integer overflows in line‑mapping calculations,https://avd.aquasec.com/nvd/cve-2026-53910 +debian,dpkg,1.21.23,CVE-2026-91094,UNKNOWN,,fix_deferred,A directory traversal bug was discovered when unpacking 3.0 (quilt) so ...,https://avd.aquasec.com/nvd/cve-2026-91094 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-102010,MEDIUM,,fix_deferred,gcc-toolset-15-gcc: gcc: gcc-toolset-16: gcc: Denial of Service via use-after-free in binary heap erase_if,https://avd.aquasec.com/nvd/cve-2026-102010 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-114690,MEDIUM,,affected,gcc: Confirmed out-of-bounds read/write in libstdc++ parallel `std,https://avd.aquasec.com/nvd/cve-2026-114690 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-114691,MEDIUM,,affected,gcc: Integer wrap in `std,https://avd.aquasec.com/nvd/cve-2026-114691 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-125709,MEDIUM,,fix_deferred,libstdc++: overflow leaves streambuf in inconsistent state on I/O error.,https://avd.aquasec.com/nvd/cve-2026-125709 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-95619,MEDIUM,,fix_deferred,gcc: libstdc++ integer overflow in `new` operator,https://avd.aquasec.com/nvd/cve-2026-95619 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2022-27943,LOW,,affected,binutils: libiberty/rust-demangle.c in GNU GCC 11.2 allows stack exhaustion in demangle_const,https://avd.aquasec.com/nvd/cve-2022-27943 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-115456,LOW,,fix_deferred,gcc: Out-of-bounds read in std::from_chars,https://avd.aquasec.com/nvd/cve-2026-115456 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2025-30258,MEDIUM,,affected,gnupg: verification DoS due to a malicious subkey in the keyring,https://avd.aquasec.com/nvd/cve-2025-30258 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2025-68972,MEDIUM,,affected,gnupg: GnuPG: Signature bypass via form feed character in signed messages,https://avd.aquasec.com/nvd/cve-2025-68972 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2022-3219,LOW,,affected,gnupg: denial of service issue (resource consumption) using compressed packets,https://avd.aquasec.com/nvd/cve-2022-3219 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2026-105712,LOW,,fix_deferred,gnupg2: gnupg: Arbitrary file overwrite via symlink traversal in gpgtar,https://avd.aquasec.com/nvd/cve-2026-105712 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2026-57062,LOW,,fix_deferred,GnuPG: Incorrect cryptographic message parsing,https://avd.aquasec.com/nvd/cve-2026-57062 +debian,gzip,1.12-1,CVE-2026-41992,HIGH,,fix_deferred,gzip: gzip: Information disclosure via global buffer overflow in LZH decompression,https://avd.aquasec.com/nvd/cve-2026-41992 +debian,gzip,1.12-1,CVE-2026-41991,MEDIUM,,fix_deferred,gzip: gzip: Arbitrary file overwrite via insecure temporary file handling in gzexe utility,https://avd.aquasec.com/nvd/cve-2026-41991 +debian,libacl1,2.3.1-3,CVE-2026-54369,HIGH,,fix_deferred,acl: Symlink traversal privilege escalation via libacl functions,https://avd.aquasec.com/nvd/cve-2026-54369 +debian,libacl1,2.3.1-3,CVE-2026-54370,MEDIUM,,fix_deferred,acl: TOCTOU Symlink Traversal via getfacl/setfacl,https://avd.aquasec.com/nvd/cve-2026-54370 +debian,libapt-pkg6.0,2.6.2,CVE-2011-3374,LOW,,affected,"It was found that apt-key in apt, all versions, do not correctly valid ...",https://avd.aquasec.com/nvd/cve-2011-3374 +debian,libattr1,1:2.5.1-4,CVE-2026-54371,MEDIUM,,fix_deferred,attr: attr: Symlink Traversal Privilege Escalation via getfattr and setfattr,https://avd.aquasec.com/nvd/cve-2026-54371 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libbz2-1.0,1.0.8-5+b1,CVE-2026-42250,MEDIUM,,affected,bzip2: bzip2: Denial of Service in bzip2recover via a specially crafted file,https://avd.aquasec.com/nvd/cve-2026-42250 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-115819,MEDIUM,,affected,glibc: glibc: Memory corruption via out-of-bounds write in wide scanf functions,https://avd.aquasec.com/nvd/cve-2026-115819 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-121757,MEDIUM,,affected,glibc: glibc: Denial of Service via out-of-bounds read in CP949 character conversion,https://avd.aquasec.com/nvd/cve-2026-121757 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-18374,MEDIUM,,fix_deferred,glibc: glibc: Heap buffer overflow via attacker-controlled fopen mode string,https://avd.aquasec.com/nvd/cve-2026-18374 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-19499,MEDIUM,,fix_deferred,glibc: Buffer Overflow in strfmon right-justification padding,https://avd.aquasec.com/nvd/cve-2026-19499 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-19542,MEDIUM,,fix_deferred,glibc: Fix out-of-bounds array write in tdelete,https://avd.aquasec.com/nvd/cve-2026-19542 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-5435,MEDIUM,,affected,glibc: glibc: Out-of-bounds write via TSIG record processing,https://avd.aquasec.com/nvd/cve-2026-5435 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-5450,MEDIUM,,affected,glibc: glibc: Heap Buffer Overflow in `scanf` with `%mc` format specifier and large width,https://avd.aquasec.com/nvd/cve-2026-5450 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-5928,MEDIUM,,affected,glibc: glibc: Information disclosure or denial of service via ungetwc function with specific wide character encodings,https://avd.aquasec.com/nvd/cve-2026-5928 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-6238,MEDIUM,,affected,glibc: glibc: Application crash or uninitialized memory read via crafted DNS response,https://avd.aquasec.com/nvd/cve-2026-6238 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-6368,MEDIUM,,fix_deferred,glibc: glibc: Process abort due to invalid memory in wordexp,https://avd.aquasec.com/nvd/cve-2026-6368 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-6791,MEDIUM,,fix_deferred,glibc: Glibc: Denial of Service via stack exhaustion during tilde expansion,https://avd.aquasec.com/nvd/cve-2026-6791 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-77117,MEDIUM,,fix_deferred,glibc: Non-progress DoS in SHIFT_JISX0213 ->,https://avd.aquasec.com/nvd/cve-2026-77117 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-80489,MEDIUM,,fix_deferred,glibc: Non-progress DoS in EUC_JISX0213 -> UCS-4 conversion state,https://avd.aquasec.com/nvd/cve-2026-80489 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-84243,MEDIUM,,affected,glibc: glibc: Arbitrary code execution via directory traversal in LANGUAGE environment variable,https://avd.aquasec.com/nvd/cve-2026-84243 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-8674,MEDIUM,,fix_deferred,glibc: glibc DNS stub resolver: Denial of Service via long search domain in configuration,https://avd.aquasec.com/nvd/cve-2026-8674 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-86805,MEDIUM,,affected,glibc: glibc: Privilege escalation and arbitrary code execution via TOCTOU race condition in dynamic loader,https://avd.aquasec.com/nvd/cve-2026-86805 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-89092,MEDIUM,,fix_deferred,glibc: nscd stack overflow leads to degraded DNS resolution,https://avd.aquasec.com/nvd/cve-2026-89092 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-95818,MEDIUM,,affected,glibc: glibc: Local attacker can cause denial of service and information disclosure via stack-based buffer overflow.,https://avd.aquasec.com/nvd/cve-2026-95818 +debian,libc-bin,2.36-9+deb12u14,CVE-2010-4756,LOW,,affected,glibc: glob implementation can cause excessive CPU and memory consumption due to crafted glob expressions,https://avd.aquasec.com/nvd/cve-2010-4756 +debian,libc-bin,2.36-9+deb12u14,CVE-2018-20796,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2018-20796 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010022,LOW,,affected,glibc: stack guard protection bypass,https://avd.aquasec.com/nvd/cve-2019-1010022 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010023,LOW,,affected,glibc: running ldd on malicious ELF leads to code execution because of wrong size computation,https://avd.aquasec.com/nvd/cve-2019-1010023 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010024,LOW,,affected,glibc: ASLR bypass using cache of thread stack and heap,https://avd.aquasec.com/nvd/cve-2019-1010024 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010025,LOW,,affected,glibc: information disclosure of heap addresses of pthread_created thread,https://avd.aquasec.com/nvd/cve-2019-1010025 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-9192,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2019-9192 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-100290,LOW,,affected,glibc: glibc: Denial of Service via memory allocation failure during regular expression processing,https://avd.aquasec.com/nvd/cve-2026-100290 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-126765,LOW,,affected,glibc: glibc: Denial of Service via double free in glob functions,https://avd.aquasec.com/nvd/cve-2026-126765 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-97399,LOW,,affected,glibc: glibc: Denial of Service via out-of-bounds read in strncasecmp,https://avd.aquasec.com/nvd/cve-2026-97399 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-121758,UNKNOWN,,affected,Converting crafted ISO-2022-CN-EXT input in the GNU C Library version ...,https://avd.aquasec.com/nvd/cve-2026-121758 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-124024,UNKNOWN,,affected,Converting crafted input from UCS-4 to IBM1390 or IBM1399 character en ...,https://avd.aquasec.com/nvd/cve-2026-124024 +debian,libc6,2.36-9+deb12u14,CVE-2026-115819,MEDIUM,,affected,glibc: glibc: Memory corruption via out-of-bounds write in wide scanf functions,https://avd.aquasec.com/nvd/cve-2026-115819 +debian,libc6,2.36-9+deb12u14,CVE-2026-121757,MEDIUM,,affected,glibc: glibc: Denial of Service via out-of-bounds read in CP949 character conversion,https://avd.aquasec.com/nvd/cve-2026-121757 +debian,libc6,2.36-9+deb12u14,CVE-2026-18374,MEDIUM,,fix_deferred,glibc: glibc: Heap buffer overflow via attacker-controlled fopen mode string,https://avd.aquasec.com/nvd/cve-2026-18374 +debian,libc6,2.36-9+deb12u14,CVE-2026-19499,MEDIUM,,fix_deferred,glibc: Buffer Overflow in strfmon right-justification padding,https://avd.aquasec.com/nvd/cve-2026-19499 +debian,libc6,2.36-9+deb12u14,CVE-2026-19542,MEDIUM,,fix_deferred,glibc: Fix out-of-bounds array write in tdelete,https://avd.aquasec.com/nvd/cve-2026-19542 +debian,libc6,2.36-9+deb12u14,CVE-2026-5435,MEDIUM,,affected,glibc: glibc: Out-of-bounds write via TSIG record processing,https://avd.aquasec.com/nvd/cve-2026-5435 +debian,libc6,2.36-9+deb12u14,CVE-2026-5450,MEDIUM,,affected,glibc: glibc: Heap Buffer Overflow in `scanf` with `%mc` format specifier and large width,https://avd.aquasec.com/nvd/cve-2026-5450 +debian,libc6,2.36-9+deb12u14,CVE-2026-5928,MEDIUM,,affected,glibc: glibc: Information disclosure or denial of service via ungetwc function with specific wide character encodings,https://avd.aquasec.com/nvd/cve-2026-5928 +debian,libc6,2.36-9+deb12u14,CVE-2026-6238,MEDIUM,,affected,glibc: glibc: Application crash or uninitialized memory read via crafted DNS response,https://avd.aquasec.com/nvd/cve-2026-6238 +debian,libc6,2.36-9+deb12u14,CVE-2026-6368,MEDIUM,,fix_deferred,glibc: glibc: Process abort due to invalid memory in wordexp,https://avd.aquasec.com/nvd/cve-2026-6368 +debian,libc6,2.36-9+deb12u14,CVE-2026-6791,MEDIUM,,fix_deferred,glibc: Glibc: Denial of Service via stack exhaustion during tilde expansion,https://avd.aquasec.com/nvd/cve-2026-6791 +debian,libc6,2.36-9+deb12u14,CVE-2026-77117,MEDIUM,,fix_deferred,glibc: Non-progress DoS in SHIFT_JISX0213 ->,https://avd.aquasec.com/nvd/cve-2026-77117 +debian,libc6,2.36-9+deb12u14,CVE-2026-80489,MEDIUM,,fix_deferred,glibc: Non-progress DoS in EUC_JISX0213 -> UCS-4 conversion state,https://avd.aquasec.com/nvd/cve-2026-80489 +debian,libc6,2.36-9+deb12u14,CVE-2026-84243,MEDIUM,,affected,glibc: glibc: Arbitrary code execution via directory traversal in LANGUAGE environment variable,https://avd.aquasec.com/nvd/cve-2026-84243 +debian,libc6,2.36-9+deb12u14,CVE-2026-8674,MEDIUM,,fix_deferred,glibc: glibc DNS stub resolver: Denial of Service via long search domain in configuration,https://avd.aquasec.com/nvd/cve-2026-8674 +debian,libc6,2.36-9+deb12u14,CVE-2026-86805,MEDIUM,,affected,glibc: glibc: Privilege escalation and arbitrary code execution via TOCTOU race condition in dynamic loader,https://avd.aquasec.com/nvd/cve-2026-86805 +debian,libc6,2.36-9+deb12u14,CVE-2026-89092,MEDIUM,,fix_deferred,glibc: nscd stack overflow leads to degraded DNS resolution,https://avd.aquasec.com/nvd/cve-2026-89092 +debian,libc6,2.36-9+deb12u14,CVE-2026-95818,MEDIUM,,affected,glibc: glibc: Local attacker can cause denial of service and information disclosure via stack-based buffer overflow.,https://avd.aquasec.com/nvd/cve-2026-95818 +debian,libc6,2.36-9+deb12u14,CVE-2010-4756,LOW,,affected,glibc: glob implementation can cause excessive CPU and memory consumption due to crafted glob expressions,https://avd.aquasec.com/nvd/cve-2010-4756 +debian,libc6,2.36-9+deb12u14,CVE-2018-20796,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2018-20796 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010022,LOW,,affected,glibc: stack guard protection bypass,https://avd.aquasec.com/nvd/cve-2019-1010022 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010023,LOW,,affected,glibc: running ldd on malicious ELF leads to code execution because of wrong size computation,https://avd.aquasec.com/nvd/cve-2019-1010023 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010024,LOW,,affected,glibc: ASLR bypass using cache of thread stack and heap,https://avd.aquasec.com/nvd/cve-2019-1010024 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010025,LOW,,affected,glibc: information disclosure of heap addresses of pthread_created thread,https://avd.aquasec.com/nvd/cve-2019-1010025 +debian,libc6,2.36-9+deb12u14,CVE-2019-9192,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2019-9192 +debian,libc6,2.36-9+deb12u14,CVE-2026-100290,LOW,,affected,glibc: glibc: Denial of Service via memory allocation failure during regular expression processing,https://avd.aquasec.com/nvd/cve-2026-100290 +debian,libc6,2.36-9+deb12u14,CVE-2026-126765,LOW,,affected,glibc: glibc: Denial of Service via double free in glob functions,https://avd.aquasec.com/nvd/cve-2026-126765 +debian,libc6,2.36-9+deb12u14,CVE-2026-97399,LOW,,affected,glibc: glibc: Denial of Service via out-of-bounds read in strncasecmp,https://avd.aquasec.com/nvd/cve-2026-97399 +debian,libc6,2.36-9+deb12u14,CVE-2026-121758,UNKNOWN,,affected,Converting crafted ISO-2022-CN-EXT input in the GNU C Library version ...,https://avd.aquasec.com/nvd/cve-2026-121758 +debian,libc6,2.36-9+deb12u14,CVE-2026-124024,UNKNOWN,,affected,Converting crafted input from UCS-4 to IBM1390 or IBM1399 character en ...,https://avd.aquasec.com/nvd/cve-2026-124024 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-102010,MEDIUM,,fix_deferred,gcc-toolset-15-gcc: gcc: gcc-toolset-16: gcc: Denial of Service via use-after-free in binary heap erase_if,https://avd.aquasec.com/nvd/cve-2026-102010 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-114690,MEDIUM,,affected,gcc: Confirmed out-of-bounds read/write in libstdc++ parallel `std,https://avd.aquasec.com/nvd/cve-2026-114690 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-114691,MEDIUM,,affected,gcc: Integer wrap in `std,https://avd.aquasec.com/nvd/cve-2026-114691 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-125709,MEDIUM,,fix_deferred,libstdc++: overflow leaves streambuf in inconsistent state on I/O error.,https://avd.aquasec.com/nvd/cve-2026-125709 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-95619,MEDIUM,,fix_deferred,gcc: libstdc++ integer overflow in `new` operator,https://avd.aquasec.com/nvd/cve-2026-95619 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2022-27943,LOW,,affected,binutils: libiberty/rust-demangle.c in GNU GCC 11.2 allows stack exhaustion in demangle_const,https://avd.aquasec.com/nvd/cve-2022-27943 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-115456,LOW,,fix_deferred,gcc: Out-of-bounds read in std::from_chars,https://avd.aquasec.com/nvd/cve-2026-115456 +debian,libgcrypt20,1.10.1-3+deb12u1,CVE-2018-6829,LOW,,affected,libgcrypt: ElGamal implementation doesn't have semantic security due to incorrectly encoded plaintexts possibly allowing to obtain sensitive information,https://avd.aquasec.com/nvd/cve-2018-6829 +debian,libgcrypt20,1.10.1-3+deb12u1,CVE-2024-2236,LOW,,affected,libgcrypt: vulnerable to Marvin Attack,https://avd.aquasec.com/nvd/cve-2024-2236 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2011-3389,LOW,,affected,HTTPS: block-wise chosen-plaintext attack against SSL/TLS (BEAST),https://avd.aquasec.com/nvd/cve-2011-3389 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-67693,LOW,,affected,gnutls: gnutls: Information disclosure via contradictory Key Usage and Extended Key Usage extensions,https://avd.aquasec.com/nvd/cve-2026-67693 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-88647,LOW,,affected,gnutls: gnutls: Information disclosure via hostname verification bypass,https://avd.aquasec.com/nvd/cve-2026-88647 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-88648,LOW,,affected,gnutls: gnutls: Cross-domain certificate restriction bypass via incomplete X.509 validation,https://avd.aquasec.com/nvd/cve-2026-88648 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-95184,LOW,,affected,gnutls: gnutls: legitimate user certificates incorrectly rejected causing denial of service,https://avd.aquasec.com/nvd/cve-2026-95184 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-95210,LOW,,affected,gnutls: gnutls: certificates with invalid extensions incorrectly accepted,https://avd.aquasec.com/nvd/cve-2026-95210 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-127039,UNKNOWN,,fix_deferred,The certificate authentication info handling in gnutls from 2.5.9 up t ...,https://avd.aquasec.com/nvd/cve-2026-127039 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-127040,UNKNOWN,,fix_deferred,The RSA-PSK ClientKeyExchange handler in gnutls before 3.8.14 does not ...,https://avd.aquasec.com/nvd/cve-2026-127040 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-127231,UNKNOWN,,fix_deferred,A double free in the X.509 name constraints enforcement of GnuTLS 3.8. ...,https://avd.aquasec.com/nvd/cve-2026-127231 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libmount1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libmount1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libncursesw6,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,libncursesw6,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,libncursesw6,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,libp11-kit0,0.24.1-2,CVE-2026-13757,MEDIUM,,fix_deferred,p11-kit: Stack exhaustion via unbounded recursion in RPC attribute parsing,https://avd.aquasec.com/nvd/cve-2026-13757 +debian,libp11-kit0,0.24.1-2,CVE-2026-18938,MEDIUM,,fix_deferred,p11-kit: Integer overflow in RPC attribute-array length calculation can under-allocate nested attribute storage on 32 bit systems,https://avd.aquasec.com/nvd/cve-2026-18938 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-402D17,UNKNOWN,,affected,[GHSA-4q85-33p6-j5g6: Incorrect 64-bit comparison merge in libseccomp can weaken seccomp filters],https://security-tracker.debian.org/tracker/TEMP-0000000-402D17 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-414660,UNKNOWN,,affected,[GHSA-35x7-vh54-jvqf: Incorrect accumulator reloads when comparing arguments can lead to erroneous actions],https://security-tracker.debian.org/tracker/TEMP-0000000-414660 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-43231F,UNKNOWN,,affected,[GHSA-2hqh-5c36-grrm: Oversized seccomp filters can trigger libseccomp heap corruption],https://security-tracker.debian.org/tracker/TEMP-0000000-43231F +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-AE2C66,UNKNOWN,,affected,[GHSA-84vx-jqqr-h4f2: Unmatched seccomp transaction rejections can result in a segmentation fault],https://security-tracker.debian.org/tracker/TEMP-0000000-AE2C66 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-ED49F3,UNKNOWN,,affected,[GHSA-q75f-27j4-2h7j: Missing syscall-number load in BPF filter can bypass seccomp restrictions],https://security-tracker.debian.org/tracker/TEMP-0000000-ED49F3 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-F88C7E,UNKNOWN,,affected,[GHSA-qxh5-4cq9-6mjx: Crafted seccomp rules can trigger an infinite loop in libseccomp],https://security-tracker.debian.org/tracker/TEMP-0000000-F88C7E +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-FCA4C0,UNKNOWN,,affected,[GHSA-46fr-jh49-xvhx: Oversized seccomp filters can trigger libseccomp double free],https://security-tracker.debian.org/tracker/TEMP-0000000-FCA4C0 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-7458,CRITICAL,,affected,sqlite: SQLite integer overflow,https://avd.aquasec.com/nvd/cve-2025-7458 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-11822,HIGH,,fix_deferred,sqlite: SQLite: Arbitrary code execution via crafted FTS5 full-text search data,https://avd.aquasec.com/nvd/cve-2026-11822 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-11824,HIGH,,fix_deferred,sqlite: SQLite: Arbitrary code execution and crash via heap-based buffer overflow in FTS5,https://avd.aquasec.com/nvd/cve-2026-11824 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119373,HIGH,,affected,sqlite: sqlite: Denial of service via heap-based buffer overflow in FTS5,https://avd.aquasec.com/nvd/cve-2026-119373 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119374,HIGH,,affected,sqlite: sqlite: Arbitrary code execution via corrupted FTS5 index,https://avd.aquasec.com/nvd/cve-2026-119374 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119379,HIGH,,affected,sqlite: sqlite: Arbitrary code execution via crafted session changesets,https://avd.aquasec.com/nvd/cve-2026-119379 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-7709,MEDIUM,,affected,An integer overflow exists in the FTS5 https://sqlite.org/fts5.html e ...,https://avd.aquasec.com/nvd/cve-2025-7709 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119371,MEDIUM,,affected,sqlite: sqlite: Denial of Service via stack exhaustion from deeply nested Common Table Expressions,https://avd.aquasec.com/nvd/cve-2026-119371 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119372,MEDIUM,,affected,sqlite: sqlite: Denial of Service via use-after-free in full-text search,https://avd.aquasec.com/nvd/cve-2026-119372 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119375,MEDIUM,,affected,sqlite: sqlite: Information disclosure via undersized WAL page size,https://avd.aquasec.com/nvd/cve-2026-119375 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119376,MEDIUM,,affected,sqlite: sqlite: Denial of Service via stack exhaustion from chained COLLATE operators,https://avd.aquasec.com/nvd/cve-2026-119376 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119378,MEDIUM,,affected,sqlite: sqlite: Denial of Service via use-after-free in R-Tree extension,https://avd.aquasec.com/nvd/cve-2026-119378 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119591,MEDIUM,,affected,sqlite: sqlite: Denial of Service via stack exhaustion in countOfViewOptimization(),https://avd.aquasec.com/nvd/cve-2026-119591 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-50812,MEDIUM,,fix_deferred,sqlite: SQLite: Denial of Service via malformed changeset in Session Extension,https://avd.aquasec.com/nvd/cve-2026-50812 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-50813,MEDIUM,,fix_deferred,sqlite: SQLite: Information disclosure via Session Extension changeset merge path,https://avd.aquasec.com/nvd/cve-2026-50813 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2021-45346,LOW,,affected,sqlite: crafted SQL query allows a malicious user to obtain sensitive information,https://avd.aquasec.com/nvd/cve-2021-45346 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-29088,LOW,,affected,sqlite: Denial of Service in SQLite,https://avd.aquasec.com/nvd/cve-2025-29088 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-70873,LOW,,affected,sqlite: SQLite: Information Disclosure via Crafted ZIP File,https://avd.aquasec.com/nvd/cve-2025-70873 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119377,LOW,,fix_deferred,sqlite: sqlite: Authorization bypass via USING clause in JOIN queries,https://avd.aquasec.com/nvd/cve-2026-119377 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-107496,MEDIUM,,affected,openssl: openssl: Denial of Service via crafted EC certificate in CMS encryption,https://avd.aquasec.com/nvd/cve-2026-107496 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-84786,MEDIUM,,affected,openssl: OpenSSL: Denial of Service via NULL pointer dereference during DANE TLSA record processing,https://avd.aquasec.com/nvd/cve-2026-84786 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-95690,MEDIUM,,affected,openssl: openssl: Denial of service via crafted out-of-sequence DTLS handshake fragments,https://avd.aquasec.com/nvd/cve-2026-95690 +debian,libssl3,3.0.22-1~deb12u2,CVE-2025-27587,LOW,,affected,OpenSSL 3.0.0 through 3.3.2 on the PowerPC architecture is vulnerable ...,https://avd.aquasec.com/nvd/cve-2025-27587 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-107493,LOW,,affected,openssl: openssl: Denial of Service via malformed PEM data in PEM_X509_INFO_read_bio_ex,https://avd.aquasec.com/nvd/cve-2026-107493 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-121481,LOW,,affected,openssl: openssl: Out-of-bounds write via integer overflow in EVP_EncodeBlock(),https://avd.aquasec.com/nvd/cve-2026-121481 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-102010,MEDIUM,,fix_deferred,gcc-toolset-15-gcc: gcc: gcc-toolset-16: gcc: Denial of Service via use-after-free in binary heap erase_if,https://avd.aquasec.com/nvd/cve-2026-102010 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-114690,MEDIUM,,affected,gcc: Confirmed out-of-bounds read/write in libstdc++ parallel `std,https://avd.aquasec.com/nvd/cve-2026-114690 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-114691,MEDIUM,,affected,gcc: Integer wrap in `std,https://avd.aquasec.com/nvd/cve-2026-114691 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-125709,MEDIUM,,fix_deferred,libstdc++: overflow leaves streambuf in inconsistent state on I/O error.,https://avd.aquasec.com/nvd/cve-2026-125709 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-95619,MEDIUM,,fix_deferred,gcc: libstdc++ integer overflow in `new` operator,https://avd.aquasec.com/nvd/cve-2026-95619 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2022-27943,LOW,,affected,binutils: libiberty/rust-demangle.c in GNU GCC 11.2 allows stack exhaustion in demangle_const,https://avd.aquasec.com/nvd/cve-2022-27943 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-115456,LOW,,fix_deferred,gcc: Out-of-bounds read in std::from_chars,https://avd.aquasec.com/nvd/cve-2026-115456 +debian,libsystemd0,252.39-1~deb12u2,CVE-2026-16742,HIGH,,fix_deferred,systemd: systemd-homed: Local privilege escalation via missing home-record signature verification,https://avd.aquasec.com/nvd/cve-2026-16742 +debian,libsystemd0,252.39-1~deb12u2,CVE-2026-15059,MEDIUM,,fix_deferred,systemd: systemd-oomd: Unprivileged users can terminate arbitrary processes via IPC API,https://avd.aquasec.com/nvd/cve-2026-15059 +debian,libsystemd0,252.39-1~deb12u2,CVE-2013-4392,LOW,,affected,systemd: TOCTOU race condition when updating file permissions and SELinux security contexts,https://avd.aquasec.com/nvd/cve-2013-4392 +debian,libsystemd0,252.39-1~deb12u2,CVE-2023-31437,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify a seale ...,https://avd.aquasec.com/nvd/cve-2023-31437 +debian,libsystemd0,252.39-1~deb12u2,CVE-2023-31438,LOW,,affected,An issue was discovered in systemd 253. An attacker can truncate a sea ...,https://avd.aquasec.com/nvd/cve-2023-31438 +debian,libsystemd0,252.39-1~deb12u2,CVE-2023-31439,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify the con ...,https://avd.aquasec.com/nvd/cve-2023-31439 +debian,libtasn1-6,4.19.0-2+deb12u1,CVE-2025-13151,LOW,,affected,libtasn1: libtasn1: Denial of Service via stack-based buffer overflow in asn1_expend_octet_string,https://avd.aquasec.com/nvd/cve-2025-13151 +debian,libtinfo6,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,libtinfo6,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,libtinfo6,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,libtirpc-common,1.3.3+ds-1,CVE-2026-104357,MEDIUM,,affected,libtirpc: libtirpc: SunRPC UDP datagram-boundary violation (stale buffer bytes decoded as current request),https://avd.aquasec.com/nvd/cve-2026-104357 +debian,libtirpc-common,1.3.3+ds-1,CVE-2026-85231,MEDIUM,,affected,libtirpc: libtirpc: Denial of service via unbounded memory allocation during RPCSEC_GSS decoding,https://avd.aquasec.com/nvd/cve-2026-85231 +debian,libtirpc-common,1.3.3+ds-1,CVE-2026-85977,MEDIUM,,affected,libtirpc: libtirpc: Denial of Service via unbounded memory allocation during portmapper response decoding,https://avd.aquasec.com/nvd/cve-2026-85977 +debian,libtirpc3,1.3.3+ds-1,CVE-2026-104357,MEDIUM,,affected,libtirpc: libtirpc: SunRPC UDP datagram-boundary violation (stale buffer bytes decoded as current request),https://avd.aquasec.com/nvd/cve-2026-104357 +debian,libtirpc3,1.3.3+ds-1,CVE-2026-85231,MEDIUM,,affected,libtirpc: libtirpc: Denial of service via unbounded memory allocation during RPCSEC_GSS decoding,https://avd.aquasec.com/nvd/cve-2026-85231 +debian,libtirpc3,1.3.3+ds-1,CVE-2026-85977,MEDIUM,,affected,libtirpc: libtirpc: Denial of Service via unbounded memory allocation during portmapper response decoding,https://avd.aquasec.com/nvd/cve-2026-85977 +debian,libudev1,252.39-1~deb12u2,CVE-2026-16742,HIGH,,fix_deferred,systemd: systemd-homed: Local privilege escalation via missing home-record signature verification,https://avd.aquasec.com/nvd/cve-2026-16742 +debian,libudev1,252.39-1~deb12u2,CVE-2026-15059,MEDIUM,,fix_deferred,systemd: systemd-oomd: Unprivileged users can terminate arbitrary processes via IPC API,https://avd.aquasec.com/nvd/cve-2026-15059 +debian,libudev1,252.39-1~deb12u2,CVE-2013-4392,LOW,,affected,systemd: TOCTOU race condition when updating file permissions and SELinux security contexts,https://avd.aquasec.com/nvd/cve-2013-4392 +debian,libudev1,252.39-1~deb12u2,CVE-2023-31437,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify a seale ...,https://avd.aquasec.com/nvd/cve-2023-31437 +debian,libudev1,252.39-1~deb12u2,CVE-2023-31438,LOW,,affected,An issue was discovered in systemd 253. An attacker can truncate a sea ...,https://avd.aquasec.com/nvd/cve-2023-31438 +debian,libudev1,252.39-1~deb12u2,CVE-2023-31439,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify the con ...,https://avd.aquasec.com/nvd/cve-2023-31439 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libzstd1,1.5.4+dfsg2-5,CVE-2026-124851,HIGH,,affected,zstd: Zstandard Information Disclosure via Uninitialized Buffer,https://avd.aquasec.com/nvd/cve-2026-124851 +debian,login,1:4.13+dfsg1-1+deb12u2,CVE-2007-5686,LOW,,affected,initscripts in rPath Linux 1 sets insecure permissions for the /var/lo ...,https://avd.aquasec.com/nvd/cve-2007-5686 +debian,login,1:4.13+dfsg1-1+deb12u2,CVE-2024-56433,LOW,,affected,shadow-utils: Default subordinate ID configuration in /etc/login.defs could lead to compromise,https://avd.aquasec.com/nvd/cve-2024-56433 +debian,login,1:4.13+dfsg1-1+deb12u2,TEMP-0628843-DBAD28,LOW,,affected,[more related to CVE-2005-4890],https://security-tracker.debian.org/tracker/TEMP-0628843-DBAD28 +debian,login,1:4.13+dfsg1-1+deb12u2,CVE-2026-135901,UNKNOWN,,affected,[shadow: Security fix for newgidmap],https://avd.aquasec.com/nvd/cve-2026-135901 +debian,mount,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,mount,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,mount,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,mount,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,mount,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,mount,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,mount,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,mount,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,ncurses-base,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,ncurses-base,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,ncurses-base,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,ncurses-bin,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,ncurses-bin,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,ncurses-bin,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-107496,MEDIUM,,affected,openssl: openssl: Denial of Service via crafted EC certificate in CMS encryption,https://avd.aquasec.com/nvd/cve-2026-107496 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-84786,MEDIUM,,affected,openssl: OpenSSL: Denial of Service via NULL pointer dereference during DANE TLSA record processing,https://avd.aquasec.com/nvd/cve-2026-84786 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-95690,MEDIUM,,affected,openssl: openssl: Denial of service via crafted out-of-sequence DTLS handshake fragments,https://avd.aquasec.com/nvd/cve-2026-95690 +debian,openssl,3.0.22-1~deb12u2,CVE-2025-27587,LOW,,affected,OpenSSL 3.0.0 through 3.3.2 on the PowerPC architecture is vulnerable ...,https://avd.aquasec.com/nvd/cve-2025-27587 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-107493,LOW,,affected,openssl: openssl: Denial of Service via malformed PEM data in PEM_X509_INFO_read_bio_ex,https://avd.aquasec.com/nvd/cve-2026-107493 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-121481,LOW,,affected,openssl: openssl: Out-of-bounds write via integer overflow in EVP_EncodeBlock(),https://avd.aquasec.com/nvd/cve-2026-121481 +debian,passwd,1:4.13+dfsg1-1+deb12u2,CVE-2007-5686,LOW,,affected,initscripts in rPath Linux 1 sets insecure permissions for the /var/lo ...,https://avd.aquasec.com/nvd/cve-2007-5686 +debian,passwd,1:4.13+dfsg1-1+deb12u2,CVE-2024-56433,LOW,,affected,shadow-utils: Default subordinate ID configuration in /etc/login.defs could lead to compromise,https://avd.aquasec.com/nvd/cve-2024-56433 +debian,passwd,1:4.13+dfsg1-1+deb12u2,TEMP-0628843-DBAD28,LOW,,affected,[more related to CVE-2005-4890],https://security-tracker.debian.org/tracker/TEMP-0628843-DBAD28 +debian,passwd,1:4.13+dfsg1-1+deb12u2,CVE-2026-135901,UNKNOWN,,affected,[shadow: Security fix for newgidmap],https://avd.aquasec.com/nvd/cve-2026-135901 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-9538,HIGH,,fix_deferred,perl-Archive-Tar: perl-Archive-Tar: Denial of Service via crafted tar header with large entry size,https://avd.aquasec.com/nvd/cve-2026-9538 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-15534,MEDIUM,,fix_deferred,perl: Perl: Arbitrary code execution via out-of-bounds memory access in regular expression engine.,https://avd.aquasec.com/nvd/cve-2026-15534 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-82560,MEDIUM,,fix_deferred,Pod::Text versions before 6.1.1 for Perl allow CPU and memory exhausti ...,https://avd.aquasec.com/nvd/cve-2026-82560 +debian,perl-base,5.36.0-7+deb12u4,CVE-2011-4116,LOW,,affected,perl: File:: Temp insecure temporary file handling,https://avd.aquasec.com/nvd/cve-2011-4116 +debian,perl-base,5.36.0-7+deb12u4,CVE-2023-31486,LOW,,affected,http-tiny: perl: insecure TLS cert default,https://avd.aquasec.com/nvd/cve-2023-31486 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-40558,UNKNOWN,,affected,CVE-2026-40558,https://avd.aquasec.com/nvd/cve-2026-40558 +debian,sysvinit-utils,3.06-4,TEMP-0517018-A83CE6,LOW,,affected,[sysvinit: no-root option in expert installer exposes locally exploitable security flaw],https://security-tracker.debian.org/tracker/TEMP-0517018-A83CE6 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2026-18477,MEDIUM,,fix_deferred,tar: tar: TOCTOU in incremental dumpdir 'X' rename handling allows restore path escape,https://avd.aquasec.com/nvd/cve-2026-18477 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2026-18508,MEDIUM,,fix_deferred,tar: tar: --one-top-level hardlink targets not confined to top-level directory enabling arbitrary file overwrite,https://avd.aquasec.com/nvd/cve-2026-18508 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2026-5704,MEDIUM,,affected,tar: tar: Hidden file injection via crafted archives,https://avd.aquasec.com/nvd/cve-2026-5704 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2005-2541,LOW,,affected,tar: does not properly warn the user when extracting setuid or setgid files,https://avd.aquasec.com/nvd/cve-2005-2541 +debian,tar,1.34+dfsg-1.2+deb12u1,TEMP-0290435-0B57B5,LOW,,affected,[tar's rmt command may have undesired side effects],https://security-tracker.debian.org/tracker/TEMP-0290435-0B57B5 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,util-linux,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,util-linux,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,zlib1g,1:1.2.13.dfsg-1,CVE-2023-45853,CRITICAL,,will_not_fix,zlib: integer overflow and resultant heap-based buffer overflow in zipOpenNewFileInZip4_6,https://avd.aquasec.com/nvd/cve-2023-45853 +debian,zlib1g,1:1.2.13.dfsg-1,CVE-2026-85091,HIGH,,affected,zlib: zlib: Heap buffer overflow in gz_vacate() allows arbitrary code execution,https://avd.aquasec.com/nvd/cve-2026-85091 +debian,zlib1g,1:1.2.13.dfsg-1,CVE-2026-27171,MEDIUM,,affected,zlib: zlib: Denial of Service via infinite loop in CRC32 combine functions,https://avd.aquasec.com/nvd/cve-2026-27171 +python-pkg,opentelemetry-api,1.38.0,CVE-2026-114603,MEDIUM,1.45.1,fixed,opentelemetry-api: opentelemetry-api: Denial of Service via regular expression backtracking in header parsing,https://avd.aquasec.com/nvd/cve-2026-114603 +python-pkg,opentelemetry-api,1.38.0,CVE-2026-126360,MEDIUM,1.45.2,fixed,opentelemetry-api: opentelemetry-api: Denial of Service via regular expression backtracking,https://avd.aquasec.com/nvd/cve-2026-126360 +python-pkg,pip,25.0.1,CVE-2025-8869,MEDIUM,25.3,fixed,pip: pip missing checks on symbolic link extraction,https://avd.aquasec.com/nvd/cve-2025-8869 +python-pkg,pip,25.0.1,CVE-2026-13346,MEDIUM,26.2.0,fixed,pip: pip: Arbitrary file installation via malicious package indexes,https://avd.aquasec.com/nvd/cve-2026-13346 +python-pkg,pip,25.0.1,CVE-2026-3219,MEDIUM,26.1,fixed,pip: pip: Incorrect file installation due to improper archive handling,https://avd.aquasec.com/nvd/cve-2026-3219 +python-pkg,pip,25.0.1,CVE-2026-6357,MEDIUM,26.1,fixed,pip: pip: Arbitrary code execution or information disclosure via malicious wheel package installation,https://avd.aquasec.com/nvd/cve-2026-6357 +python-pkg,pip,25.0.1,CVE-2026-8643,MEDIUM,26.1.2,fixed,python-pip: Path traversal via malicious entry point name in pip wheel installation allows arbitrary file overwrite,https://avd.aquasec.com/nvd/cve-2026-8643 +python-pkg,pip,25.0.1,CVE-2026-1703,LOW,26.0,fixed,pip: pip: Information disclosure via path traversal when installing crafted wheel archives,https://avd.aquasec.com/nvd/cve-2026-1703 +python-pkg,starlette,0.41.3,CVE-2025-62727,HIGH,0.49.1,fixed,starlette: Starlette DoS via Range header merging,https://avd.aquasec.com/nvd/cve-2025-62727 +python-pkg,starlette,0.41.3,CVE-2026-48818,HIGH,1.1.0,fixed,starlette: Starlette: SSRF and NTLM credential theft via UNC paths in StaticFiles on Windows,https://avd.aquasec.com/nvd/cve-2026-48818 +python-pkg,starlette,0.41.3,CVE-2026-54283,HIGH,1.3.1,fixed,starlette: Starlette: request.form() limits silently ignored for application/x-www-form-urlencoded enable DoS,https://avd.aquasec.com/nvd/cve-2026-54283 +python-pkg,starlette,0.41.3,CVE-2025-54121,MEDIUM,0.47.2,fixed,starlette: Starlette denial-of-service,https://avd.aquasec.com/nvd/cve-2025-54121 +python-pkg,starlette,0.41.3,CVE-2026-48710,MEDIUM,1.0.1,fixed,starlette: Starlette: Security restriction bypass via malformed HTTP Host header,https://avd.aquasec.com/nvd/cve-2026-48710 +python-pkg,starlette,0.41.3,CVE-2026-48817,MEDIUM,1.1.0,fixed,starlette: Starlette: Information disclosure and unintended method execution via non-standard HTTP methods,https://avd.aquasec.com/nvd/cve-2026-48817 +python-pkg,starlette,0.41.3,CVE-2026-54282,LOW,1.3.0,fixed,starlette: Starlette: Information disclosure due to improper HTTP request path validation,https://avd.aquasec.com/nvd/cve-2026-54282 diff --git a/evidence/scan-summary.json b/evidence/scan-summary.json new file mode 100644 index 0000000..76da73e --- /dev/null +++ b/evidence/scan-summary.json @@ -0,0 +1,40 @@ +{ + "before": { + "image_id": "sha256:0c0f7c060303d5c1157ca12f6c058b0475866c0a4852cb9a65de4df3289e784f", + "counts": { + "debian": { + "HIGH": 145, + "LOW": 164, + "MEDIUM": 232, + "UNKNOWN": 25, + "CRITICAL": 9 + }, + "python-pkg": { + "MEDIUM": 30, + "CRITICAL": 5, + "HIGH": 40, + "LOW": 2 + } + } + }, + "after": { + "image_id": "sha256:6e8a0e258485d21c9b4f239cf2856de6b9d0aefc0b34853dc82a74d28f7d1842", + "counts": { + "debian": { + "LOW": 114, + "HIGH": 100, + "MEDIUM": 148, + "UNKNOWN": 18, + "CRITICAL": 2 + }, + "python-pkg": { + "MEDIUM": 10, + "LOW": 2, + "HIGH": 3 + } + }, + "docker_manifest_id": "sha256:8ce282347ac73e6fd187038941b84d16df7cceede5a47e8310f381ae0275e3f6", + "scanner": "Trivy 0.76.2", + "scanned_at": "2026-11-27T18:52:12.467848599Z" + } +} diff --git a/evidence/security.txt b/evidence/security.txt new file mode 100644 index 0000000..ff2e222 --- /dev/null +++ b/evidence/security.txt @@ -0,0 +1 @@ +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 0000000..b484213 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1 @@ +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/telemetry.json b/evidence/telemetry.json new file mode 100644 index 0000000..23e227e --- /dev/null +++ b/evidence/telemetry.json @@ -0,0 +1,9 @@ +{ + "metric_series": 161, + "log_streams": 328, + "trace_results": 100, + "checked_trace_bodies": 20, + "credential_canaries_absent": true, + "grafana_write_denied": true, + "grafana_datasource_health": true +} \ No newline at end of file diff --git a/evidence/verification.txt b/evidence/verification.txt new file mode 100644 index 0000000..4523940 --- /dev/null +++ b/evidence/verification.txt @@ -0,0 +1,17 @@ +Verification date: 2026-11-27 (Europe/Moscow) +$ python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +PASS: Python syntax in 44 application/operator/test modules +PASS: public tests and OpenAPI unchanged; assignment README retained +PASS: staged files contain no generated secret values/private keys or temporary archives/caches/raw scans +PASS: REPORT and PR template filled; local Markdown links resolve +$ python scripts/lab7.py bootstrap +PASS: repeated bootstrap with existing volumes; HTTPS readiness 200 +$ python scripts/lab7.py verify +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. +PASS: 114 internal checks and 16 lifecycle checks; suite complete +PASS: all 26 running service containers inspected after suite; HTTPS readiness 200 with CA verification +PASS: Trivy 0.76.2 final image scan complete; config digest matched docker-save archive +$ git diff --cached --check +PASS: staged diff has no whitespace errors diff --git a/infra/grafana/provisioning/datasources/sources.yaml b/infra/grafana/provisioning/datasources/sources.yaml index 2a3dc75..68fb32c 100644 --- a/infra/grafana/provisioning/datasources/sources.yaml +++ b/infra/grafana/provisioning/datasources/sources.yaml @@ -1,41 +1,53 @@ +# Public template. lab7.py injects cert/key into ignored secrets/grafana-datasources. apiVersion: 1 datasources: - - name: Prometheus - uid: prometheus - type: prometheus - access: proxy - url: http://prometheus:9090 - isDefault: true - jsonData: - timeInterval: 5s - exemplarTraceIdDestinations: - - name: trace_id - datasourceUid: tempo - - name: Loki - uid: loki - type: loki - access: proxy - url: http://loki:3100 - jsonData: - derivedFields: - - name: trace_id - matcherType: label - matcherRegex: trace_id - datasourceUid: tempo - url: '$${__value.raw}' - urlDisplayLabel: View trace - - name: Tempo - uid: tempo - type: tempo - access: proxy - url: http://tempo:3200 - jsonData: - tracesToLogsV2: - datasourceUid: loki - spanStartTimeShift: '-5m' - spanEndTimeShift: '5m' - tags: [{key: service.name, value: service_name}] - filterByTraceID: true - filterBySpanID: false - nodeGraph: - enabled: true +- name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:19090 + isDefault: true + jsonData: + timeInterval: 5s + exemplarTraceIdDestinations: + - name: trace_id + datasourceUid: tempo + tlsAuth: true + tlsAuthWithCACert: true + serverName: prometheus +- name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:13100 + jsonData: + derivedFields: + - name: trace_id + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: $${__value.raw} + urlDisplayLabel: View trace + tlsAuth: true + tlsAuthWithCACert: true + serverName: loki +- name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:13200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -5m + spanEndTimeShift: 5m + tags: + - key: service.name + value: service_name + filterByTraceID: true + filterBySpanID: false + nodeGraph: + enabled: true + tlsAuth: true + tlsAuthWithCACert: true + serverName: tempo diff --git a/infra/nginx.conf b/infra/nginx.conf deleted file mode 100644 index 1cc308b..0000000 --- a/infra/nginx.conf +++ /dev/null @@ -1,38 +0,0 @@ -worker_processes 1; -worker_shutdown_timeout 8s; -events { worker_connections 1024; } -http { - upstream messenger { - zone messenger 64k; - include /etc/nginx/ready-backends.conf; - } - log_format upstream '$request_method $uri $status upstream=$upstream_addr ' - 'upstream_status=$upstream_status time=$request_time'; - access_log /var/log/nginx/access.log upstream; - server { - listen 8080; - # API enforces the byte limit and returns the contracted JSON error. - client_max_body_size 0; - client_body_timeout 5s; - client_header_timeout 5s; - keepalive_timeout 5s; - location / { - proxy_pass http://messenger; - proxy_http_version 1.1; - proxy_request_buffering off; - proxy_buffering off; - proxy_set_header Host $host; - proxy_set_header Connection close; - proxy_connect_timeout 1s; - proxy_send_timeout 35s; - proxy_read_timeout 120s; - # A 503 is an API response (for example, S3 is unavailable), so - # preserve it for the client instead of marking every replica down. - proxy_next_upstream error timeout http_502 http_504; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 8s; - # Never transparently retry a POST already sent to an API. - # A client retries messages using the original Idempotency-Key. - } - } -} diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 0850e23..db49ea9 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,7 +1,5 @@ -# OpenBao — реализовать конфигурацию и политики +# OpenBao -Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. - -Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения. - -Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md. +Non-dev file storage и TLS: config.hcl. Scoped KV policies: api/worker/dispatcher/cleanup.hcl. +Bootstrap, init/unseal и lifecycle: [инструкция оператора](../../security/OPERATIONS.md). +Секреты и ключи генерируются локально; в этом каталоге их нет. diff --git a/infra/openbao/api.hcl b/infra/openbao/api.hcl new file mode 100644 index 0000000..e880a9e --- /dev/null +++ b/infra/openbao/api.hcl @@ -0,0 +1,2 @@ +path "secret/data/api" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/cleanup.hcl b/infra/openbao/cleanup.hcl new file mode 100644 index 0000000..723539d --- /dev/null +++ b/infra/openbao/cleanup.hcl @@ -0,0 +1,2 @@ +path "secret/data/cleanup" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/config.hcl b/infra/openbao/config.hcl new file mode 100644 index 0000000..283c3a4 --- /dev/null +++ b/infra/openbao/config.hcl @@ -0,0 +1,11 @@ +ui = false +api_addr = "https://openbao:8200" +storage "file" { path = "/bao/data" } +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/identity/tls.crt" + tls_key_file = "/run/identity/tls.key" + tls_client_ca_file = "/run/identity/ca.crt" + tls_min_version = "tls12" + tls_max_version = "tls12" +} diff --git a/infra/openbao/dispatcher.hcl b/infra/openbao/dispatcher.hcl new file mode 100644 index 0000000..ca57393 --- /dev/null +++ b/infra/openbao/dispatcher.hcl @@ -0,0 +1,2 @@ +path "secret/data/dispatcher" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/worker.hcl b/infra/openbao/worker.hcl new file mode 100644 index 0000000..1a5e177 --- /dev/null +++ b/infra/openbao/worker.hcl @@ -0,0 +1,2 @@ +path "secret/data/worker" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index 529a107..8b336d9 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -2,8 +2,7 @@ receivers: otlp: protocols: http: - endpoint: 0.0.0.0:4318 - + endpoint: 127.0.0.1:4318 processors: memory_limiter: check_interval: 1s @@ -13,17 +12,16 @@ processors: timeout: 1s send_batch_size: 128 send_batch_max_size: 256 - exporters: prometheus: - endpoint: 0.0.0.0:8889 + endpoint: 127.0.0.1:8889 resource_to_telemetry_conversion: enabled: true enable_open_metrics: true metric_expiration: 30s translation_strategy: UnderscoreEscapingWithSuffixes otlphttp/loki: - endpoint: http://loki:3100/otlp + endpoint: https://loki:13100/otlp timeout: 2s sending_queue: queue_size: 32 @@ -33,8 +31,12 @@ exporters: initial_interval: 1s max_interval: 5s max_elapsed_time: 15s + tls: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key otlphttp/tempo: - endpoint: http://tempo:4318 + endpoint: https://tempo:14318 timeout: 2s sending_queue: queue_size: 32 @@ -44,26 +46,41 @@ exporters: initial_interval: 1s max_interval: 5s max_elapsed_time: 15s - + tls: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key service: telemetry: metrics: readers: - - pull: - exporter: - prometheus: - host: 0.0.0.0 - port: 8888 + - pull: + exporter: + prometheus: + host: 127.0.0.1 + port: 8888 pipelines: metrics: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [prometheus] + receivers: + - otlp + processors: + - memory_limiter + - batch + exporters: + - prometheus logs: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [otlphttp/loki] + receivers: + - otlp + processors: + - memory_limiter + - batch + exporters: + - otlphttp/loki traces: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [otlphttp/tempo] + receivers: + - otlp + processors: + - memory_limiter + - batch + exporters: + - otlphttp/tempo diff --git a/infra/otel/loki.yaml b/infra/otel/loki.yaml index b5cf04f..6d6df22 100644 --- a/infra/otel/loki.yaml +++ b/infra/otel/loki.yaml @@ -1,7 +1,10 @@ auth_enabled: false server: http_listen_port: 3100 + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 common: + instance_addr: 127.0.0.1 path_prefix: /loki replication_factor: 1 ring: @@ -13,13 +16,13 @@ common: rules_directory: /loki/rules schema_config: configs: - - from: 2024-01-01 - store: tsdb - object_store: filesystem - schema: v13 - index: - prefix: index_ - period: 24h + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h limits_config: allow_structured_metadata: true retention_period: 72h @@ -27,8 +30,10 @@ limits_config: resource_attributes: ignore_defaults: true attributes_config: - - action: index_label - attributes: [service.name, deployment.environment.name] + - action: index_label + attributes: + - service.name + - deployment.environment.name compactor: working_directory: /loki/compactor retention_enabled: true diff --git a/infra/otel/prometheus.yaml b/infra/otel/prometheus.yaml index 5613d18..547cb37 100644 --- a/infra/otel/prometheus.yaml +++ b/infra/otel/prometheus.yaml @@ -2,11 +2,23 @@ global: scrape_interval: 5s evaluation_interval: 5s rule_files: - - /etc/prometheus/alerts.yaml +- /etc/prometheus/alerts.yaml scrape_configs: - - job_name: messenger - static_configs: - - targets: ['otel-collector:8889'] - - job_name: collector - static_configs: - - targets: ['otel-collector:8888'] +- job_name: messenger + static_configs: + - targets: + - otel-collector:18889 + scheme: https + tls_config: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key +- job_name: collector + static_configs: + - targets: + - otel-collector:18888 + scheme: https + tls_config: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key diff --git a/infra/otel/tempo.yaml b/infra/otel/tempo.yaml index 9653bf2..496f1b4 100644 --- a/infra/otel/tempo.yaml +++ b/infra/otel/tempo.yaml @@ -1,12 +1,16 @@ server: http_listen_port: 3200 + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 distributor: receivers: otlp: protocols: http: - endpoint: 0.0.0.0:4318 + endpoint: 127.0.0.1:4318 ingester: + lifecycler: + address: 127.0.0.1 trace_idle_period: 10s max_block_duration: 5m compactor: diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..6c31017 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,3 @@ +local all all trust +hostssl messenger all 0.0.0.0/0 scram-sha-256 +hostssl messenger all ::/0 scram-sha-256 diff --git a/infra/postgres/start.sh b/infra/postgres/start.sh new file mode 100644 index 0000000..d049130 --- /dev/null +++ b/infra/postgres/start.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +cp /run/identity/tls.key /tmp/server.key +chown postgres:postgres /tmp/server.key +chmod 600 /tmp/server.key +exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/run/identity/tls.crt -c ssl_key_file=/tmp/server.key -c hba_file=/etc/pg_hba.conf diff --git a/infra/readiness.sh b/infra/readiness.sh deleted file mode 100644 index 9a2e627..0000000 --- a/infra/readiness.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/sh -# Only ready API addresses enter the upstream, including at nginx startup. -update_backends() { - next=/etc/nginx/ready-backends.conf.next - : > "$next" - for address in $(getent ahostsv4 api | awk '{print $1}' | sort -u); do - if wget -q -T 1 -O /dev/null "http://$address:8080/health/ready"; then - echo "server $address:8080;" >> "$next" - fi - done - # If every running API temporarily loses a shared dependency (for example - # S3), retain the last addresses. The API can then return the contracted - # 503 instead of Nginx replacing it with a 502. At initial startup there - # is no previous healthy set, so use an inert placeholder. - if [ ! -s "$next" ]; then - if [ -s /etc/nginx/ready-backends.conf ] && ! grep -q '127.0.0.1:9 down' /etc/nginx/ready-backends.conf; then - rm -f "$next" - return - fi - echo 'server 127.0.0.1:9 down;' > "$next" - fi - if ! cmp -s "$next" /etc/nginx/ready-backends.conf; then - mv "$next" /etc/nginx/ready-backends.conf - if [ "${1:-}" = reload ] && [ -f /var/run/nginx.pid ]; then - nginx -s reload - fi - else - rm -f "$next" - fi -} - -update_backends -( - while sleep 2; do - update_backends reload - done -) & -exec nginx -g 'daemon off;' diff --git a/infra/s3-api-policy.json b/infra/s3-api-policy.json new file mode 100644 index 0000000..2496f64 --- /dev/null +++ b/infra/s3-api-policy.json @@ -0,0 +1 @@ +{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]}, {"Effect": "Allow", "Action": ["s3:PutObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/originals/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/variants/*"]}]} diff --git a/infra/s3-bootstrap.sh b/infra/s3-bootstrap.sh deleted file mode 100644 index c0baf62..0000000 --- a/infra/s3-bootstrap.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -set -eu -test "$MINIO_ROOT_USER" != "$S3_ACCESS_KEY_ID" -mc alias set local http://s3:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null -mc mb --ignore-existing local/messenger-attachments -mc anonymous set none local/messenger-attachments -mc admin user add local "$S3_ACCESS_KEY_ID" "$S3_SECRET_ACCESS_KEY" >/dev/null -mc admin policy info local attachments >/dev/null 2>&1 || mc admin policy create local attachments /policy.json -mc admin policy attach local attachments --user "$S3_ACCESS_KEY_ID" diff --git a/infra/s3-cleanup-policy.json b/infra/s3-cleanup-policy.json new file mode 100644 index 0000000..240313a --- /dev/null +++ b/infra/s3-cleanup-policy.json @@ -0,0 +1 @@ +{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]}, {"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/originals/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/variants/*"]}]} diff --git a/infra/s3-policy.json b/infra/s3-policy.json deleted file mode 100644 index 8e77546..0000000 --- a/infra/s3-policy.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["s3:ListBucket", "s3:GetBucketLocation"], - "Resource": ["arn:aws:s3:::messenger-attachments"] - }, - { - "Effect": "Allow", - "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], - "Resource": ["arn:aws:s3:::messenger-attachments/originals/*", - "arn:aws:s3:::messenger-attachments/staging/*", - "arn:aws:s3:::messenger-attachments/variants/*"] - } - ] -} diff --git a/infra/s3-worker-policy.json b/infra/s3-worker-policy.json new file mode 100644 index 0000000..8d38ec9 --- /dev/null +++ b/infra/s3-worker-policy.json @@ -0,0 +1 @@ +{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]}, {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}, {"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/originals/*"]}, {"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/variants/*"]}]} diff --git a/infra/tls/api1.cfg b/infra/tls/api1.cfg new file mode 100644 index 0000000..9210b8a --- /dev/null +++ b/infra/tls/api1.cfg @@ -0,0 +1,20 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port8443 + bind :8443 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str lb } + server local 127.0.0.1:8080 diff --git a/infra/tls/api2.cfg b/infra/tls/api2.cfg new file mode 100644 index 0000000..9210b8a --- /dev/null +++ b/infra/tls/api2.cfg @@ -0,0 +1,20 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port8443 + bind :8443 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str lb } + server local 127.0.0.1:8080 diff --git a/infra/tls/broker.cfg b/infra/tls/broker.cfg new file mode 100644 index 0000000..19f7d19 --- /dev/null +++ b/infra/tls/broker.cfg @@ -0,0 +1,20 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port6380 + bind :6380 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str api dispatcher worker } + server local 127.0.0.1:6379 diff --git a/infra/tls/grafana.cfg b/infra/tls/grafana.cfg new file mode 100644 index 0000000..97b2d45 --- /dev/null +++ b/infra/tls/grafana.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port3443 + bind :3443 ssl crt /run/identity/tls.pem + server local 127.0.0.1:3000 diff --git a/infra/tls/lb.cfg b/infra/tls/lb.cfg new file mode 100644 index 0000000..f36b111 --- /dev/null +++ b/infra/tls/lb.cfg @@ -0,0 +1,34 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +frontend ingress + mode http + bind :8443 ssl crt /run/identity/tls.pem + http-request set-header X-Forwarded-Proto https + http-response set-header Strict-Transport-Security max-age=31536000 + default_backend apis +backend apis + mode http + balance roundrobin + option redispatch 1 + retries 1 + timeout connect 1s + option httpchk GET /health/ready + timeout check 1s + http-check expect status 200 + default-server inter 1s fall 1 rise 1 on-marked-down shutdown-sessions + server api1 api1:8443 ssl verify required ca-file /run/identity/ca.crt crt /run/identity/tls.pem verifyhost api1 sni str(api1) check check-sni api1 resolvers docker init-addr libc,none + server api2 api2:8443 ssl verify required ca-file /run/identity/ca.crt crt /run/identity/tls.pem verifyhost api2 sni str(api2) check check-sni api2 resolvers docker init-addr libc,none diff --git a/infra/tls/loki.cfg b/infra/tls/loki.cfg new file mode 100644 index 0000000..feede3e --- /dev/null +++ b/infra/tls/loki.cfg @@ -0,0 +1,24 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port13100 + bind :13100 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str otel-collector grafana operator } + mode http + http-request deny if { ssl_c_s_dn(CN) -m str grafana operator } !{ method GET HEAD } + http-request deny if { ssl_c_s_dn(CN) -m str otel-collector } !{ path /otlp/v1/logs } + http-request deny if { ssl_c_s_dn(CN) -m str otel-collector } !{ method POST } + server local 127.0.0.1:3100 diff --git a/infra/tls/otel-collector.cfg b/infra/tls/otel-collector.cfg new file mode 100644 index 0000000..8477cdd --- /dev/null +++ b/infra/tls/otel-collector.cfg @@ -0,0 +1,30 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port44318 + bind :44318 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str api worker dispatcher } + server local 127.0.0.1:4318 + +listen port18889 + bind :18889 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str prometheus } + server local 127.0.0.1:8889 + +listen port18888 + bind :18888 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str prometheus } + server local 127.0.0.1:8888 diff --git a/infra/tls/prometheus.cfg b/infra/tls/prometheus.cfg new file mode 100644 index 0000000..5feed70 --- /dev/null +++ b/infra/tls/prometheus.cfg @@ -0,0 +1,24 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port19090 + bind :19090 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str grafana operator } + mode http + acl read_post method POST + acl read_path path /api/v1/query /api/v1/query_range /api/v1/series + http-request deny unless { method GET HEAD } or read_post read_path + server local 127.0.0.1:9090 diff --git a/infra/tls/redis.cfg b/infra/tls/redis.cfg new file mode 100644 index 0000000..b683045 --- /dev/null +++ b/infra/tls/redis.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port6380 + bind :6380 ssl crt /run/identity/tls.pem + server local 127.0.0.1:6379 diff --git a/infra/tls/s3.cfg b/infra/tls/s3.cfg new file mode 100644 index 0000000..1e178f3 --- /dev/null +++ b/infra/tls/s3.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port9443 + bind :9443 ssl crt /run/identity/tls.pem + server local 127.0.0.1:9000 diff --git a/infra/tls/tempo.cfg b/infra/tls/tempo.cfg new file mode 100644 index 0000000..4b7d04d --- /dev/null +++ b/infra/tls/tempo.cfg @@ -0,0 +1,29 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port13200 + bind :13200 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str grafana operator } + mode http + http-request deny unless { method GET HEAD } + server local 127.0.0.1:3200 + +listen port14318 + bind :14318 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str otel-collector } + mode http + http-request deny unless { method POST } { path /v1/traces } + server local 127.0.0.1:4318 diff --git a/requirements-operator.txt b/requirements-operator.txt new file mode 100644 index 0000000..e621012 --- /dev/null +++ b/requirements-operator.txt @@ -0,0 +1,3 @@ +cryptography==50.0.2 +PyYAML==6.0.3 +requests==2.34.2 diff --git a/requirements.txt b/requirements.txt index 01c2cf2..e0f5a6d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,7 +16,7 @@ SQLAlchemy==2.0.41 redis==5.2.1 argon2-cffi==23.1.0 boto3==1.40.70 -Pillow==12.0.0 +Pillow==13.0.0 opentelemetry-api==1.38.0 opentelemetry-sdk==1.38.0 opentelemetry-exporter-otlp-proto-http==1.38.0 diff --git a/scripts/lab7.py b/scripts/lab7.py new file mode 100644 index 0000000..d89f21f --- /dev/null +++ b/scripts/lab7.py @@ -0,0 +1,328 @@ +"""Local operator: bootstrap, unseal, rotate. Never print secret material.""" +import argparse +import datetime as dt +import ipaddress +import json +import os +from pathlib import Path +import secrets +import subprocess +import sys +import time + +import requests +import yaml +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID + +ROOT = Path(__file__).resolve().parents[1] +os.chdir(ROOT) +PRIVATE = ROOT / 'secrets/operator-private' +ROLES = ['api', 'worker', 'dispatcher', 'cleanup'] +IDENTITIES = ROLES + ['api1','api2','lb','postgres','redis','broker','s3','openbao', + 'otel-collector','prometheus','loki','tempo','grafana','operator','outsider'] + + +def write(path, data): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data, encoding='utf-8', newline='\n') + if os.name != 'nt': path.chmod(0o600) + + +def docker(*args, data=None, check=True): + result = subprocess.run(['docker', *args], input=data.encode('utf-8') if data is not None else None, capture_output=True) + result.stdout = result.stdout.decode('utf-8', errors='replace') + result.stderr = result.stderr.decode('utf-8', errors='replace') + if check and result.returncode: + # Commands/stdin/output can contain credentials; keep failure messages bounded. + diagnostic=result.stderr + def hide(value): + nonlocal diagnostic + if isinstance(value,dict): + for child in value.values(): hide(child) + elif isinstance(value,list): + for child in value: hide(child) + elif isinstance(value,str) and len(value)>8: diagnostic=diagnostic.replace(value,'[redacted]') + for file in PRIVATE.glob('*.json'): hide(json.loads(file.read_text())) + for file in (ROOT/'secrets').glob('*-admin/*'): hide(file.read_text()) + raise RuntimeError('Docker operation failed: ' + ' '.join(args[:3])+'\n'+diagnostic[-1500:]) + return result + + +def compose(*args, **kw): + return docker('compose', *args, **kw) + + +def ca(): + return (serialization.load_pem_private_key((PRIVATE/'ca.key').read_bytes(), password=None), + x509.load_pem_x509_certificate((ROOT/'secrets/ca.crt').read_bytes())) + + +def issue(name, expired=False, identity=None, untrusted=False): + key, authority = ca() + identity = identity or name + issuer = authority.subject + if untrusted: + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + issuer = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Untrusted CA')]) + leaf_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + now = dt.datetime.now(dt.timezone.utc) + names = [x509.DNSName(identity)] + if identity in ('lb','openbao','grafana'): + names += [x509.DNSName('localhost'),x509.IPAddress(ipaddress.ip_address('127.0.0.1'))] + cert = (x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,identity)])) + .issuer_name(issuer).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now-dt.timedelta(days=2) if expired else now-dt.timedelta(minutes=5)) + .not_valid_after(now-dt.timedelta(days=1) if expired else now+dt.timedelta(hours=24)) + .add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),critical=False) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()),critical=False) + .add_extension(x509.KeyUsage(True,False,True,False,False,False,False,False,False),critical=True) + .add_extension(x509.SubjectAlternativeName(names),critical=False) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False) + .sign(key,hashes.SHA256())) + folder=ROOT/'secrets'/name + cert_pem=cert.public_bytes(serialization.Encoding.PEM).decode() + key_pem=leaf_key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()).decode() + for filename,content in [('tls.crt',cert_pem),('tls.key',key_pem),('tls.pem',cert_pem+key_pem),('ca.crt',authority.public_bytes(serialization.Encoding.PEM).decode())]: + write(folder/filename,content) + return cert + + +def crl(serials=()): + key,authority=ca() + now=dt.datetime.now(dt.timezone.utc) + builder=x509.CertificateRevocationListBuilder().issuer_name(authority.subject).last_update(now).next_update(now+dt.timedelta(days=7)) + for serial in serials: + builder=builder.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(serial).revocation_date(now).build()) + pem=builder.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode() + for folder in (ROOT/'secrets').iterdir(): + if folder.is_dir() and (folder/'tls.crt').exists(): write(folder/'ca.crl',pem) + + +def generate(): + if (PRIVATE/'ca.key').exists(): + print('Existing local secrets preserved'); return + PRIVATE.mkdir(parents=True,exist_ok=True) + if os.name=='nt': + user = subprocess.check_output(['whoami'],text=True).strip() + subprocess.run(['icacls',str(ROOT/'secrets'),'/inheritance:r','/grant:r',user+':(OI)(CI)F'],check=True,capture_output=True) + key=rsa.generate_private_key(public_exponent=65537,key_size=3072) + name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Lab7 local CA')]) + now=dt.datetime.now(dt.timezone.utc) + cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()) + .serial_number(x509.random_serial_number()).not_valid_before(now-dt.timedelta(minutes=5)).not_valid_after(now+dt.timedelta(days=30)) + .add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),critical=False) + .add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),critical=True).sign(key,hashes.SHA256())) + write(PRIVATE/'ca.key',key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()).decode()) + write(ROOT/'secrets/ca.crt',cert.public_bytes(serialization.Encoding.PEM).decode()) + for identity in IDENTITIES: issue(identity) + test_certificates() + crl() + config={role:{'db':secrets.token_hex(24),'s3':secrets.token_hex(24),'redis':secrets.token_hex(24),'broker':secrets.token_hex(24)} for role in ROLES} + write(PRIVATE/'credentials.json',json.dumps(config)) + for p in ['postgres-admin/postgres-password','s3-admin/password','grafana-admin/password']: + write(ROOT/'secrets'/p,secrets.token_hex(24)) + write(ROOT/'secrets/s3-admin/user','operator') + redis_config(config) + refresh_datasources() + print('Created local CA, 24-hour identities and independent service credentials') + + +def refresh_datasources(): + datasource=yaml.safe_load((ROOT/'infra/grafana/provisioning/datasources/sources.yaml').read_text()) + for ds in datasource['datasources']: + port={'prometheus':19090,'loki':13100,'tempo':13200}[ds['uid']] + ds['url']=f"https://{ds['uid']}:{port}" + ds.setdefault('jsonData',{}).update(tlsAuth=True,tlsAuthWithCACert=True,serverName=ds['uid']) + ds['secureJsonData']={'tlsCACert':(ROOT/'secrets/ca.crt').read_text(), + 'tlsClientCert':(ROOT/'secrets/grafana/tls.crt').read_text(), + 'tlsClientKey':(ROOT/'secrets/grafana/tls.key').read_text()} + write(ROOT/'secrets/grafana-datasources/sources.yaml',yaml.safe_dump(datasource,sort_keys=False)) + + +def test_certificates(): + # Keep the allowed role constant: isolate CA trust and expiry from the CN allowlist. + for identity in ['lb','worker','api']: + issue('expired-'+identity,expired=True,identity=identity) + issue('foreign-'+identity,identity=identity,untrusted=True) + + +def redis_config(config): + for name in ['redis','broker']: + lines=['user default off'] + if name=='redis': + lines.append(f"user api on >{config['api']['redis']} ~session:* ~history-v4:* ~login:* +ping +get +set +del +eval +incr +expire +pttl +ttl +client|setinfo") + else: + for role,commands in [('api','+ping'),('dispatcher','+ping +xadd +xgroup|create'), + ('worker','+ping +xgroup|create +xautoclaim +xreadgroup +xack +xdel +multi +exec')]: + lines.append(f"user {role} on >{config[role]['broker']} ~attachment-jobs {commands} +client|setinfo") + write(ROOT/f'secrets/{name}-config/users.acl','\n'.join(lines)+'\n') + write(ROOT/f'secrets/{name}-config/redis.conf','bind 127.0.0.1\nprotected-mode yes\nport 6379\nappendonly yes\nappendfsync always\nmaxmemory 128mb\nmaxmemory-policy noeviction\naclfile /run/config/users.acl\n') + + +def bao(method,path,payload=None,token=None,role=None): + session=requests.Session();session.trust_env=False + cert=None if role is None else (str(ROOT/f'secrets/{role}/tls.crt'),str(ROOT/f'secrets/{role}/tls.key')) + response=session.request(method,'https://127.0.0.1:8200/v1/'+path,json=payload, + headers={'X-Vault-Token':token} if token else {},cert=cert,verify=str(ROOT/'secrets/ca.crt'),timeout=5) + if response.status_code>=400: raise RuntimeError(f'OpenBao {path}: HTTP {response.status_code}') + return response.json() if response.content else {} + + +def unseal(): + state=json.loads((PRIVATE/'bao-init.json').read_text()) + if bao('GET','sys/seal-status')['sealed']: + bao('POST','sys/unseal',{'key':state['keys_base64'][0]}) + print('OpenBao unsealed by operator') + + +def initialize_bao(): + if not bao('GET','sys/init')['initialized']: + state=bao('POST','sys/init',{'secret_shares':1,'secret_threshold':1}) + write(PRIVATE/'bao-init.json',json.dumps(state)) + unseal() + state=json.loads((PRIVATE/'bao-init.json').read_text());token=state['root_token'] + mounts=bao('GET','sys/mounts',token=token) + if 'secret/' not in mounts: bao('POST','sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token) + auth=bao('GET','sys/auth',token=token) + if 'cert/' not in auth: bao('POST','sys/auth/cert',{'type':'cert'},token) + for role in ROLES: + policy=(ROOT/f'infra/openbao/{role}.hcl').read_text(encoding='utf-8') + bao('PUT','sys/policies/acl/'+role,{'policy':policy},token) + bao('POST','auth/cert/certs/'+role,{'certificate':(ROOT/'secrets/ca.crt').read_text(), + 'allowed_common_names':[role],'allowed_dns_sans':[role],'token_policies':[role], + 'token_ttl':60,'token_max_ttl':60,'token_explicit_max_ttl':60,'token_no_default_policy':True},token) + publish_secrets(token) + + +def publish_secrets(token): + config=json.loads((PRIVATE/'credentials.json').read_text()) + for role in ROLES: + c=config[role] + data={'DATABASE_URL':f"postgresql+psycopg://{role}:{c['db']}@postgres/messenger?sslmode=verify-full&sslrootcert=/run/identity/ca.crt"} + if role=='api': data['REDIS_URL']=f"rediss://api:{c['redis']}@redis:6380/0" + if role in ['api','worker','dispatcher']: data['BROKER_URL']=f"rediss://{role}:{c['broker']}@broker:6380/0" + if role in ['api','worker','cleanup']: + data.update(S3_ENDPOINT='https://s3:9443',S3_ACCESS_KEY_ID=role,S3_SECRET_ACCESS_KEY=c['s3']) + bao('POST','secret/data/'+role,{'data':data},token) + + +def prepare_volumes(): + volumes={'postgres':999,'redis':999,'broker':999,'s3':1000,'bao':100,'prometheus':65534,'loki':1000,'tempo':1000,'grafana':472} + for name,uid in volumes.items(): + docker('run','--rm','--network','none','--user','0','-v',f'mtusi2026lab7_{name}_data:/data', + '--entrypoint','sh','redis:7.4.2-bookworm','-c',f'chown {uid}:{uid} /data') + + +def database(): + config=json.loads((PRIVATE/'credentials.json').read_text()) + sql="CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY);\n" + for file in sorted((ROOT/'migrations').glob('*.sql')): + sql+=f"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version='{file.name}') AS applied \\gset\n\\if :applied\n\\else\nBEGIN;\n"+file.read_text()+f"\nINSERT INTO schema_migrations VALUES ('{file.name}'); COMMIT;\n\\endif\n" + sql+='REVOKE CREATE ON SCHEMA public FROM PUBLIC; REVOKE ALL ON DATABASE messenger FROM PUBLIC;\n' + for role in ROLES: + sql+=f"DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='{role}') THEN CREATE ROLE {role} LOGIN; END IF; END $$;\nALTER ROLE {role} PASSWORD '{config[role]['db']}'; GRANT CONNECT ON DATABASE messenger TO {role}; GRANT USAGE ON SCHEMA public TO {role};\n" + sql+='GRANT SELECT, INSERT, UPDATE ON users,chats,chat_members,messages,message_idempotency,attachments,attachment_jobs TO api;\n' + sql+='GRANT SELECT, UPDATE ON attachments,attachment_jobs TO worker,dispatcher;\nGRANT SELECT, UPDATE ON attachments TO cleanup;\n' + compose('exec','-T','postgres','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=sql) + + +def storage(): + cfg=json.loads((PRIVATE/'credentials.json').read_text()) + admin_user=(ROOT/'secrets/s3-admin/user').read_text();admin_pass=(ROOT/'secrets/s3-admin/password').read_text() + script=f"set -eu\nexport MC_CONFIG_DIR=/tmp/mc\nmc alias set local http://127.0.0.1:9000 {admin_user} {admin_pass} >/dev/null\nmc mb --ignore-existing local/messenger-attachments >/dev/null\nmc anonymous set none local/messenger-attachments >/dev/null\n" + for role in ['api','worker','cleanup']: + policy=(ROOT/f'infra/s3-{role}-policy.json').read_text(encoding='utf-8').strip() + script+=f"cat > /tmp/{role}.json <<'POLICY'\n{policy}\nPOLICY\nmc admin user add local {role} {cfg[role]['s3']} >/dev/null\nmc admin policy create local {role} /tmp/{role}.json >/dev/null\nmc admin policy attach local {role} --user {role} >/dev/null\n" + compose('exec','-T','s3','sh',data=script) + + +def wait_service(test,seconds=60): + deadline=time.monotonic()+seconds + while True: + try: + if test(): return + except (requests.RequestException,RuntimeError): pass + if time.monotonic()>deadline: raise RuntimeError('Service readiness timeout') + time.sleep(1) + + +def bootstrap(): + generate() + compose('config','--quiet') + prepare_volumes() + compose('up','-d','postgres','redis','broker','s3','openbao') + wait_service(lambda: bao('GET','sys/init') is not None) + initialize_bao() + wait_service(lambda: compose('exec','-T','postgres','pg_isready','-U','postgres',check=False).returncode==0) + database() + wait_service(lambda: compose('exec','-T','s3','curl','-sf','http://127.0.0.1:9000/minio/health/live',check=False).returncode==0) + storage() + compose('up','-d','--build') + wait_service(lambda: requests.get('https://localhost:8443/health/ready',verify=str(ROOT/'secrets/ca.crt'),timeout=3).status_code==200,90) + print('PASS: https://localhost:8443/health/ready; CA: secrets/ca.crt') + + +def rotate_secret(): + cfg=json.loads((PRIVATE/'credentials.json').read_text()) + cfg['api']['db']=secrets.token_hex(24) + write(PRIVATE/'credentials.json',json.dumps(cfg)) + compose('exec','-T','postgres','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=f"ALTER ROLE api PASSWORD '{cfg['api']['db']}'; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='api';") + publish_secrets(json.loads((PRIVATE/'bao-init.json').read_text())['root_token']) + print('API database credential rotated; existing connections terminated; supervisor reload <=10s') + + +def rotate_leaf(): + archive=ROOT/'secrets/old-lb';archive.mkdir(exist_ok=True) + for name in ['tls.crt','tls.key','ca.crt']: write(archive/name,(ROOT/'secrets/lb'/name).read_text()) + old=x509.load_pem_x509_certificate((archive/'tls.crt').read_bytes()) + revoked_file=PRIVATE/'revoked.json' + revoked=json.loads(revoked_file.read_text()) if revoked_file.exists() else [] + revoked.append(old.serial_number);write(revoked_file,json.dumps(revoked)) + issue('lb');crl(revoked) + compose('restart','api1-tls','api2-tls','lb') + print('LB leaf rotated, old serial revoked; TLS listeners restarted to close old sessions') + + +def verify(): + for name in ['smoke','security']: + result=compose('run','--rm','--no-deps','audit',f'/tests/{name}.py', + '--base-url','https://lb:8443','--ca-file','/audit-secrets/ca.crt') + write(ROOT/f'evidence/{name}.txt',result.stdout) + print(result.stdout.strip()) + subprocess.run([sys.executable,'-X','utf8','-u',str(ROOT/'student-tests/lifecycle.py')],check=True) + + +def restart_stack(): + services=json.loads(compose('config','--format','json').stdout)['services'] + proxies=[n for n in services if n.endswith('-tls')]+['lb'] + owners=[n for n,spec in services.items() if n not in proxies and not spec.get('profiles')] + compose('stop',*proxies) + compose('restart',*owners) + wait_service(lambda: bao('GET','sys/seal-status')['sealed'],30) + unseal() + compose('start',*proxies) + print('Restarted owners before TLS sidecars; data volumes preserved') + + +def renew_leaves(): + """Operator renewal before 24h expiry; not an automated PKI service.""" + for identity in IDENTITIES: issue(identity) + revoked_file=PRIVATE/'revoked.json' + crl(json.loads(revoked_file.read_text()) if revoked_file.exists() else []) + refresh_datasources() + restart_stack() + print('24-hour service identities renewed; no image rebuild') + + +if __name__=='__main__': + sys.stdout.reconfigure(line_buffering=True) + parser=argparse.ArgumentParser() + parser.add_argument('command',choices=['generate','bootstrap','unseal','rotate-secret','rotate-leaf','status','verify','renew-leaves','restart']) + args=parser.parse_args() + {'generate':generate,'bootstrap':bootstrap,'unseal':unseal,'rotate-secret':rotate_secret,'rotate-leaf':rotate_leaf,'status':lambda: print(bao('GET','sys/init')),'verify':verify,'renew-leaves':renew_leaves,'restart':restart_stack}[args.command]() diff --git a/security/OPERATIONS.md b/security/OPERATIONS.md new file mode 100644 index 0000000..feb26f8 --- /dev/null +++ b/security/OPERATIONS.md @@ -0,0 +1,86 @@ +# Запуск и проверка lab7 на 4 + +Нужны Docker Compose и Python 3.12+ у оператора. Из корня репозитория: + +```sh +python -m pip install -r requirements-operator.txt +python scripts/lab7.py bootstrap +python scripts/lab7.py verify +``` + +Bootstrap генерирует CA/leaf и независимые credentials, готовит named volumes, +поднимает PostgreSQL/Redis/S3/OpenBao, выполняет init/unseal, настраивает cert auth, +политики KV, DB grants/S3 policies и запускает приложение. Повторный bootstrap +сохраняет существующие данные и secrets. Результаты и ограничения описаны в REPORT.md. + +API: https://localhost:8443. CA: secrets/ca.crt. Grafana: https://localhost:3443, +логин admin, пароль в secrets/grafana-admin/password. OpenBao: https://127.0.0.1:8200. +Все опубликованные порты привязаны к loopback host. Доступ из браузера требует доверия +локальному CA; тесты передают CA явно и никогда не отключают проверку TLS. + +## Bootstrap trust и renewal + +Оператор создаёт CA private key и хранит его в secrets/operator-private. Каталог secrets +исключён из Git и Docker build context; на Windows bootstrap ограничивает NTFS ACL +текущим пользователем. Не передавать эту папку вместе с проектом. Сервисам монтируется +только их identity, CA public certificate и CRL. Operator/audit инструмент имеет более +широкие права для воспроизводимых отрицательных тестов и не является рабочим сервисом. + +OpenBao использует persistent file storage, не dev-mode. Для одного учебного оператора +init создаёт один unseal share (threshold=1). Он и root token остаются в локальном +operator-private/bao-init.json, не монтируются в OpenBao/API/worker. Это ручной bootstrap, +не auto-unseal. После перезапуска OpenBao: + +```sh +python scripts/lab7.py unseal +``` + +Сервисы используют cert auth, читают только свой KV path, получают token с TTL/maxTTL +60s и повторяют аутентификацию каждые 10s. Token после чтения отзывается; конфигурация +кешируется в памяти не более 60s. При изменении secret supervisor перезапускает child; +при sealed/unavailable OpenBao прекращает его работу после истечения cache. После +unseal повторный cert auth восстанавливает сервис. Ни постоянного SecretID, ни root +токена, ни fallback password в образе приложения нет. + +Leaf действует 24 часа, CA 30 дней. Renewal выполняет оператор до expiry; пример +проверенной ротации LB с отзывом предыдущего serial: + +```sh +python scripts/lab7.py rotate-leaf +python scripts/lab7.py rotate-secret +``` + +Первый вызов заменяет LB leaf, публикует CRL и перезапускает оба API TLS listener и LB, +закрывая старые TLS-сессии/resumption. Второй меняет API DB password, разрывает существующие +DB connections и обновляет KV. Новые секреты подхватываются <=10s. Образы не пересобираются. +Для остальных identities используется renew-leaves; ключ CA переиздаётся отдельно при +истечении 30 дней на новом учебном стенде. Автоматическая PKI/CA rollover — не трек этой работы. + +## Hardening и ограничения + +У всех сервисов read_only, no-new-privileges, cap_drop ALL, CPU/RAM limits и /tmp tmpfs. +API/worker и TLS proxies работают non-root. PostgreSQL стартует entrypoint с CHOWN, +DAC_OVERRIDE/FOWNER/SETUID/SETGID для подготовки volume и приватного server key, затем +переходит в postgres. Stateful volumes остаются writable: это необходимые данные, +а не writable root filesystem. Bootstrap chown выполняется отдельным operator container. + +Приложение слушает только loopback; TLS sidecar делит с ним namespace. При restart +основного контейнера следует restart его sidecar после запуска: это важно для Docker +namespace lifecycle. Полный verify делает это явно. Для полного restart используйте `python scripts/lab7.py restart`: сначала owners, затем TLS sidecars, без гонки network namespaces. TLS1.2 у OpenBao совместим с локальным +Python/OpenSSL; остальной transport допускает TLS1.2/1.3. Проверка CA/SAN везде обязательна. + +Argon2id: m=19456 KiB, t=2, p=1, random salt; старые параметры обновляются после успешного +входа. Измерение времени в evidence/internal.json выполнено в audit-контейнере (0.5 CPU/256MiB); это latency, не гарантия RPS. не более двух hash operations на API +(около 38 MiB под Argon2), не более 32/s на весь стенд и 8/10s на username через общий Redis. +При недоступности Redis вход fail-closed с 503; 429 содержит Retry-After: 1. + +Upload worker: 2 CPU, 2GiB, два subprocess, 768MiB RLIMIT_AS и timeout 60s на задачу. +Изображения только PNG/JPEG, ограничены bytes/pixels; варианты JPEG/WebP. + +## Evidence + +verify выполняет публичные smoke/security, отрицательный TLS/ACL аудит, rehash/expiry, +последовательный отказ обеих API, restart с сохранением sessions/messages/attachments, +ротацию DB password и LB leaf, OpenBao token expiry/seal/unseal, проверку трёх сигналов +и отсутствия секретов в telemetry. Только синтетические данные; секреты не записываются +в evidence. Scan и применимость CVE описаны в SCAN_TRIAGE.md. diff --git a/security/SCAN_TRIAGE.md b/security/SCAN_TRIAGE.md new file mode 100644 index 0000000..9aabdb2 --- /dev/null +++ b/security/SCAN_TRIAGE.md @@ -0,0 +1,38 @@ +# Dependency/image scan и применимость + +Проверен **собранный образ приложения**, включая Debian packages и Python dependencies, +Trivy 0.76.2, vulnerability DB загружена 27.11.2026. Сканер получает docker-save archive, +не Docker socket и не secrets. Полные локальные отчёты: evidence/raw/image-scan.json (до), +evidence/raw/image-scan-updated.json (после). В Git сохранены evidence/scan-findings.csv +со всеми находками повторного scan и evidence/scan-summary.json с итогами до/после. +Это не полный scan всех сторонних инфраструктурных images; их pinned версии перечислены +в compose.yaml. Не заявляется отсутствие CVE или промышленная готовность. + +Воспроизведение из PowerShell, путь к archive можно выбрать локально: + +```powershell +docker save -o C:\vnp\lab7-app-scan.tar mtusi2026lab7-api:local +New-Item -ItemType Directory -Force evidence/raw +docker run --rm --cap-drop ALL --security-opt no-new-privileges -v C:\vnp\lab7-app-scan.tar:/scan/image.tar:ro -v C:\vnp\mtusi2026lab7\evidence\raw:/out -v lab7_trivy_cache:/root/.cache aquasec/trivy:0.76.2 image --input /scan/image.tar --scanners vuln --format json --output /out/image-scan-updated.json --quiet +``` + +| Finding | Реальная применимость | Решение / оставшийся риск | +| --- | --- | --- | +| Pillow 12.0.0, в т.ч. CVE-2026-112403 JPEG decode и семейство CVE-2026-11239x/11240x | JPEG/PNG из пользовательских uploads реально декодируются API и worker; просто лимит размера не устраняет memory corruption | Обновлён до 13.0.0; повторены smoke/варианты. Python-dependency CRITICAL: 5 → 0 | +| Старая базовая ОС/Python 3.12.8 | TLS, standard library и native dependencies реально используются | База обновлена до python:3.12.16-slim-bookworm. Debian CRITICAL 9 → 2, HIGH 145 → 100; это не доказательство неприменимости остальных | +| OpenTelemetry API CVE-2026-114603, CVE-2026-126360 | Наш TraceContextTextMapPropagator принимает HTTP и JSON-carrier; regex DoS был достижим | Перед extract ограничены traceparent ровно 55 символами и tracestate 512 символами, остальные поля отброшены. Применено и к worker/dispatcher. Сканер всё ещё видит старую версию; это локальная mitigation, не исправление зависимости upstream | +| Starlette CVE-2025-62727 Range merging | Требует FileResponse; приложение использует StreamingResponse без Range processing | Уязвимая ветка не вызывается. При добавлении FileResponse потребуется обновить совместимые FastAPI/Starlette | +| Starlette CVE-2026-48818 Windows StaticFiles/UNC | Runtime Linux, StaticFiles не используется | Неприменимо к текущим маршрутам | +| Starlette CVE-2025-54121/CVE-2026-54283 multipart/form parsing | request.form(), multipart и urlencoded не используются; JSON/raw upload имеют собственные byte limits | Неприменимо к текущему input path; добавление forms требует обновления | +| Остальные Starlette path/Host/method findings | Приложение не использует Host для authorization; FastAPI routing, UUID validation и DB ACL остаются обязательными | Публичный smoke/ACL проверяют контракт, но это не полное доказательство для произвольного HTTP parser attack; остаточный риск принят в учебной модели | +| pip 25.0.1 installation findings | В рабочем контейнере packages не устанавливаются: non-root/read_only/no network egress; установка только на build с pinned direct dependencies | Runtime path отсутствует; supply-chain риск сборки остаётся, transitive packages не hash-locked | +| libsqlite3-0 CVE-2025-7458, CRITICAL | Приложение использует PostgreSQL; SQLite API не вызывается | Пакет присутствует в base image, опасный SQL path приложением не экспонирован | +| zlib1g CVE-2023-45853, CRITICAL | Finding относится к minizip zipOpenNewFileInZip4_6, не к обычному zlib inflate | Приложение ZIP/minizip не создаёт; не считать весь zlib безопасным по одному этому выводу | +| PAM CVE-2025-6020, HIGH с доступным исправлением | Локальный PAM login/pam_namespace не используется, shell login не публикуется; app non-root без caps | Не достигается бизнес-API; исправление пакета необходимо при расширении модели до локального login | +| Kerberos libraries и остальные Debian findings | DB auth SCRAM, не GSSAPI/Kerberos; util-linux/mount не вызываются приложением; app без capabilities | Все находки сохранены в CSV. Для libc/OpenSSL и других используемых библиотек нельзя объявлять blanket false-positive: остаточный риск base image, нужен отдельный upstream patch review перед production | + +Принимается только учебный стенд с доверенным оператором/host, закрытыми внутренними +портами и ограниченными ресурсами. Исходные CVE, versions, fixed version и ссылки на +advisory сохранены построчно в CSV: неподтверждённые находки не скрыты allowlist-файлом. +Документация сканирования: https://trivy.dev/docs/v0.68/guide/target/container_image/. +Релиз исправленного Pillow: https://pypi.org/project/pillow/13.0.0/. diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..04ebe0e 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,26 @@ -# Модель угроз — заполнить +# Модель угроз учебного стенда -## Активы и акторы +Активы: пароли и сессии, сообщения и вложения, очередь обработки, service credentials, +CA/ключи и telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, +скомпрометированный сервис и оператор Docker-host. Оператор и host доверенные. +Один host не защищён от собственной компрометации или потери. Ключ CA и unseal material +не монтируются в рабочие контейнеры. Сетевые границы: [матрица](../contracts/trust-matrix.md). -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +| Путь атаки | Инвариант и контроль | Отрицательная проверка | Остаточное ограничение | +| --- | --- | --- | --- | +| Eve читает metadata/content Alice или прикрепляет файл другого чата | Bearer + членство в PostgreSQL, 404 | smoke и lifecycle cross-chat | Администратор БД доверенный | +| Подстановка X-User-Id | Header не определяет пользователя | smoke | Украденный Bearer действует до logout/expiry | +| Обход LB прямым вызовом API | Loopback приложения, mTLS CN=lb и CRL | internal: no cert, foreign, outsider, expired, old-lb и plaintext bypass | Root host может войти в namespace | +| Worker публикует поддельные задания | mTLS identity + отдельные Redis producer/consumer ACL | internal: worker/API XADD и dispatcher XREADGROUP запрещены | Worker имеет права на рабочую очередь | +| Worker читает password hashes или получает admin secrets | DB grants, S3 prefix policies, scoped KV paths | internal: SELECT users, DDL, чужой KV, policy write, PutObject запрещены | Нет построчной изоляции задач worker | +| Login DoS на двух репликах | Redis: 32/s глобально, 8/10s на username; 2 hash slots/API | internal: две реплики, 429/Retry-After, измерение Argon2 | Атакующий может исчерпать общий бюджет и задержать законный вход | +| Подмена сервера зависимости | CA + hostname, verify-full, без plaintext fallback | internal: неверный hostname, TLS и закрытые plaintext ports | Локальный hop доверяет процессам одного namespace | +| Grafana пытается писать telemetry | mTLS CN grafana, GET/HEAD и POST только query/query_range/series Prometheus; отдельный ingest Collector | lifecycle: POST denied | Grafana вправе читать диагностику | +| Повторное использование старого secret/cert | Смена DB password с разрывом сессий, CRL + restart listeners | lifecycle: старые credentials отклонены на новых соединениях | Краткий перерыв при ротации допустим | +| OpenBao sealed, недоступен или token истёк | Token TTL 60s, cert auth каждые 10s, остановка child после 60s без secrets | lifecycle: expiry/seal/unseal | Restart OpenBao требует operator unseal | +| Изображение расходует CPU/RAM | Worker 2 CPU/2GiB, 2 subprocess, 768MiB address space и 60s на задачу, bytes/pixels limits | Compose, image_processor/worker, smoke обработки | Image decoder остаётся attack surface; Pillow обновлён после scan | +| Credentials попадают в error/log/trace | Технический allowlist, SQL hide_parameters, общие API errors | lifecycle: поиск реальных synthetic canaries/service secrets в logs/Loki/Tempo | Оператор может прочитать память процесса | -## Границы доверия - -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. - -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | -| --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | - -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. - -## Lifecycle и инциденты - -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +Bootstrap/renewal и исключения hardening: [OPERATIONS.md](OPERATIONS.md). +Результаты — в evidence, применимость CVE — в SCAN_TRIAGE.md. Это учебная модель, +а не заявление о промышленной готовности. diff --git a/src/auth.py b/src/auth.py index ab93a9f..568b8c8 100644 --- a/src/auth.py +++ b/src/auth.py @@ -3,6 +3,7 @@ import json import os import re import secrets +from threading import BoundedSemaphore from datetime import datetime, timedelta, timezone from argon2 import PasswordHasher @@ -11,7 +12,28 @@ from redis import Redis from .errors import APIError -password_hasher = PasswordHasher() +hash_slots = BoundedSemaphore(2) + + +class BoundedHasher(PasswordHasher): + def hash(self, password, **kwargs): + if not hash_slots.acquire(blocking=False): + raise APIError(429, 'rate_limited', 'Повторите попытку позже') + try: + return super().hash(password, **kwargs) + finally: + hash_slots.release() + + def verify(self, encoded, password): + if not hash_slots.acquire(blocking=False): + raise APIError(429, 'rate_limited', 'Повторите попытку позже') + try: + return super().verify(encoded, password) + finally: + hash_slots.release() + + +password_hasher = BoundedHasher(time_cost=2, memory_cost=19456, parallelism=1) dummy_hash = password_hasher.hash(secrets.token_urlsafe(32)) @@ -32,6 +54,7 @@ class Sessions: os.getenv('REDIS_URL', 'redis://redis:6379/0'), decode_responses=True, socket_connect_timeout=1, socket_timeout=1, max_connections=20, retry_on_timeout=False, + ssl_ca_certs='/run/identity/ca.crt', ssl_check_hostname=True, ) self.ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600')) if self.ttl < 1: @@ -66,3 +89,18 @@ class Sessions: sessions = Sessions() + + +def password_budget(subject): + """Atomic, shared fixed windows before any expensive hash (including registration).""" + digest = hashlib.sha256(subject.encode()).hexdigest() + allowed = sessions.client.eval(''' + local global = redis.call('INCR', KEYS[1]) + if global == 1 then redis.call('EXPIRE', KEYS[1], 1) end + local account = redis.call('INCR', KEYS[2]) + if account == 1 then redis.call('EXPIRE', KEYS[2], 10) end + if global > 32 or account > 8 then return 0 end + return 1 + ''', 2, 'login:global', 'login:' + digest) + if not allowed: + raise APIError(429, 'rate_limited', 'Повторите попытку позже') diff --git a/src/image_processor.py b/src/image_processor.py index 8533d88..fadf1b2 100644 --- a/src/image_processor.py +++ b/src/image_processor.py @@ -102,7 +102,7 @@ def main(): otel.setup(child=True) engine = create_db_engine() try: - with otel.span('image.process', context=otel.propagator.extract({ + with otel.span('image.process', context=otel.extract({ 'traceparent': os.getenv('TRACEPARENT', ''), 'tracestate': os.getenv('TRACESTATE', '')})): process(sessionmaker(engine, expire_on_commit=False), sys.argv[1], sys.argv[2]) otel.event('image_completed') diff --git a/src/jobs.py b/src/jobs.py index 0757b2c..315cf13 100644 --- a/src/jobs.py +++ b/src/jobs.py @@ -32,7 +32,9 @@ def now(): def broker(): return Redis.from_url(os.getenv('BROKER_URL', 'redis://broker:6379/0'), - decode_responses=True, socket_connect_timeout=2, socket_timeout=5) + decode_responses=True, socket_connect_timeout=2, socket_timeout=5, + ssl_ca_certs='/run/identity/ca.crt', ssl_check_hostname=True, + ssl_certfile='/run/identity/tls.crt', ssl_keyfile='/run/identity/tls.key') def ensure_group(client): @@ -83,7 +85,7 @@ def dispatch_once(sessions, client): continue if job.published_at is None: with otel.span('attachment-jobs publish', kind=otel.SpanKind.PRODUCER, - context=otel.propagator.extract(job.trace_context), attributes={ + context=otel.extract(job.trace_context), attributes={ 'messaging.system': 'redis', 'messaging.destination.name': STREAM, 'messaging.operation.type': 'publish', 'job.attempt': job.attempt + 1}): client.xadd(STREAM, {'job': json.dumps({**envelope(job), **otel.carrier()})}) diff --git a/src/object_storage.py b/src/object_storage.py index 924a837..f7d071e 100644 --- a/src/object_storage.py +++ b/src/object_storage.py @@ -16,6 +16,7 @@ def s3_client(): region_name=os.getenv('S3_REGION', 'us-east-1'), aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'], + verify='/run/identity/ca.crt', config=Config(connect_timeout=2, read_timeout=5, retries={'total_max_attempts': 1}, s3={'addressing_style': 'path'}, diff --git a/src/secure_run.py b/src/secure_run.py new file mode 100644 index 0000000..8898b49 --- /dev/null +++ b/src/secure_run.py @@ -0,0 +1,82 @@ +"""Cert-auth OpenBao supervisor. Secrets stay in memory; fail closed at lease expiry.""" +import json +import os +import signal +import subprocess +import sys +import time + +import requests + + +def main(): + role = os.environ['SERVICE_ROLE'] + client = requests.Session() + client.trust_env = False + client.verify = '/run/identity/ca.crt' + client.cert = ('/run/identity/tls.crt', '/run/identity/tls.key') + child = None + stopping = False + token = None + deadline = 0 + current = None + + def stop(*_): + nonlocal stopping + stopping = True + + def stop_child(): + nonlocal child + if child is not None: + if child.poll() is not None: + child = None + return + os.killpg(child.pid, signal.SIGTERM) + try: + child.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(child.pid, signal.SIGKILL) + child.wait() + child = None + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + while not stopping: + try: + # Fresh cert authentication bounds revocation; no permanent bootstrap password. + response = client.post('https://openbao:8200/v1/auth/cert/login', + json={'name': role}, timeout=3) + response.raise_for_status() + auth = response.json()['auth'] + token = auth['client_token'] + response = client.get(f'https://openbao:8200/v1/secret/data/{role}', + headers={'X-Vault-Token': token}, timeout=3) + response.raise_for_status() + config = response.json()['data']['data'] + deadline = time.monotonic() + min(auth['lease_duration'], 60) + if config != current: + stop_child() + current = config + if child is None: + child = subprocess.Popen(sys.argv[1:], env={**os.environ, **config}, start_new_session=True) + print('Service started with scoped secrets', flush=True) + # Each poll uses a new short lease; revoke the used token to avoid accumulation. + client.post('https://openbao:8200/v1/auth/token/revoke-self', + headers={'X-Vault-Token': token}, timeout=3) + except (requests.RequestException, KeyError, ValueError): + print('Secrets temporarily unavailable', flush=True) + if time.monotonic() >= deadline: + stop_child() + current = None + if child is not None and child.poll() is not None: + return child.returncode + for _ in range(10): + if stopping: + break + time.sleep(1) + stop_child() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/store.py b/src/store.py index b273f4c..f91c9ec 100644 --- a/src/store.py +++ b/src/store.py @@ -7,7 +7,7 @@ from uuid import UUID from sqlalchemy import select, tuple_, update from sqlalchemy.exc import IntegrityError -from .auth import password_hasher, verify_password, unauthorized +from .auth import password_hasher, verify_password, unauthorized, password_budget from .errors import APIError from .cache import history_cache from .models import User, Chat, ChatMember, Message, IdempotencyRecord, Attachment @@ -57,6 +57,7 @@ class PostgresStore: self.cache = cache def create_user(self, username, display_name, password): + password_budget(username) user = User(username=username, display_name=display_name, password_hash=password_hasher.hash(password)) try: with self.sessions.begin() as session: @@ -74,12 +75,18 @@ class PostgresStore: return serialize(session.get(User, ensure_uuid(user_id)), *USER_FIELDS) def login(self, username, password): + password_budget(username) with self.sessions() as session: user = session.scalar(select(User).where(User.username == username)) encoded = user.password_hash if user else None result = serialize(user, *USER_FIELDS) if not verify_password(encoded, password): raise unauthorized() + if password_hasher.check_needs_rehash(encoded): + replacement = password_hasher.hash(password) + with self.sessions.begin() as session: + session.execute(update(User).where(User.id == result['id'], User.password_hash == encoded) + .values(password_hash=replacement)) return result def create_chat(self, actor_id, title, member_ids): diff --git a/src/telemetry.py b/src/telemetry.py index bc285bf..7382ea0 100644 --- a/src/telemetry.py +++ b/src/telemetry.py @@ -136,6 +136,14 @@ def seed_http(routes): http_requests.add(0, {'method': method, 'route': route.path, 'status_class': status}) +def extract(carrier): + # Bound regex work in both HTTP headers and JSON broker carriers (CVE-2026-114603/126360). + bounded = {key: value for key, value in carrier.items() if isinstance(value, str) + and ((key == 'traceparent' and len(value) == 55) + or (key == 'tracestate' and len(value) <= 512))} + return propagator.extract(bounded) + + def carrier(): result = {} propagator.inject(result) @@ -174,11 +182,12 @@ class HttpTelemetry: if scope['type'] != 'http' or scope['path'].startswith('/health/'): return await self.app(scope, receive, send) headers = {k.decode('latin1'): v.decode('latin1') for k, v in scope['headers'] - if k in (b'traceparent', b'tracestate')} + if (k == b'traceparent' and len(v) == 55) + or (k == b'tracestate' and len(v) <= 512)} method = scope['method'] if scope['method'] in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'} else 'OTHER' status = 500 started = time.monotonic() - with span('HTTP ' + method, kind=SpanKind.SERVER, context=propagator.extract(headers)) as current: + with span('HTTP ' + method, kind=SpanKind.SERVER, context=extract(headers)) as current: async def response(message): nonlocal status if message['type'] == 'http.response.start': diff --git a/src/worker.py b/src/worker.py index 118c885..b28ce9b 100644 --- a/src/worker.py +++ b/src/worker.py @@ -26,7 +26,7 @@ def handle(sessions, client, message_id, fields): acknowledge(client, message_id) return with otel.span('attachment-jobs process', kind=otel.SpanKind.CONSUMER, - context=otel.propagator.extract(message), attributes={ + context=otel.extract(message), attributes={ 'messaging.system': 'redis', 'messaging.destination.name': STREAM, 'messaging.operation.type': 'process', 'job.attempt': message.get('attempt', 0)}): process_message(sessions, client, message_id, message) diff --git a/student-tests/internal.py b/student-tests/internal.py new file mode 100644 index 0000000..ebab6f5 --- /dev/null +++ b/student-tests/internal.py @@ -0,0 +1,185 @@ +"""Operator-only, real network negative tests; no credentials in result files.""" +import base64 +import hashlib +import json +import resource +from pathlib import Path +import socket +import ssl +import statistics +import sys +import time +import uuid + +import boto3 +from botocore.exceptions import ClientError +import psycopg +from redis import Redis +from redis.exceptions import ResponseError +import requests +from argon2 import PasswordHasher + +S=Path('/audit-secrets') +sys.path.insert(0, '/app') +CA=str(S/'ca.crt') +config=json.loads((S/'operator-private/credentials.json').read_text()) +results=[] + + +def record(name, condition=True, **details): + assert condition, name + results.append({'test':name,'passed':True,**details}) + print('PASS: '+name,flush=True) + + +def http(method,url,role=None,**kw): + client=requests.Session();client.trust_env=False + cert=(str(S/role/'tls.crt'),str(S/role/'tls.key')) if role else None + return client.request(method,url,verify=CA,cert=cert,timeout=8,**kw) + + +def tls(host,port,identity,body,hostname=None): + ctx=ssl.create_default_context(cafile=CA) + if identity: ctx.load_cert_chain(str(S/identity/'tls.crt'),str(S/identity/'tls.key')) + with socket.create_connection((host,port),timeout=3) as raw: + with ctx.wrap_socket(raw,server_hostname=hostname or host) as conn: + conn.sendall(body) + return conn.recv(8192) + + +def rejection(host,port,identity,body): + try: response=tls(host,port,identity,body) + except (ssl.SSLError,ConnectionResetError): response=b'' + # Timeouts/refused connections are NOT accepted as proof of authorization denial. + return not response + + +def db(role): + return psycopg.connect(host='postgres',dbname='messenger',user=role,password=config[role]['db'], + sslmode='verify-full',sslrootcert=CA,connect_timeout=3,autocommit=True) + + +def redis(role,broker=False): + return Redis(host='broker' if broker else 'redis',port=6380,username=role, + password=config[role]['broker' if broker else 'redis'],ssl=True,ssl_ca_certs=CA, + ssl_check_hostname=True,ssl_certfile=str(S/role/'tls.crt') if broker else None, + ssl_keyfile=str(S/role/'tls.key') if broker else None,decode_responses=True, + socket_timeout=3,socket_connect_timeout=3) + + +def main(): + from src.telemetry import extract, trace + start=time.perf_counter() + for _ in range(20): + extract({'traceparent':'00-'+' '*100000+'\n','tracestate':' '*100000+'x'}) + record('Oversized HTTP/JSON trace context has bounded parsing cost',time.perf_counter()-start<1) + context=extract({'traceparent':'00-'+'1'*32+'-'+'2'*16+'-01'}) + record('Valid trace context remains supported',trace.get_current_span(context).get_span_context().is_valid) + body=b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' + ingest=b'POST /v1/traces HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}' + matrix=[('api1',8443,'lb',body),('api2',8443,'lb',body), + ('broker',6380,'worker',b'*1\r\n$4\r\nPING\r\n'),('otel-collector',44318,'api',ingest)] + for host,port,allowed,payload in matrix: + record(host+' accepts allowed identity',bool(tls(host,port,allowed,payload))) + for forbidden in [None,'foreign-'+allowed,'outsider','expired-'+allowed]: + record(host+' rejects '+str(forbidden),rejection(host,port,forbidden,payload)) + if host.startswith('api') and (S/'old-lb/tls.crt').exists(): + record(host+' rejects revoked LB serial',rejection(host,port,'old-lb',payload)) + for role in ['worker','dispatcher']: + record('Collector accepts '+role,b'200' in tls('otel-collector',44318,role,ingest)) + for host,port in [('lb',8443),('redis',6380),('s3',9443),('grafana',3443),('openbao',8200)]: + ctx=ssl.create_default_context(cafile=CA) + with socket.create_connection((host,port),timeout=3) as raw: + with ctx.wrap_socket(raw,server_hostname=host) as conn: + record(host+' server TLS verified',True,protocol=conn.version()) + try: tls(host,port,None,b'GET / HTTP/1.0\r\n\r\n',hostname='wrong.invalid') + except ssl.SSLCertVerificationError: record(host+' rejects wrong hostname') + else: raise AssertionError('hostname accepted') + for host,port,local,role,path in [('prometheus',19090,9090,'grafana','/-/ready'), + ('loki',13100,3100,'grafana','/ready'),('tempo',13200,3200,'grafana','/ready'), + ('otel-collector',18889,8889,'prometheus','/metrics'),('otel-collector',18888,8888,'prometheus','/metrics'), + ('tempo',14318,4318,'otel-collector','/v1/traces')]: + payload=(f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n').encode() + record(f'{host}:{port} trusted identity',bool(tls(host,port,role,payload))) + record(f'{host}:{port} rejects outsider',rejection(host,port,'outsider',payload)) + for host,port in [('api1',8080),('api2',8080),('broker',6379),('redis',6379),('s3',9000), + ('otel-collector',4318),('otel-collector',8888),('otel-collector',8889), + ('prometheus',9090),('loki',3100),('loki',9095),('tempo',3200),('tempo',4318),('tempo',9095),('grafana',3000)]: + try: + with socket.create_connection((host,port),timeout=2): pass + except ConnectionRefusedError: record(f'No plaintext bypass {host}:{port}') + else: raise AssertionError('plaintext listener exposed') + for role in ['api','worker','dispatcher','cleanup']: + with db(role) as conn: + record('PostgreSQL TLS '+role,conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]) + try: conn.execute('CREATE TABLE forbidden_probe(id int)') + except psycopg.errors.InsufficientPrivilege: record('DB no DDL '+role) + else: raise AssertionError('DDL allowed') + if role!='api': + try: conn.execute('SELECT password_hash FROM users LIMIT 1') + except psycopg.errors.InsufficientPrivilege: record('DB password hashes denied '+role) + else: raise AssertionError('password hashes exposed') + auth=http('POST','https://openbao:8200/v1/auth/cert/login',role,json={'name':role}) + record('OpenBao cert auth '+role,auth.status_code==200) + token=auth.json()['auth']['client_token'];headers={'X-Vault-Token':token} + record('OpenBao short TTL '+role,0'},count=1))]: + client=redis(role,True);record('Broker authenticated '+role,client.ping()) + try:cmd(client) + except ResponseError as exc: record('Broker ACL denied '+role,'permissions' in str(exc).lower() or 'noperm' in str(exc).lower()) + else:raise AssertionError('broker command allowed') + for role,prefix in [('api','variants'),('worker','staging'),('cleanup','staging')]: + client=boto3.client('s3',endpoint_url='https://s3:9443',verify=CA, + aws_access_key_id=role,aws_secret_access_key=config[role]['s3'],region_name='us-east-1') + try:client.put_object(Bucket='messenger-attachments',Key=prefix+'/forbidden',Body=b'x') + except ClientError as exc:record('S3 denied write prefix '+role,exc.response['Error']['Code']=='AccessDenied') + else:raise AssertionError('S3 write allowed') + # Real rehash via the public API and a synthetic old Argon2id record. + username='rehash_'+uuid.uuid4().hex[:12];password='synthetic-'+uuid.uuid4().hex + old=PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(password) + user_id=str(uuid.uuid4()) + with db('api') as conn: + conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',(user_id,username,'Rehash test',old)) + response=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,password)) + record('Old Argon2 login succeeds',response.status_code==201) + token=response.json()['token'] + with db('api') as conn: + encoded=conn.execute('SELECT password_hash FROM users WHERE id=%s',(user_id,)).fetchone()[0] + record('Password rehashed',encoded.startswith('$argon2id$v=19$m=19456,t=2,p=1$')) + client=redis('api');key='session:'+hashlib.sha256(token.encode()).hexdigest() + stored=client.get(key) + record('Session stores digest key, no credential',stored is not None and token not in stored and password not in stored) + client.expire(key,1);time.sleep(1.1) + record('Expired session rejected',http('GET','https://lb:8443/api/v1/users/me',headers={'Authorization':'Bearer '+token}).status_code==401) + # Same account alternates replicas. Eight accepted attempts total, not per replica. + username='missing_'+uuid.uuid4().hex[:12];statuses=[];instances=set() + for _ in range(12): + r=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,'synthetic-password')) + statuses.append(r.status_code);instances.add(r.headers.get('X-Instance-Id')) + if r.status_code==429:record('Rate limit carries Retry-After',r.headers.get('Retry-After')=='1') + record('Rate limit shared across replicas',statuses.count(401)==8 and statuses.count(429)==4 and len(instances)==2,instances=len(instances),statuses=statuses) + samples=[];hasher=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1) + hasher.verify(encoded,password) # One warmup; sequential measurements, no HTTP load. + wall_start=time.perf_counter();cpu_start=time.process_time() + for _ in range(20): + start=time.perf_counter();hasher.verify(encoded,password);samples.append(time.perf_counter()-start) + record('Measured Argon2 budget',True,memory_kib=19456,time_cost=2,parallelism=1, + median_ms=round(statistics.median(samples)*1000,2),p95_ms=round(sorted(samples)[18]*1000,2), + p99_ms=round(max(samples)*1000,2),samples_ms=[round(s*1000,3) for s in samples], + duration_seconds=round(time.perf_counter()-wall_start,3), + cpu_seconds=round(time.process_time()-cpu_start,3), + process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + global_limit_per_second=32,account_limit_per_10seconds=8,hash_concurrency_per_api=2) + # Every secret is checked as a value, but never serialized in evidence. + (Path('/evidence')/'internal.json').write_text(json.dumps({'checks':results},indent=2)) + print(f'PASS: {len(results)} internal checks') + + +if __name__=='__main__':main() diff --git a/student-tests/lifecycle.py b/student-tests/lifecycle.py new file mode 100644 index 0000000..53c78c1 --- /dev/null +++ b/student-tests/lifecycle.py @@ -0,0 +1,127 @@ +"""Operator-driven lifecycle tests. Synthetic data; volumes are never deleted.""" +import hashlib +import json +import sys +import time +from pathlib import Path + +ROOT=Path(__file__).resolve().parents[1] +sys.path[:0]=[str(ROOT),str(ROOT/'tests')] +from scripts import lab7 as op +from client import Client + + +def main(): + evidence=ROOT/'evidence';evidence.mkdir(exist_ok=True) + checks=[] + def ok(name,condition=True,**details): + assert condition,name + checks.append({'test':name,'passed':True,**details});print('PASS: '+name,flush=True) + (evidence/'lifecycle.json').write_text(json.dumps(checks,indent=2),encoding='utf-8') + def audit(code): + return op.compose('run','--rm','--no-deps','-T','audit','-',data=code).stdout + def ready(): + try:return c.call('GET','/health/ready',schema='Health')['status']==200 + except Exception:return False + def saved(): + c.call('GET','/api/v1/users/me',actor=alice,schema='User') + history=c.call('GET',f"/api/v1/chats/{chat['id']}/messages?limit=100",actor=bob,schema='MessagePage')['json']['items'] + assert original in history + content=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content",actor=bob)['bytes'] + assert content==blob + thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes'] + assert thumbnail==original_thumbnail + c=Client('https://127.0.0.1:8443',str(ROOT/'secrets/ca.crt'),timeout=5) + alice,bob,eve,chat=c.bootstrap() + canary='private-message-'+hashlib.sha256(alice['token'].encode()).hexdigest() + original=c.message(alice,chat,canary)['json'] + attachment,blob=c.attachment(alice,chat);c.wait_ready(alice,attachment) + original_thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes'] + foreign=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other chat','member_ids':[eve['id']]},schema='Chat')['json'] + c.call('POST',f"/api/v1/chats/{foreign['id']}/messages",404,actor=eve, + body={'text':'','attachment_ids':[attachment['id']]},headers={'Idempotency-Key':'cross-chat-probe'}) + ok('Cannot attach another chat file') + c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'}) + ok('Request size is bounded') + ids={name:op.compose('exec','-T',name,'hostname').stdout.strip() for name in ['api1','api2']} + for target in ['api1','api2']: + op.compose('stop',target) + start=time.monotonic() + try: + successes=0;failures=0 + while successes<5: + try: + response=c.call('GET','/api/v1/users/me',actor=alice) + assert response['headers']['X-Instance-Id']!=ids[target] + successes+=1 + except Exception: + failures+=1;successes=0 + assert time.monotonic()-start<10,'failover did not recover within 10s' + saved() + ok('Replica failover '+target,recovery_seconds=round(time.monotonic()-start,2),failed_attempts=failures) + finally: + op.compose('start',target);op.compose('restart',target+'-tls') + time.sleep(12) + # Restart the complete stack, including sealed persistent OpenBao. + op.restart_stack() + op.wait_service(ready,90);saved() + ok('Full restart preserves sessions, messages, original and processed attachment') + old=json.loads((op.PRIVATE/'credentials.json').read_text())['api']['db'] + image_before=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip() + op.rotate_secret();time.sleep(12);op.wait_service(ready,30) + code="""import psycopg +try: + psycopg.connect(host='postgres',dbname='messenger',user='api',password=OLD,sslmode='verify-full',sslrootcert='/audit-secrets/ca.crt',connect_timeout=3) +except psycopg.OperationalError as e: + assert 'password authentication failed' in str(e) + print('old DB password rejected') +else:raise AssertionError('old DB password accepted') +""".replace('password=OLD','password='+repr(old)) + audit(code);saved();ok('Working DB secret rotated; old password rejected on new connection') + op.rotate_leaf();op.wait_service(ready,30);saved() + output=op.compose('run','--rm','--no-deps','audit','/audit/internal.py').stdout + (evidence/'internal.txt').write_text(output,encoding='utf-8') + ok('Leaf rotated and old LB identity revoked on both replicas') + image_after=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip() + ok('Rotations do not rebuild image',image_before==image_after,image=image_after) + # Obtain a real scoped token, let it expire, then demonstrate sealed fail-closed. + auth=op.bao('POST','auth/cert/login',{'name':'api'},role='api')['auth'] + started=time.monotonic() + time.sleep(auth['lease_duration']+2) + try:op.bao('GET','secret/data/api',token=auth['client_token'],role='api') + except RuntimeError as exc:ok('Expired OpenBao token denied','HTTP 403' in str(exc)) + else:raise AssertionError('expired token accepted') + admin=json.loads((op.PRIVATE/'bao-init.json').read_text())['root_token'] + op.bao('PUT','sys/seal',token=admin) + started=time.monotonic() + try: + time.sleep(70) + ok('Sealed OpenBao stops API within bounded secret cache',not ready(),elapsed_seconds=round(time.monotonic()-started,2)) + for name in ['worker','dispatcher','cleanup']: + code="import pathlib; x=[p.read_bytes() for p in pathlib.Path('/proc').glob('[0-9]*/cmdline')]; assert not any(b'python\\x00-m\\x00src.' in v and b'src.secure_run' not in v for v in x)" + op.compose('exec','-T',name,'python','-c',code) + ok('Sealed OpenBao stops background consumers too') + finally: + op.unseal() + op.wait_service(ready,45);saved();ok('Unseal recovers without baked-in fallback secret') + # Public API errors and telemetry must not contain actual secrets or canaries. + credentials=json.loads((op.PRIVATE/'credentials.json').read_text()) + values=[v for role in credentials.values() for v in role.values()] + values += [alice['token'],alice['registration']['password'],canary] + logs=op.compose('logs','--no-color','--since','30m','api1','api2','worker','dispatcher','cleanup','otel-collector','loki','tempo').stdout + ok('Container logs do not expose credentials or private message',not any(v in logs for v in values)) + telemetry_code="import sys; sys.path.insert(0,'/audit'); from telemetry import check; check("+repr(values)+")" + print(audit(telemetry_code),flush=True);ok('Live metrics/logs/traces have no credential leaks; datasource writes denied') + deployed=json.loads(op.compose('config','--format','json').stdout)['services'] + for name,spec in deployed.items(): + assert spec['read_only'] and 'ALL' in spec['cap_drop'] and 'no-new-privileges:true' in spec['security_opt'] + assert spec.get('mem_limit') and spec.get('cpus') + ok('All services have read_only, no-new-privileges, cap_drop and limits') + hardware=json.loads(op.docker('info','--format','{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"os":{{json .OperatingSystem}},"architecture":{{json .Architecture}}}').stdout) + hardware['app_image']=image_after + hardware['services']={name:{key:spec.get(key) for key in ['image','cpus','mem_limit','user','read_only','cap_drop','cap_add','security_opt']} for name,spec in deployed.items()} + (evidence/'environment.json').write_text(json.dumps(hardware,indent=2),encoding='utf-8') + ok('Complete lifecycle suite') + + +if __name__=='__main__':main() diff --git a/student-tests/telemetry.py b/student-tests/telemetry.py new file mode 100644 index 0000000..fe3abb0 --- /dev/null +++ b/student-tests/telemetry.py @@ -0,0 +1,47 @@ +"""Verify live encrypted telemetry paths and inspect content without printing it.""" +import json +import time +from pathlib import Path +from internal import http, config, S + + +def check(needles=()): + deadline=time.monotonic()+30 + while True: + bodies=[] + for url,params in [ + ('https://prometheus:19090/api/v1/query',{'query':'http_requests_total'}), + ('https://loki:13100/loki/api/v1/query_range',{'query':'{service_name=~"messenger-.*"}','limit':1000}), + ('https://tempo:13200/api/search',{'limit':100})]: + r=http('GET',url,'operator',params=params) + assert r.status_code==200, f'{url}: HTTP {r.status_code}' + bodies.append(r.text) + metrics=json.loads(bodies[0])['data']['result'] + logs=json.loads(bodies[1])['data']['result'] + traces=json.loads(bodies[2]).get('traces',[]) + if (metrics and logs and traces) or time.monotonic()>=deadline: break + time.sleep(1) + assert metrics and logs and traces, f'Signal counts: metrics={len(metrics)}, logs={len(logs)}, traces={len(traces)}' + for trace in traces[:20]: + r=http('GET','https://tempo:13200/api/traces/'+trace['traceID'],'operator') + assert r.status_code==200 + bodies.append(r.text) + values=list(needles)+[v for role in config.values() for v in role.values()] + assert not any(value in body for value in values for body in bodies),'Telemetry credential/private-message leak' + for host,port,path in [('loki',13100,'/otlp/v1/logs'),('prometheus',19090,'/api/v1/write'),('tempo',13200,'/anything')]: + assert http('POST',f'https://{host}:{port}{path}','grafana',json={}).status_code==403 + password=(S/'grafana-admin/password').read_text() + for name in ['prometheus','loki','tempo']: + path=(f'/api/datasources/uid/{name}/health' if name!='tempo' + else '/api/datasources/proxy/uid/tempo/api/search?limit=1') + response=http('GET','https://grafana:3443'+path, + auth=('admin',password)) + assert response.status_code==200, f'Grafana datasource {name}: HTTP {response.status_code}' + result={'metric_series':len(metrics),'log_streams':len(logs),'trace_results':len(traces), + 'checked_trace_bodies':min(20,len(traces)),'credential_canaries_absent':True, + 'grafana_write_denied':True,'grafana_datasource_health':True} + Path('/evidence/telemetry.json').write_text(json.dumps(result,indent=2)) + print('PASS: live metrics/logs/traces; no credential/message leaks; Grafana read-only TLS sources') + + +if __name__=='__main__':check()