Проверка rehash, login DoS и общего rate limit
This commit is contained in:
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security test-session-expiry test-mtls
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security test-session-expiry test-mtls test-login-dos test-credential-storage
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -35,5 +35,12 @@ test-security:
|
||||
test-session-expiry:
|
||||
$(PYTHON) tests/session_expiry.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
LOGIN_DOS_ARGS ?= --source-budget
|
||||
test-login-dos:
|
||||
$(PYTHON) tests/login_dos.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(LOGIN_DOS_ARGS)
|
||||
|
||||
test-credential-storage:
|
||||
$(PYTHON) tests/credential_storage.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-mtls:
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-mtls.ps1
|
||||
|
||||
@@ -109,7 +109,7 @@ docker compose --env-file .env up -d --build
|
||||
# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md.
|
||||
```
|
||||
|
||||
Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет внешний TLS trust, ACL, upload/session/login limits и logout; `make test-session-expiry` управляемо истекает одну синтетическую сессию локального Compose-стенда и подтверждает `401`. Внутренние отрицательные тесты реализованы отдельно по [trust matrix](contracts/trust-matrix.md).
|
||||
Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет внешний TLS trust, ACL, upload/session/login limits и logout; `make test-session-expiry` управляемо истекает одну синтетическую сессию локального Compose-стенда и подтверждает `401`. `make test-login-dos` измеряет общий Redis-бюджет login DoS и распределение попыток по репликам; `make test-credential-storage` проверяет, что пароль и session token хранятся только как hashes и не попадают в логи. Внутренние отрицательные тесты реализованы отдельно по [trust matrix](contracts/trust-matrix.md).
|
||||
|
||||
Проверка hardening и lifecycle не требует запущенного приложения:
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ TODO: схема процессов/хранилищ, источник исти
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Argon2id storage и калибровка | `scripts/benchmark-argon2.ps1`, `PasswordConfigTest` | PASS: итоговый профиль 32768 KiB/t=2/p=1; p95 encode 150.3 мс, verify 142.7 мс при 0.75 CPU/768 MiB; PHC хранит параметры и уникальный 16-byte salt | `README.md`, benchmark output, unit test |
|
||||
| Argon2id storage и калибровка | `scripts/benchmark-argon2.ps1`, `PasswordConfigTest` | PASS: итоговый профиль 32768 KiB/t=2/p=1; p95 encode 134.8 мс, verify 165.5 мс при 0.75 CPU/768 MiB (предыдущий прогон: 150.3/142.7 мс); PHC хранит параметры и уникальный 16-byte salt | `evidence/login-dos.txt`, `README.md`, unit test |
|
||||
| LB → каждая API-реплика | `scripts/test-mtls.ps1`, `TrustedClientCertificateFilterTest` | PASS: обе реплики отдельно отклоняют no-cert, foreign CA и доверенный cert с чужим URI SAN; LB identity принята; API port не опубликован | `compose.yaml`, runtime test, unit test |
|
||||
| Внутренние TLS-связи и service ACL | `scripts/test-internal-tls.ps1`; `docker compose --env-file .env --profile verification run --rm private-bucket-check` | PASS: PostgreSQL, MinIO, OpenBao, Redis, RabbitMQ, Collector, Loki, Tempo и Prometheus проверяют service CA и hostname; mTLS endpoints отвергают no-cert; PostgreSQL/Redis/RabbitMQ и MinIO API/worker identities разделены, запрещённые DDL/keys/commands/prefixes denied | `evidence/internal-tls.txt`, `contracts/trust-matrix.md` |
|
||||
| Broker/Collector mTLS role binding | `scripts/test-service-mtls-identities.ps1` | PASS: API/worker идут через разные broker gateways; OTLP gateway принимает обе разрешённые роли; same-CA migration/cross-role cert не получает AMQP/OTLP доступ; direct backend bypass отклонён | `evidence/service-mtls-identities.txt` |
|
||||
@@ -26,25 +26,74 @@ TODO: схема процессов/хранилищ, источник исти
|
||||
| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта |
|
||||
| Runtime isolation и утечки secrets | `scripts/test-container-secret-boundaries.ps1` | PASS: API/worker фактически non-root; privileged/host network/Docker socket отсутствуют; runtime limits и только разрешённые loopback bindings подтверждены; локальные secret values не найдены в Git, image metadata/filesystem и логах; redaction включён для traces/metrics/logs | `evidence/container-secret-boundaries.txt` |
|
||||
| Публичная security-проверка и session lifecycle | `tests/security.py`, `tests/smoke.py`, `tests/session_expiry.py` | PASS: verified HTTPS и отказ пустого trust store; outsider ACL, attachment isolation, 10 MiB limit, session cap, `429 Retry-After`, logout/revocation и управляемое expiry → `401` | `evidence/public-security.txt` |
|
||||
| Rehash старого password hash | `DatabaseAuthenticationProviderTest` (5 тестов) | PASS: legacy Argon2id 19456 KiB/t=2/p=1 после успешного login заменяется на 32768 KiB/t=2/p=1 через CAS `replacePasswordHash(userId, expectedHash, newHash)`; неверный пароль, unknown user и уже актуальный hash не переписываются; unknown/non-Argon2 значение проверяется по dummy hash | `evidence/password-rehash.txt` |
|
||||
| Login DoS budget и общий rate limit | `scripts/measure-login-dos.ps1 -SourceBudget`, `scripts/benchmark-argon2.ps1`, `LoginRateLimiterTest` | PASS: 5 попыток/username/60 s и 100/source/60 s в общем Redis; 6-я и 101-я попытки → `429` + `Retry-After`; 429 ≈ 19 мс против 401 p50 287 мс (Argon2 не запускается); обе реплики наблюдались; Redis outage fail-closed; ключи — SHA-256 digests | `evidence/login-dos.txt` |
|
||||
| Credential non-disclosure | `tests/credential_storage.py`, `tests/login_dos.py` | PASS: `password_hash` — Argon2id PHC, `token_hash` — 32-byte SHA-256; plaintext password/token/hash отсутствуют в API/LB logs; known и unknown user дают одинаковый `401` code/message; тела ошибок не содержат credentials | `evidence/credential-storage.txt`, `evidence/login-dos.txt` |
|
||||
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 26 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | `evidence/security-lifecycle.txt` |
|
||||
| Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | `evidence/verify-https-resilience.txt` |
|
||||
| Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | `evidence/verify-https-resilience.txt` |
|
||||
| Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей без неуспешных попыток, восстановление за 5.042 с (предыдущий прогон — 4.763 с); подтверждённые данные не потеряны | `evidence/verify-https-resilience.txt` |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Остальные пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### Login DoS budget
|
||||
|
||||
Гипотеза: общий Redis fixed-window лимит не даёт одному username или одному
|
||||
ingress-адресу бесконечно запускать дорогой Argon2id, а отказ Redis не
|
||||
открывает дорогой путь.
|
||||
|
||||
Стенд: Docker Desktop, две API-реплики по 0.75 CPU / 768 MiB, nginx HTTPS
|
||||
ingress, Redis 7.4 по mTLS. Argon2id: 32768 KiB, t=2, p=1; 5 warmup и 21
|
||||
измерение с уникальной солью. Калибровка: encode p50 100.2 мс / p95 134.8 мс,
|
||||
verify p50 115.5 мс / p95 165.5 мс. Предыдущий прогон того же скрипта дал
|
||||
encode p95 150.3 мс и verify p95 142.7 мс, поэтому в расчёте используется
|
||||
худший из наблюдавшихся p95 verify 165.5 мс.
|
||||
|
||||
Black-box через nginx: 5 неверных попыток одного username прошли с `401`
|
||||
(обе реплики видны в `X-Instance-Id`), 6-я вернула `429` + `Retry-After`.
|
||||
После окна 60 с 100 попыток с разными username прошли с `401`, 101-я вернула
|
||||
`429`. В последовательном режиме 401 p50 287.5 мс / p95 490.4 мс, а 429 —
|
||||
18.7–19.7 мс, то есть лимитер срабатывает до Argon2. Пять одновременных
|
||||
Argon2-проверок дали p50 1547 мс: это очередь на CPU-лимите 0.75, а не
|
||||
латентность одной проверки. Расчёт бюджета: 5 × 165.5 мс ≈ 0.83 с Argon2 CPU
|
||||
на username за окно; 100 × 165.5 мс ≈ 16.55 с, то есть ≈0.276 CPU в среднем
|
||||
за 60 с при лимите 0.75 CPU. Лимитер ограничивает rate, но не concurrency;
|
||||
одновременный burst всё ещё может создать очередь. При недоступном Redis
|
||||
проверка fail-closed, а не пропускает login.
|
||||
|
||||
Ограничение: source-ключ сейчас строится по `request.getRemoteAddr()`, то есть
|
||||
по адресу nginx/LB. Это общий cap для всех клиентов за LB, а не per-client;
|
||||
основная защита конкретного аккаунта — username-лимит. Trusted-proxy модель
|
||||
для клиентского адреса остаётся следующим шагом. Fixed window допускает burst
|
||||
на границе окна; успешные login тоже расходуют бюджет.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| Перезапуск PostgreSQL, Redis, MinIO, RabbitMQ, worker, двух API и LB без удаления volumes | Существующая сессия и подтверждённые данные доступны после готовности | Сессия повторно не создавалась; сообщение и вложение совпали с исходными | в пределах 180 с / потерь не обнаружено |
|
||||
| Остановка API-реплики, обслужившей контрольный запрос | LB продолжает направлять запросы на вторую реплику | 7 успешных записей без неуспешных попыток; остановленная реплика отсутствует среди последних ответов | 4.763 с / потерь и дублей не обнаружено |
|
||||
| Остановка API-реплики, обслужившей контрольный запрос | LB продолжает направлять запросы на вторую реплику | 7 успешных записей без неуспешных попыток; остановленная реплика отсутствует среди последних ответов | 5.042 с / потерь и дублей не обнаружено |
|
||||
| 5 неверных login одного username; 100 login с разными username | Argon2 ограничен, следующая попытка — быстрый 429 | 6-я и 101-я попытки → 429 + Retry-After; 429 ≈ 19 мс против 401 p50 287 мс; обе реплики | n/a / budget восстанавливается по TTL окна |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Login source limit использует адрес nginx/LB, поэтому это общий cap для
|
||||
клиентов за LB, а не per-client. Username-лимит остаётся основной защитой
|
||||
аккаунта; для per-client нужна trusted-proxy модель с проверкой, что
|
||||
`X-Forwarded-For` пришёл от доверенного LB.
|
||||
- Fixed window допускает burst на границе окна и считает успешные login
|
||||
наравне с неуспешными. Это осознанный компромисс; sliding window или
|
||||
отдельный счётчик только неуспешных попыток — возможное улучшение.
|
||||
- Лимитер ограничивает rate, но не concurrency: одновременный burst из
|
||||
нескольких клиентов может создать очередь на CPU-лимите API. Дополнительный
|
||||
bulkhead/semaphore вокруг Argon2 остаётся улучшением.
|
||||
- Argon2id 32768 KiB/t=2/p=1 выбран по измерению на локальном стенде; на
|
||||
другом hardware профиль нужно перекалибровать и обновить benchmark.
|
||||
- `MtusiMessengerApplicationTests` — интеграционный тест, которому нужны
|
||||
доступные PostgreSQL/Redis на localhost; в текущем Compose они не
|
||||
публикуются. Проверка этого критерия выполнена unit-тестами
|
||||
`DatabaseAuthenticationProviderTest`/`LoginRateLimiterTest` и black-box
|
||||
тестами через HTTPS.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
| Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/pki/public-ca/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement/expiry revoke access; leaf 30 d | `make test-security`, `make test-session-expiry`; пустой trust store → certificate error; revoked/expired token → 401; login burst → 429 + Retry-After | **PASS** для внешнего TLS/auth/session/rate-limit контракта |
|
||||
| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/pki/public-ca/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement/expiry revoke access; leaf 30 d | `make test-security`, `make test-session-expiry`, `scripts/measure-login-dos.ps1 -SourceBudget`; пустой trust store → certificate error; revoked/expired token → 401; login burst → 429 + Retry-After; rehash и dummy hash — unit tests | **PASS** для внешнего TLS/auth/session/rate-limit контракта |
|
||||
| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1` обращается к каждой реплике отдельно: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; LB cert → health 200; прямой published port отсутствует | **PASS** |
|
||||
| API → PostgreSQL | `postgres:5432` | TLS `verify-full`; service CA + SAN `DNS:postgres`; plaintext rejected by `pg_hba.conf` | `messenger_api`: runtime CRUD без superuser/DDL/role management | Static stand secret, rotate/reconnect; dynamic credentials remain extension | Wrong CA/hostname fails; DDL/role management denied | **PASS (уровень 3)** |
|
||||
| Worker → PostgreSQL | `postgres:5432` | TLS `verify-full` | `messenger_worker`: jobs/attachments/variants; нет users password/session/membership | Отдельный secret | `SELECT password_hash`, update membership denied; job transitions allowed | **PASS (уровень 3)** |
|
||||
@@ -33,6 +33,23 @@
|
||||
| Operator → MinIO admin | Не публикуется; bootstrap внутри сети | TLS verify | Root/operator отдельно; API/worker его не получают | Rotate after bootstrap/exposure | API/worker `mc admin info` denied | **PARTIAL:** port закрыт/policy test есть; HTTP и root env у init |
|
||||
| Replication channels | N/A: все stateful services single-node | N/A | N/A | N/A | При добавлении replicas матрица пересматривается | **N/A** |
|
||||
|
||||
### Пароли, сессии и login DoS
|
||||
|
||||
| Контроль | Реализация | Проверка | Статус |
|
||||
| --- | --- | --- | --- |
|
||||
| Password storage | Argon2id PHC 32768 KiB/t=2/p=1, уникальная 16-byte salt; параметры проверяются при старте | `PasswordConfigTest`; `benchmark-argon2.ps1`; `credential_storage.py` проверяет префикс PHC и отсутствие plaintext | **PASS** |
|
||||
| Rehash при успешном login | `upgradeEncoding` + CAS `replacePasswordHash(userId, expectedHash, newHash)`; неверный пароль/unknown/current hash не переписываются | `DatabaseAuthenticationProviderTest` (5 тестов) | **PASS** |
|
||||
| Session token storage | 32 random bytes, base64url; в БД только 32-byte SHA-256 `token_hash`; TTL и максимум 3 активных сессии | `AuthenticationServiceTest`; `credential_storage.py` сверяет SHA-256 и отсутствие token в БД/логах | **PASS** |
|
||||
| Error non-disclosure | Единые `401 unauthorized`, `429 rate_limited`, `503 unavailable`; known/unknown user не различаются; тела ошибок без credentials | `login_dos.py`; `credential_storage.py`; redaction `authorization`/body в telemetry | **PASS** |
|
||||
| Shared login limit | Redis Lua atomic fixed window: 5/username/60 s и 100/source/60 s; ключи — SHA-256 digests; обе реплики используют один Redis | `LoginRateLimiterTest`; `measure-login-dos.ps1 -SourceBudget` (обе реплики в `X-Instance-Id`) | **PASS** |
|
||||
| Redis outage | Fail-closed `AuthenticationServiceException` → `503`, дорогой Argon2 не запускается | `LoginRateLimiterTest`; runtime можно проверить остановкой Redis | **PASS** |
|
||||
| Measured DoS budget | p95 verify 165.5 мс при 0.75 CPU/768 MiB; 5 × p95 ≈ 0.83 s CPU на username/окно; 100 × p95 ≈ 16.55 s CPU на source/окно (≈0.276 CPU в среднем); 429 ≈ 19 мс без Argon2 | `benchmark-argon2.ps1`; `measure-login-dos.ps1 -SourceBudget`; `evidence/login-dos.txt` | **PASS** |
|
||||
|
||||
Ограничение: source-ключ строится по `request.getRemoteAddr()`, то есть по
|
||||
адресу nginx/LB. Это общий cap для всех клиентов за LB, не per-client;
|
||||
username-лимит остаётся основной защитой аккаунта. Fixed window допускает
|
||||
burst на границе окна; лимитер ограничивает rate, но не concurrency.
|
||||
|
||||
## Health, scrape и bootstrap
|
||||
|
||||
| Канал | Разрешение | Запрет / тест | Статус |
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Credential storage and log non-disclosure
|
||||
|
||||
Date: 2026-11-27
|
||||
Stand: local Docker Desktop, compose project hla-lab7
|
||||
|
||||
Command:
|
||||
python tests/credential_storage.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
|
||||
|
||||
Observed result:
|
||||
PASS: password and session token are stored only as hashes and are absent from API/LB logs.
|
||||
|
||||
What the check does:
|
||||
- creates one synthetic user and one session over verified HTTPS;
|
||||
- reads the user's password_hash and the session token_hash from
|
||||
PostgreSQL using the operator connection;
|
||||
- requires password_hash to start with the measured
|
||||
$argon2id$v=19$m=32768,t=2,p=1$ profile and to differ from the password;
|
||||
- requires token_hash to be exactly the SHA-256 of the issued token
|
||||
(64 hex characters / 32 bytes) and not the token itself;
|
||||
- scans the API and nginx logs for the synthetic password, the synthetic
|
||||
token, the stored password hash and the stored token hash;
|
||||
- fails if any of those values appear in the logs.
|
||||
|
||||
Related black-box check:
|
||||
tests/login_dos.py asserts that 401/429 bodies and headers do not contain
|
||||
the tested username, password, hash or token. Known and unknown usernames
|
||||
return the same 401 code and message.
|
||||
|
||||
The synthetic password and token exist only in process memory; this file
|
||||
contains no credential values.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Measured login DoS budget and shared rate limit
|
||||
|
||||
Date: 2026-11-27
|
||||
Stand: local Docker Desktop, compose project hla-lab7, two API replicas
|
||||
(0.75 CPU / 768 MiB each), nginx HTTPS ingress, Redis 7.4 over mTLS.
|
||||
|
||||
Commands:
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\benchmark-argon2.ps1
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\measure-login-dos.ps1 -SourceBudget
|
||||
|
||||
Argon2id calibration (0.75 CPU / 768 MiB, 5 warmups, 21 samples, unique salt):
|
||||
32768 KiB, t=2, p=1:
|
||||
encode p50 100.182 ms, p95 134.817 ms
|
||||
verify p50 115.483 ms, p95 165.503 ms
|
||||
Previous run of the same script: encode p95 150.3 ms, verify p95 142.7 ms.
|
||||
|
||||
Observed login budget (black-box through nginx):
|
||||
Per username: 5 attempts / 60 s, shared by both replicas.
|
||||
- 5 concurrent failed logins returned 401 and were served by two
|
||||
distinct X-Instance-Id values.
|
||||
- The 6th attempt returned 429 rate_limited with Retry-After 58 s.
|
||||
- 5 concurrent Argon2 verifications: p50 1547.045 ms, p95 1662.582 ms.
|
||||
This is queueing on the 0.75-CPU limit, not a single-request latency.
|
||||
- The 429 response took 19.682 ms, i.e. it did not run Argon2.
|
||||
Per source: 100 attempts / 60 s, shared by both replicas.
|
||||
- After the 60 s window was allowed to expire, 100 failed logins with
|
||||
distinct usernames returned 401; both replicas were observed.
|
||||
- The 101st attempt returned 429 rate_limited with Retry-After 60 s.
|
||||
- Sequential 401 path: p50 287.473 ms, p95 490.411 ms (includes
|
||||
TLS, Redis, PostgreSQL and Argon2id).
|
||||
- The 429 response took 18.654 ms, i.e. it did not run Argon2.
|
||||
Known and unknown usernames:
|
||||
- Both returned 401 with code "unauthorized" and the same message.
|
||||
- Known-user request 510.424 ms; unknown-user request 309.891 ms in
|
||||
that run. The difference is not a stable user-existence oracle; both
|
||||
paths run one Argon2id verification (the unknown path uses the dummy
|
||||
hash).
|
||||
|
||||
Budget calculation using the p95 verify time:
|
||||
- Per username: 5 * 165.503 ms = 0.83 s of Argon2 CPU per 60 s window.
|
||||
- Per source: 100 * 165.503 ms = 16.55 s of Argon2 CPU per 60 s window,
|
||||
i.e. about 0.276 CPU averaged over the window on the 0.75-CPU API limit.
|
||||
- The limiter is a rate cap, not a concurrency cap: a simultaneous burst
|
||||
can still queue on the CPU limit, as the 5-way burst above shows.
|
||||
- A Redis outage fails closed (503), so the expensive path is not exposed.
|
||||
|
||||
Shared-state and key handling:
|
||||
- The fixed-window counters live in Redis under
|
||||
messenger:login:user:<sha256> and messenger:login:source:<sha256>.
|
||||
- The Lua script increments both counters and sets the TTL atomically.
|
||||
- Both API replicas use the same Redis keys, so the budget is global for
|
||||
the deployment, not per process.
|
||||
- Raw usernames and source addresses are not used as Redis key material.
|
||||
|
||||
Known limitation:
|
||||
- The source key currently uses request.getRemoteAddr(), which is the
|
||||
nginx/LB address. It is therefore a global source cap shared by all
|
||||
clients behind the LB, not a per-client cap. The per-username limit is
|
||||
the primary per-account control. A trusted-proxy client-address model
|
||||
remains the next step.
|
||||
|
||||
No passwords, session tokens or password hashes are included.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Password rehash and shared login-rate-limit unit checks
|
||||
|
||||
Date: 2026-11-27
|
||||
Stand: Windows host, Gradle 9.7.1, Java 23 toolchain
|
||||
|
||||
Command:
|
||||
.\gradlew.bat test --tests com.example.mtusi_messenger.security.DatabaseAuthenticationProviderTest --tests com.example.mtusi_messenger.security.LoginRateLimiterTest --no-daemon --console=plain
|
||||
|
||||
Observed result:
|
||||
BUILD SUCCESSFUL
|
||||
DatabaseAuthenticationProviderTest: 5 tests, 0 failures, 0 errors
|
||||
LoginRateLimiterTest: 5 tests, 0 failures, 0 errors
|
||||
|
||||
DatabaseAuthenticationProviderTest proves:
|
||||
- a valid legacy Argon2id hash (19456 KiB, t=2, p=1) is replaced after a
|
||||
successful login by a hash with the measured runtime profile
|
||||
(32768 KiB, t=2, p=1);
|
||||
- the replacement uses the compare-and-swap contract
|
||||
replacePasswordHash(userId, expectedHash, newHash);
|
||||
- a wrong password, an unknown user and an already-current hash do not
|
||||
rewrite the stored hash;
|
||||
- an unknown user and a non-Argon2 stored value are checked against the
|
||||
dummy hash, not against attacker-controlled stored text;
|
||||
- authentication failures do not echo the password or the stored hash.
|
||||
|
||||
LoginRateLimiterTest proves:
|
||||
- two limiter instances (simulated replicas) share the same username and
|
||||
source budgets through the same Redis template;
|
||||
- username matching is case-insensitive;
|
||||
- Redis keys are SHA-256 digests and do not contain the raw username or
|
||||
source address;
|
||||
- a Redis outage fails closed with AuthenticationServiceException instead
|
||||
of allowing expensive password verification;
|
||||
- invalid limit/window configuration is rejected.
|
||||
|
||||
No passwords, session tokens or password hashes are printed by these tests.
|
||||
@@ -0,0 +1,42 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$EnvFile = '.env',
|
||||
[string]$Python = 'python',
|
||||
[string]$BaseUrl = 'https://localhost:8443',
|
||||
[int]$MinimumInstances = 2,
|
||||
[switch]$SourceBudget,
|
||||
[switch]$IncludeArgon2
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
Set-Location $projectRoot
|
||||
if(-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
|
||||
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
|
||||
}
|
||||
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
|
||||
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
|
||||
if($replicas.Count -lt $MinimumInstances){
|
||||
throw "At least $MinimumInstances running API replicas are required"
|
||||
}
|
||||
|
||||
# Check storage/logs before the DoS phase consumes the source budget.
|
||||
& $Python 'tests/credential_storage.py' --base-url $BaseUrl --ca-file $ca --env-file $EnvFile
|
||||
if($LASTEXITCODE -ne 0){ throw 'Credential storage/log check failed' }
|
||||
|
||||
if($IncludeArgon2){
|
||||
& "$PSScriptRoot\benchmark-argon2.ps1"
|
||||
if($LASTEXITCODE -ne 0){ throw 'Argon2id benchmark failed' }
|
||||
}
|
||||
|
||||
$testArguments = @(
|
||||
'tests/login_dos.py',
|
||||
'--base-url', $BaseUrl,
|
||||
'--ca-file', $ca,
|
||||
'--minimum-instances', "$MinimumInstances"
|
||||
)
|
||||
if($SourceBudget){ $testArguments += '--source-budget' }
|
||||
|
||||
& $Python @testArguments
|
||||
if($LASTEXITCODE -ne 0){ throw 'Login DoS budget test failed' }
|
||||
Write-Host 'PASS: shared login budget, fast rate-limit rejection and credential non-disclosure verified.'
|
||||
@@ -65,8 +65,8 @@ Operator ── loopback/protected channel ── admin planes
|
||||
| Внутренний контейнер обращается к API, минуя nginx | Business API доступен только доверенному LB | API TLS `client-auth=need`, отдельный LB CA и точный allowlist SAN `spiffe://hla-lab7/lb`; порт не публикуется | `scripts/test-mtls.ps1`: no cert/foreign CA/wrong SAN rejected; LB accepted | Компрометация LB key требует немедленного отзыва/ротации |
|
||||
| Пользователь меняет `X-User-Id` или UUID и читает чужой чат/attachment | Identity определяется Bearer; membership проверяется сервером | Stateless auth filter, token hash lookup, repository membership predicates и FK | Bob + Alice UUID → 404/401; forged `X-User-Id` не меняет результат | Ошибки намеренно не различают отсутствие объекта и отсутствие прав |
|
||||
| Пользователь прикрепляет чужой attachment или читает object key напрямую | Attachment принадлежит тому же чату; bucket private | Membership/ownership/chat validation, private bucket, opaque keys | Загрузить в чат A, попытаться attach/read из B; anonymous `mc ls/cp` → denied | Компрометация S3 credential даёт доступ в пределах его policy |
|
||||
| Credential stuffing на login истощает CPU Argon2id | Login bounded; ответ не раскрывает существование user | Argon2id, dummy hash; общий Redis fixed-window limit по username/source, fail-closed, 429/Retry-After | Серия неверных login через разные replicas → 429; existing/unknown user имеют одинаковый класс ответа | Fixed window допускает burst на границе окна; source limit видит адрес ingress до завершения trusted-proxy модели |
|
||||
| Кража БД раскрывает пароль или активный bearer token | В БД нет plaintext password/session token | Argon2id password hash; SHA-256 session token hash; TTL/logout | Проверить `$argon2id$`; plaintext token отсутствует; после logout/expiry token → 401 | Offline guessing зависит от качества пароля и измеренных Argon2 параметров |
|
||||
| Credential stuffing на login истощает CPU Argon2id | Login bounded; ответ не раскрывает существование user | Argon2id 32768 KiB/t=2/p=1, dummy hash; общий Redis fixed-window limit 5/username/60 s и 100/source/60 s, fail-closed, 429/Retry-After | `measure-login-dos.ps1 -SourceBudget`: 6-я/101-я попытки → 429; обе реплики; 429 ≈19 мс против 401 p50 287 мс; `LoginRateLimiterTest` — shared state и fail-closed; existing/unknown user имеют одинаковый 401 | Fixed window допускает burst на границе окна; source limit видит адрес ingress (общий cap за LB), trusted-proxy модель не завершена; лимитер не ограничивает concurrency |
|
||||
| Кража БД раскрывает пароль или активный bearer token | В БД нет plaintext password/session token | Argon2id password hash с rehash при успешном login через CAS; SHA-256 session token hash; TTL/logout | `credential_storage.py`: PHC-префикс, SHA-256 token hash, plaintext password/token/hash отсутствуют в API/LB logs; `DatabaseAuthenticationProviderTest` — rehash и dummy hash; после logout/expiry token → 401 | Offline guessing зависит от качества пароля и измеренных Argon2 параметров |
|
||||
| Скомпрометированный worker читает users/sessions или admin bucket/queue | Worker видит только jobs и нужные storage operations | Отдельные DB role, S3 key, RabbitMQ/Redis cert+user+ACL; отдельная OpenBao AppRole читает только worker KV | Worker: `SELECT password_hash`, MinIO admin, запрещённый broker route и API KV → denied | MinIO API/worker пока используют одинаковую bucket policy, хотя keys различаются |
|
||||
| Поддельный RabbitMQ job или подтверждение чужой работы | Producer/consumer identities и ACL различаются | mTLS `5671`, отдельные cert/users/regex permissions; plaintext listener disabled; DB lease fencing | No cert/foreign CA → TLS отказ; запрещённая broker operation → access refused | Точная проверка URI SAN выполняется ACL user mapping, не самим Rabbit TLS listener |
|
||||
| Внутренний контейнер шлёт фальшивую telemetry или читает backends | Только заявленные workload identities могут ingest/query | mTLS на workload→Collector, Collector→Loki/Tempo, Prometheus→Collector и Grafana→backends; отдельные certs; redaction | No cert/foreign CA rejected; Prometheus разрешает exact Grafana SAN; canary отсутствует в telemetry | Single-tenant Loki/Tempo не дают fine-grained query ACL сверх mTLS role |
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class DatabaseAuthenticationProviderTest {
|
||||
private static final String PASSWORD = "correct horse battery staple";
|
||||
private static final User USER = new User(
|
||||
UUID.randomUUID(), "alice", "Alice", Instant.parse("2026-01-01T00:00:00Z"));
|
||||
|
||||
@Test
|
||||
void upgradesLegacyHashAfterSuccessfulLogin() {
|
||||
PasswordEncoder current = new Argon2PasswordEncoder(16, 32, 1, 32768, 2);
|
||||
PasswordEncoder legacy = new Argon2PasswordEncoder(16, 32, 1, 19456, 2);
|
||||
String legacyHash = legacy.encode(PASSWORD);
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
when(users.findCredentialsByUsername("alice"))
|
||||
.thenReturn(Optional.of(new UserRepository.UserCredentials(USER, legacyHash)));
|
||||
when(users.replacePasswordHash(eq(USER.id()), eq(legacyHash), anyString()))
|
||||
.thenReturn(true);
|
||||
|
||||
var provider = new DatabaseAuthenticationProvider(users, current);
|
||||
var result = provider.authenticate(
|
||||
UsernamePasswordAuthenticationToken.unauthenticated("alice", PASSWORD));
|
||||
|
||||
assertSame(USER, result.getPrincipal());
|
||||
ArgumentCaptor<String> upgraded = ArgumentCaptor.forClass(String.class);
|
||||
verify(users).replacePasswordHash(eq(USER.id()), eq(legacyHash), upgraded.capture());
|
||||
assertTrue(upgraded.getValue().startsWith("$argon2id$v=19$m=32768,t=2,p=1$"));
|
||||
assertTrue(current.matches(PASSWORD, upgraded.getValue()));
|
||||
assertFalse(upgraded.getValue().equals(legacyHash));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRewriteHashThatAlreadyMatchesTheCurrentProfile() {
|
||||
PasswordEncoder current = new Argon2PasswordEncoder(16, 32, 1, 32768, 2);
|
||||
String currentHash = current.encode(PASSWORD);
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
when(users.findCredentialsByUsername("alice"))
|
||||
.thenReturn(Optional.of(new UserRepository.UserCredentials(USER, currentHash)));
|
||||
|
||||
var provider = new DatabaseAuthenticationProvider(users, current);
|
||||
provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("alice", PASSWORD));
|
||||
|
||||
verify(users, never()).replacePasswordHash(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRewriteHashAfterWrongPasswordAndDoesNotEchoCredentials() {
|
||||
PasswordEncoder current = new Argon2PasswordEncoder(16, 32, 1, 32768, 2);
|
||||
String currentHash = current.encode(PASSWORD);
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
when(users.findCredentialsByUsername("alice"))
|
||||
.thenReturn(Optional.of(new UserRepository.UserCredentials(USER, currentHash)));
|
||||
|
||||
var provider = new DatabaseAuthenticationProvider(users, current);
|
||||
BadCredentialsException failure = assertThrows(BadCredentialsException.class,
|
||||
() -> provider.authenticate(
|
||||
UsernamePasswordAuthenticationToken.unauthenticated("alice", "wrong-password")));
|
||||
|
||||
assertFalse(failure.getMessage().contains("wrong-password"));
|
||||
assertFalse(failure.getMessage().contains(currentHash));
|
||||
verify(users, never()).replacePasswordHash(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownUserIsCheckedAgainstTheDummyHash() {
|
||||
PasswordEncoder encoder = mock(PasswordEncoder.class);
|
||||
String dummy = "$argon2id$v=19$m=32768,t=2,p=1$dummy-salt$dummy-hash";
|
||||
when(encoder.encode(anyString())).thenReturn(dummy);
|
||||
when(encoder.matches(anyString(), anyString())).thenReturn(false);
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
when(users.findCredentialsByUsername("missing")).thenReturn(Optional.empty());
|
||||
|
||||
var provider = new DatabaseAuthenticationProvider(users, encoder);
|
||||
BadCredentialsException failure = assertThrows(BadCredentialsException.class,
|
||||
() -> provider.authenticate(
|
||||
UsernamePasswordAuthenticationToken.unauthenticated("missing", PASSWORD)));
|
||||
|
||||
ArgumentCaptor<String> hash = ArgumentCaptor.forClass(String.class);
|
||||
verify(encoder).matches(eq(PASSWORD), hash.capture());
|
||||
assertEquals(dummy, hash.getValue());
|
||||
assertFalse(failure.getMessage().contains(PASSWORD));
|
||||
verify(users, never()).replacePasswordHash(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonArgon2StoredValueIsNotComparedDirectly() {
|
||||
PasswordEncoder encoder = mock(PasswordEncoder.class);
|
||||
String dummy = "$argon2id$v=19$m=32768,t=2,p=1$dummy-salt$dummy-hash";
|
||||
when(encoder.encode(anyString())).thenReturn(dummy);
|
||||
when(encoder.matches(anyString(), anyString())).thenReturn(false);
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
when(users.findCredentialsByUsername("alice"))
|
||||
.thenReturn(Optional.of(new UserRepository.UserCredentials(USER, "plaintext-value")));
|
||||
|
||||
var provider = new DatabaseAuthenticationProvider(users, encoder);
|
||||
assertThrows(BadCredentialsException.class,
|
||||
() -> provider.authenticate(
|
||||
UsernamePasswordAuthenticationToken.unauthenticated("alice", PASSWORD)));
|
||||
|
||||
verify(encoder).matches(eq(PASSWORD), eq(dummy));
|
||||
verify(encoder, never()).matches(anyString(), eq("plaintext-value"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.example.mtusi_messenger.security;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.data.redis.RedisConnectionFailureException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.RedisScript;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class LoginRateLimiterTest {
|
||||
@Test
|
||||
void twoReplicaInstancesShareTheSameUsernameBudget() {
|
||||
InMemoryRedis redis = new InMemoryRedis();
|
||||
LoginRateLimiter replicaA = new LoginRateLimiter(redis, 2, 10, 60);
|
||||
LoginRateLimiter replicaB = new LoginRateLimiter(redis, 2, 10, 60);
|
||||
|
||||
replicaA.check("Alice", "10.0.0.1");
|
||||
replicaA.check("alice", "10.0.0.1");
|
||||
|
||||
LoginRateLimitException blocked = assertThrows(LoginRateLimitException.class,
|
||||
() -> replicaB.check("ALICE", "10.0.0.1"));
|
||||
assertTrue(blocked.retryAfterSeconds() >= 1);
|
||||
assertTrue(blocked.retryAfterSeconds() <= 60);
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoReplicaInstancesShareTheSameSourceBudget() {
|
||||
InMemoryRedis redis = new InMemoryRedis();
|
||||
LoginRateLimiter replicaA = new LoginRateLimiter(redis, 5, 10, 60);
|
||||
LoginRateLimiter replicaB = new LoginRateLimiter(redis, 5, 10, 60);
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
replicaA.check("user-" + i, "10.0.0.2");
|
||||
}
|
||||
|
||||
assertThrows(LoginRateLimitException.class,
|
||||
() -> replicaB.check("new-user", "10.0.0.2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void redisKeysDoNotContainTheRawUsernameOrSourceAddress() {
|
||||
InMemoryRedis redis = new InMemoryRedis();
|
||||
LoginRateLimiter limiter = new LoginRateLimiter(redis, 5, 100, 60);
|
||||
|
||||
limiter.check("Alice", "192.0.2.10");
|
||||
|
||||
assertFalse(redis.seenKeys().isEmpty());
|
||||
for (String key : redis.seenKeys()) {
|
||||
assertTrue(key.matches("messenger:login:(user|source):[0-9a-f]{64}"), key);
|
||||
assertFalse(key.contains("alice"));
|
||||
assertFalse(key.contains("192.0.2.10"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void redisOutageFailsClosedInsteadOfAllowingExpensiveLogins() {
|
||||
StringRedisTemplate failing = new StringRedisTemplate() {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T execute(RedisScript<T> script, List<String> keys, Object... args) {
|
||||
throw new RedisConnectionFailureException("simulated outage");
|
||||
}
|
||||
};
|
||||
LoginRateLimiter limiter = new LoginRateLimiter(failing, 5, 100, 60);
|
||||
|
||||
assertThrows(AuthenticationServiceException.class,
|
||||
() -> limiter.check("alice", "192.0.2.10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsConfigurationWhereTheSourceBudgetIsSmallerThanTheUsernameBudget() {
|
||||
InMemoryRedis redis = new InMemoryRedis();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new LoginRateLimiter(redis, 5, 4, 60));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new LoginRateLimiter(redis, 5, 100, 0));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new LoginRateLimiter(redis, 5, 100, 3601));
|
||||
}
|
||||
|
||||
private static final class InMemoryRedis extends StringRedisTemplate {
|
||||
private final Map<String, Long> counters = new HashMap<>();
|
||||
private final List<String> seenKeys = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T execute(RedisScript<T> script, List<String> keys, Object... args) {
|
||||
seenKeys.addAll(keys);
|
||||
long usernameLimit = Long.parseLong((String) args[0]);
|
||||
long sourceLimit = Long.parseLong((String) args[1]);
|
||||
long windowSeconds = Long.parseLong((String) args[2]);
|
||||
|
||||
long usernameCount = counters.merge(keys.get(0), 1L, Long::sum);
|
||||
long sourceCount = counters.merge(keys.get(1), 1L, Long::sum);
|
||||
if (usernameCount > usernameLimit || sourceCount > sourceLimit) {
|
||||
return (T) Long.valueOf(Math.max(1, windowSeconds));
|
||||
}
|
||||
return (T) Long.valueOf(0);
|
||||
}
|
||||
|
||||
List<String> seenKeys() {
|
||||
return seenKeys;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,33 @@ make test-session-expiry BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/
|
||||
logout. Token, пароль и SQL credentials не печатаются. Это не публичный black-box
|
||||
тест, поскольку управляемое истечение часа ожидать непрактично.
|
||||
|
||||
## Login DoS budget и credential storage
|
||||
|
||||
```sh
|
||||
make test-login-dos BASE_URL=https://localhost:8443 CA_FILE=secrets/pki/public-ca/ca.crt
|
||||
make test-credential-storage BASE_URL=https://localhost:8443 CA_FILE=secrets/pki/public-ca/ca.crt
|
||||
```
|
||||
|
||||
`login_dos.py` — black-box проверка через nginx: 5 неверных попыток одного
|
||||
username и 6-я → `429` + `Retry-After`; при `--source-budget` после окна 60 с
|
||||
100 попыток с разными username и 101-я → `429`. Скрипт записывает
|
||||
`X-Instance-Id` и требует, чтобы попытки обслуживали минимум две реплики
|
||||
(`--minimum-instances`, по умолчанию 2). Он также проверяет, что 429 дешевле
|
||||
Argon2-пути, что known/unknown user дают одинаковый `401`, и что тела/headers
|
||||
не содержат credentials. `scripts/measure-login-dos.ps1 -SourceBudget` запускает
|
||||
этот тест вместе с `credential_storage.py`; `-IncludeArgon2` дополнительно
|
||||
запускает калибровку.
|
||||
|
||||
`credential_storage.py` — локальная Compose-проверка: создаёт synthetic
|
||||
пользователя и сессию, читает `password_hash`/`token_hash` из PostgreSQL,
|
||||
сверяет Argon2id PHC и SHA-256, затем ищет plaintext password/token/hash в
|
||||
логах API и nginx. Пароль и token не печатаются. Это не публичный black-box
|
||||
тест, потому что ему нужен операторский доступ к БД и логам.
|
||||
|
||||
Ограничение: source-лимит видит адрес nginx/LB, поэтому это общий cap для
|
||||
клиентов за LB, а не per-client. Username-лимит остаётся основной защитой
|
||||
аккаунта; trusted-proxy модель для клиентского адреса — следующий шаг.
|
||||
|
||||
## Что ещё остаётся доказать
|
||||
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local Compose check: stored credentials are hashes and are absent from logs.
|
||||
|
||||
The check creates one synthetic user and one session, then reads only the
|
||||
password hash and token hash from PostgreSQL. The synthetic password and token
|
||||
stay in process memory; on failure the script never prints them.
|
||||
"""
|
||||
import hashlib
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
from client import Client, LAB, arguments, check, run
|
||||
|
||||
|
||||
def read_env(path):
|
||||
values = {}
|
||||
env_path = pathlib.Path(path)
|
||||
if not env_path.is_file():
|
||||
return values
|
||||
for raw in env_path.read_text(encoding='utf-8-sig').splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
name, value = line.split('=', 1)
|
||||
values[name.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument('--env-file', default='.env')
|
||||
|
||||
|
||||
def compose(args, *command, input_text=None):
|
||||
return subprocess.run([
|
||||
'docker', 'compose', '--env-file', args.env_file, *command,
|
||||
], cwd=pathlib.Path(__file__).resolve().parents[1], input=input_text,
|
||||
capture_output=True, text=True, timeout=60)
|
||||
|
||||
|
||||
def psql(args, database_user, database_name, sql, variables=None):
|
||||
command = [
|
||||
'exec', '-T', 'postgres',
|
||||
'psql', '--username', database_user, '--dbname', database_name,
|
||||
'--set', 'ON_ERROR_STOP=1',
|
||||
'--tuples-only', '--no-align',
|
||||
]
|
||||
for name, value in (variables or {}).items():
|
||||
command.extend(['--set', name + '=' + value])
|
||||
result = compose(args, *command, input_text=sql)
|
||||
check(result.returncode == 0, 'operator database query failed')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Local Compose credential storage and log leak check', configure)
|
||||
check(LAB >= 2, 'credential storage requires lab2 or later')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
actor = client.user('storage')
|
||||
username = actor['registration']['username']
|
||||
password = actor['registration']['password']
|
||||
token = actor['token']
|
||||
|
||||
env = read_env(args.env_file)
|
||||
database_user = env.get('DATABASE_USER', 'messenger')
|
||||
database_name = env.get('DATABASE_NAME', 'messenger')
|
||||
|
||||
password_hash = psql(args, database_user, database_name, """
|
||||
SELECT password_hash
|
||||
FROM users
|
||||
WHERE username = :'target_username';
|
||||
""", {'target_username': username})
|
||||
check(password_hash.startswith('$argon2id$v=19$m=32768,t=2,p=1$'),
|
||||
'stored password value is not the measured Argon2id PHC string')
|
||||
check(password not in password_hash, 'stored password hash contains the plaintext password')
|
||||
check(len(password_hash) > 50, 'stored password hash is unexpectedly short')
|
||||
|
||||
token_hash = psql(args, database_user, database_name, """
|
||||
SELECT encode(token_hash, 'hex')
|
||||
FROM sessions
|
||||
WHERE user_id = (SELECT id FROM users WHERE username = :'target_username')
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1;
|
||||
""", {'target_username': username})
|
||||
expected = hashlib.sha256(token.encode('ascii')).hexdigest()
|
||||
check(token_hash == expected, 'stored session value is not the SHA-256 of the issued token')
|
||||
check(len(token_hash) == 64, 'stored session hash is not 32 bytes')
|
||||
check(token_hash != token, 'session token itself was stored')
|
||||
|
||||
log_text = ''
|
||||
for service in ('api', 'nginx'):
|
||||
result = compose(args, 'logs', '--no-color', service)
|
||||
check(result.returncode == 0, 'could not read ' + service + ' logs')
|
||||
log_text += result.stdout + result.stderr
|
||||
check(len(log_text) > 0, 'no API/LB logs were available for the leak check')
|
||||
check(password not in log_text, 'API/LB logs contain the synthetic password')
|
||||
check(token not in log_text, 'API/LB logs contain the synthetic session token')
|
||||
check(password_hash not in log_text, 'API/LB logs contain the stored password hash')
|
||||
check(token_hash not in log_text, 'API/LB logs contain the stored token hash')
|
||||
|
||||
print('PASS: password and session token are stored only as hashes and are absent from API/LB logs.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measures the shared login rate-limit budget and checks credential non-disclosure.
|
||||
|
||||
The test is intentionally black-box: it talks only through the public HTTPS
|
||||
ingress, records which API replica served each attempt, and never prints a
|
||||
password, session token or password hash.
|
||||
"""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import socket
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def prefer_ipv4_for_localhost():
|
||||
"""Avoid a ~2 s IPv6 fallback on Windows when localhost resolves to ::1 first."""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
|
||||
addresses = original(host, port, family, type, proto, flags)
|
||||
if host == 'localhost' and family in (0, socket.AF_UNSPEC):
|
||||
ipv4 = [address for address in addresses if address[0] == socket.AF_INET]
|
||||
return ipv4 or addresses
|
||||
return addresses
|
||||
|
||||
socket.getaddrinfo = getaddrinfo
|
||||
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument('--minimum-instances', type=int, default=2,
|
||||
help='fail unless this many distinct X-Instance-Id values are observed')
|
||||
parser.add_argument('--username-limit', type=int, default=5)
|
||||
parser.add_argument('--source-limit', type=int, default=100)
|
||||
parser.add_argument('--window-seconds', type=int, default=60)
|
||||
parser.add_argument('--source-budget', action='store_true',
|
||||
help='also exhaust the per-source budget (takes about one window plus 100 verifies)')
|
||||
parser.add_argument('--wait-window', type=int, default=61,
|
||||
help='wait this long before the source-budget phase so its counter is empty')
|
||||
|
||||
|
||||
def register(client, label):
|
||||
username = 'dos_' + label.replace('-', '_') + '_' + uuid.uuid4().hex[:12]
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
client.call('POST', '/api/v1/users', 201,
|
||||
body={'username': username, 'display_name': 'DoS ' + label, 'password': password},
|
||||
schema='User')
|
||||
return username, password
|
||||
|
||||
|
||||
def login(client, username, password):
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
return client.call('POST', '/api/v1/auth/sessions', (200, 201, 401, 429),
|
||||
headers={'Authorization': 'Basic ' + credential})
|
||||
|
||||
|
||||
def assert_no_secret(response, *secrets):
|
||||
body = response['bytes'].decode('utf-8', 'replace').lower()
|
||||
headers = ' '.join(f'{key}: {value}' for key, value in response['headers'].items()).lower()
|
||||
for secret in secrets:
|
||||
if not secret:
|
||||
continue
|
||||
check(secret.lower() not in body, 'error response leaked a credential')
|
||||
check(secret.lower() not in headers, 'error headers leaked a credential')
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
if not values:
|
||||
return 0.0
|
||||
ordered = sorted(values)
|
||||
index = max(0, min(len(ordered) - 1, int(math.ceil(fraction * len(ordered))) - 1))
|
||||
return ordered[index]
|
||||
|
||||
|
||||
def burst(base_url, ca_file, username, wrong_password, count):
|
||||
def attempt(_):
|
||||
return login(Client(base_url, ca_file), username, wrong_password)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool:
|
||||
return list(pool.map(attempt, range(count)))
|
||||
|
||||
|
||||
def check_username_budget(args):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
username, password = register(client, 'known')
|
||||
wrong = 'wrong-' + uuid.uuid4().hex
|
||||
responses = burst(client.base, args.ca_file, username, wrong, args.username_limit)
|
||||
statuses = [response['status'] for response in responses]
|
||||
check(all(status == 401 for status in statuses),
|
||||
'an attempt below the per-username budget was rejected')
|
||||
for response in responses:
|
||||
assert_no_secret(response, username, wrong, password)
|
||||
|
||||
blocked = login(client, username, wrong)
|
||||
check(blocked['status'] == 429, 'attempt above the per-username budget was not rate limited')
|
||||
check(blocked['json']['error']['code'] == 'rate_limited', 'wrong rate-limit error code')
|
||||
retry_after = blocked['headers'].get('Retry-After', '')
|
||||
check(retry_after.isdigit() and 1 <= int(retry_after) <= args.window_seconds,
|
||||
'missing or out-of-window Retry-After')
|
||||
assert_no_secret(blocked, username, wrong, password)
|
||||
|
||||
instances = sorted({response['headers'].get('X-Instance-Id', '') for response in responses})
|
||||
check(len(instances) >= args.minimum_instances,
|
||||
'login attempts reached only ' + str(len(instances)) + ' API replica(s)')
|
||||
latencies = [response['elapsed'] for response in responses]
|
||||
check(blocked['elapsed'] < percentile(latencies, 0.50),
|
||||
'rate-limited response was not cheaper than the Argon2 verification path')
|
||||
|
||||
return {
|
||||
'limit': args.username_limit,
|
||||
'window_seconds': args.window_seconds,
|
||||
'allowed_under_limit': statuses.count(401),
|
||||
'blocked_status': blocked['status'],
|
||||
'blocked_code': blocked['json']['error']['code'],
|
||||
'retry_after_seconds': int(retry_after),
|
||||
'argon2_path_p50_ms': round(statistics.median(latencies) * 1000, 3),
|
||||
'argon2_path_p95_ms': round(percentile(latencies, 0.95) * 1000, 3),
|
||||
'rate_limited_ms': round(blocked['elapsed'] * 1000, 3),
|
||||
'observed_instances': instances,
|
||||
}
|
||||
|
||||
|
||||
def check_user_enumeration(args):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
known_name, known_password = register(client, 'enum-known')
|
||||
wrong_known = 'wrong-' + uuid.uuid4().hex
|
||||
known = login(client, known_name, wrong_known)
|
||||
unknown_name = 'dos_missing_' + uuid.uuid4().hex
|
||||
wrong_unknown = 'wrong-' + uuid.uuid4().hex
|
||||
unknown = login(client, unknown_name, wrong_unknown)
|
||||
|
||||
check(known['status'] == 401 and unknown['status'] == 401,
|
||||
'known and unknown users did not receive the same 401 class')
|
||||
check(known['json']['error']['code'] == unknown['json']['error']['code'],
|
||||
'known and unknown users received different error codes')
|
||||
check(known['json']['error']['message'] == unknown['json']['error']['message'],
|
||||
'known and unknown users received different error messages')
|
||||
for response in (known, unknown):
|
||||
assert_no_secret(response, known_name, unknown_name, wrong_known, wrong_unknown,
|
||||
known_password)
|
||||
|
||||
return {
|
||||
'known_status': known['status'],
|
||||
'unknown_status': unknown['status'],
|
||||
'error_code': known['json']['error']['code'],
|
||||
'same_message': True,
|
||||
'known_ms': round(known['elapsed'] * 1000, 3),
|
||||
'unknown_ms': round(unknown['elapsed'] * 1000, 3),
|
||||
}
|
||||
|
||||
|
||||
def check_source_budget(args):
|
||||
if args.wait_window > 0:
|
||||
time.sleep(args.wait_window)
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
latencies = []
|
||||
instances = set()
|
||||
for _ in range(args.source_limit):
|
||||
username = 'dos_source_' + uuid.uuid4().hex
|
||||
wrong = 'wrong-' + uuid.uuid4().hex
|
||||
response = login(client, username, wrong)
|
||||
check(response['status'] == 401,
|
||||
'an attempt below the per-source budget was rejected')
|
||||
assert_no_secret(response, username, wrong)
|
||||
latencies.append(response['elapsed'])
|
||||
instances.add(response['headers'].get('X-Instance-Id', ''))
|
||||
|
||||
blocked_username = 'dos_source_blocked_' + uuid.uuid4().hex
|
||||
blocked_wrong = 'wrong-' + uuid.uuid4().hex
|
||||
blocked = login(client, blocked_username, blocked_wrong)
|
||||
check(blocked['status'] == 429, 'attempt above the per-source budget was not rate limited')
|
||||
check(blocked['json']['error']['code'] == 'rate_limited', 'wrong source rate-limit code')
|
||||
retry_after = blocked['headers'].get('Retry-After', '')
|
||||
check(retry_after.isdigit() and 1 <= int(retry_after) <= args.window_seconds,
|
||||
'missing or out-of-window source Retry-After')
|
||||
assert_no_secret(blocked, blocked_username, blocked_wrong)
|
||||
|
||||
return {
|
||||
'limit': args.source_limit,
|
||||
'window_seconds': args.window_seconds,
|
||||
'allowed_under_limit': args.source_limit,
|
||||
'blocked_status': blocked['status'],
|
||||
'retry_after_seconds': int(retry_after),
|
||||
'argon2_path_p50_ms': round(statistics.median(latencies) * 1000, 3),
|
||||
'argon2_path_p95_ms': round(percentile(latencies, 0.95) * 1000, 3),
|
||||
'rate_limited_ms': round(blocked['elapsed'] * 1000, 3),
|
||||
'observed_instances': sorted(instances),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
prefer_ipv4_for_localhost()
|
||||
args = arguments('Shared login rate-limit budget and credential non-disclosure', configure)
|
||||
check(args.username_limit >= 1 and args.source_limit >= args.username_limit,
|
||||
'limits must be positive and source >= username')
|
||||
check(args.window_seconds >= 1, 'window must be positive')
|
||||
|
||||
summary = {
|
||||
'username_budget': check_username_budget(args),
|
||||
'user_enumeration': check_user_enumeration(args),
|
||||
}
|
||||
if args.source_budget:
|
||||
summary['source_budget'] = check_source_budget(args)
|
||||
print(json.dumps(summary, indent=2, sort_keys=True))
|
||||
print('PASS: shared login budget, generic errors and fast rate-limit rejection verified.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user