Files
mtusi2026lab7-safronov/evidence/security/mtls-lb-api.md
T
2026-11-17 04:49:45 +03:00

145 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# mTLS LB → API: отрицательные проверки (change `pki-ingress-mtls`)
Спек `transport-security`: «Обязательное mTLS балансировщика к репликам», «Allowlist identity
клиента реплики», «Отрицательные проверки LB → API одной командой»; design, решение 12. Путь
репозитория — `<repo>`.
Код приложения на момент съёмки:
- «Штатный стенд — код 0» — 2026-11-17, `2649eb2` (правки verify: строка S1 драйвера, порт
health одним источником W1, срок ответа слушателя health S2); рабочее дерево отличалось от
него только документами и строкой справки драйвера;
- «Расхождение называется — код 1» и «Уборка при Ctrl+C» — 2026-11-16, код приложения и стенда
как в `50cb54f` (рабочее дерево поверх `4759f71`; `src/`, compose, `infra/`, `scripts/` с
`4759f71` до `50cb54f` не менялись), драйвер — до строки S1.
Команда — `make mtls_check` (`driver.py --ca-file <CA стенда> --port 8443 mtls-check`). Проба —
одноразовый контейнер на образе API (`python` и `ssl` образа) в сети стенда, к каждой реплике по
её адресу с проверкой сервера (CA стенда, hostname `api`). Материалы — во временном каталоге
хоста (0700), смонтированном только в пробу:
- `stand/` — копии `ca.crt`, `haproxy.pem`, `ingress.pem` стенда;
- `probe/mtls-probe.pem` — `pki.sh issue mtls-probe --profile client --san mtls-probe --days 1
--bundle` (CA стенда, identity вне allowlist);
- `other/haproxy.pem` — `pki.sh init` во временный каталог оператора (другой CA) и `issue haproxy
--profile client --san haproxy --days 1`; ключ временного CA удаляется до запуска пробы.
## Штатный стенд — код 0
Реплики `make run_docker` (`API_TLS__ALLOWED_CLIENTS=["haproxy"]`), 2 шт.:
```
$ make mtls_check
python3 .claude/skills/run-mtusi-messenger/driver.py --ca-file "<repo>/.pki/stand/ca.crt" --port 8443 mtls-check
stand network mtusi-lab7_default, API image mtusi-messenger:lab7, replicas 2, API port 8080
replica 67c6a50d6592a774: no client certificate: no HTTP (closed: closed after handshake)
replica 67c6a50d6592a774: certificate of another CA (SAN haproxy): no HTTP (closed: closed after handshake)
replica 67c6a50d6592a774: forbidden identity of the stand CA (mtls-probe): no HTTP (closed: closed after handshake)
replica 67c6a50d6592a774: server certificate of the stand CA (ingress): no HTTP (closed: closed after handshake)
replica 67c6a50d6592a774: HTTP without TLS: no HTTP (closed: 0 bytes, no HTTP)
replica cccacf9b0540977e: no client certificate: no HTTP (closed: closed after handshake)
replica cccacf9b0540977e: certificate of another CA (SAN haproxy): no HTTP (closed: closed after handshake)
replica cccacf9b0540977e: forbidden identity of the stand CA (mtls-probe): no HTTP (closed: closed after handshake)
replica cccacf9b0540977e: server certificate of the stand CA (ingress): no HTTP (closed: closed after handshake)
replica cccacf9b0540977e: HTTP without TLS: no HTTP (closed: 0 bytes, no HTTP)
foreign server 192.168.176.13: LB slot DOWN
20 requests through LB: {'200 67c6a50d6592a774': 10, '200 cccacf9b0540977e': 10}
replica 67c6a50d6592a774: no client certificate expected no HTTP got no HTTP
replica 67c6a50d6592a774: certificate of another CA (SAN haproxy) expected no HTTP got no HTTP
replica 67c6a50d6592a774: forbidden identity of the stand CA (mtls-probe) expected no HTTP got no HTTP
replica 67c6a50d6592a774: server certificate of the stand CA (ingress) expected no HTTP got no HTTP
replica 67c6a50d6592a774: HTTP without TLS expected no HTTP got no HTTP
replica 67c6a50d6592a774: allowed identity haproxy expected HTTP 200 TLSv1.3 got HTTP 200 TLSv1.3
replica 67c6a50d6592a774: X-Instance-Id = alias from its log expected 67c6a50d6592a774 got 67c6a50d6592a774
replica 67c6a50d6592a774: 'Rejected TLS client' with mtls-probe expected yes got yes
replica 67c6a50d6592a774: no 'Rejected TLS client' except mtls-probe (others fail at handshake) expected none got none
replica cccacf9b0540977e: no client certificate expected no HTTP got no HTTP
replica cccacf9b0540977e: certificate of another CA (SAN haproxy) expected no HTTP got no HTTP
replica cccacf9b0540977e: forbidden identity of the stand CA (mtls-probe) expected no HTTP got no HTTP
replica cccacf9b0540977e: server certificate of the stand CA (ingress) expected no HTTP got no HTTP
replica cccacf9b0540977e: HTTP without TLS expected no HTTP got no HTTP
replica cccacf9b0540977e: allowed identity haproxy expected HTTP 200 TLSv1.3 got HTTP 200 TLSv1.3
replica cccacf9b0540977e: X-Instance-Id = alias from its log expected cccacf9b0540977e got cccacf9b0540977e
replica cccacf9b0540977e: 'Rejected TLS client' with mtls-probe expected yes got yes
replica cccacf9b0540977e: no 'Rejected TLS client' except mtls-probe (others fail at handshake) expected none got none
foreign server under alias api: seen by LB, slot not UP expected yes got yes
20 requests through LB answered by stand replicas expected yes got yes
foreign server: HTTP requests received expected 0 got 0
control replica (allowlist with the probe) healthy expected yes got yes
control replica: mtls-probe accepted expected HTTP 200 got HTTP 200
PASS: replicas accept only the haproxy identity of the stand CA; a foreign server under the name api gets no requests; the probe tells an allowed identity from a forbidden one
cleanup: 2 probe container(s) removed, temporary key directory removed: True
exit 0
```
Как читать исходы:
- «closed after handshake» — рукопожатие клиента TLS 1.3 закончилось, а сервер закрыл
соединение до запроса. Без сертификата, с чужим CA и с серверным сертификатом (`ingress`:
EKU `serverAuth`, purpose `sslclient` не проходит) отказ — в рукопожатии на стороне сервера:
asyncio вне debug его не пишет, алерта клиент до закрытия не прочёл. Запрещённая identity
`mtls-probe` рукопожатие проходит, и реплика закрывает соединение в протоколе. Различают их
две строки по журналу каждой реплики с начала прогона: запись «Rejected TLS client» с
`client_identity: ["mtls-probe"]` есть, а других записей «Rejected TLS client» нет (`none`;
иначе в `got` — их `client_identity`). Значит, четыре прочих отказа случились до протокола
allowlist, в рукопожатии (verify S1);
- HTTP без TLS — ни байта HTTP-ответа;
- `haproxy` — 200 по TLS 1.3, `X-Instance-Id` = alias реплики из её журнала;
- чужой сервер — контейнер на образе API с алиасом сети `api` и сертификатом `ingress` (SAN
`localhost`, без `api`): LB увидел его адрес в слоте, слот `DOWN` (`verifyhost api`), 20
запросов через LB ответили штатные реплики, у сервера 0 HTTP-запросов;
- контрольная реплика — `docker compose run --rm --no-deps api` с
`API_TLS__ALLOWED_CLIENTS=["haproxy","mtls-probe"]` (без алиаса сети, LB её не видит): та же
проба `mtls-probe` получает 200 — проба различает разрешённое и запрещённое, тест не пустой.
Ключевого материала в выводе нет: `grep -c 'PRIVATE KEY\|BEGIN '` по выводу всех прогонов
этой проверки — 0.
## Расхождение называется — код 1
Реплики временно пересозданы с allowlist, допускающим пробу (override в scratchpad, `docker
compose -f docker-compose.yml -f <tmp>/allow-probe.compose.yml up -d --no-deps --wait api`):
```
$ make mtls_check
…
replica d8f8345871d8a7bb: forbidden identity of the stand CA (mtls-probe) expected no HTTP got HTTP 200 TLSv1.3 FAIL
replica d8f8345871d8a7bb: 'Rejected TLS client' with mtls-probe expected yes got no FAIL
replica 6221ce44e26a43cd: forbidden identity of the stand CA (mtls-probe) expected no HTTP got HTTP 200 TLSv1.3 FAIL
replica 6221ce44e26a43cd: 'Rejected TLS client' with mtls-probe expected yes got no FAIL
FAIL: 4 check(s) failed
cleanup: 2 probe container(s) removed, temporary key directory removed: True
make: *** [mtls_check] Error 1
```
Затем `make run_docker` вернул штатный allowlist (`API_TLS__ALLOWED_CLIENTS=["haproxy"]` у обеих
реплик).
## Уборка при Ctrl+C
SIGINT драйверу посреди прогона (через 9 с: идут пробы реплик, жив контейнер пробы) и через 14 с
(живы чужой сервер и контрольная реплика):
```
containers during run: 1
exit 1
replica 6221ce44e26a43cd: HTTP without TLS: no HTTP (closed: 0 bytes, no HTTP)
mtls-check: interrupted ()
cleanup: 1 probe container(s) removed, temporary key directory removed: True
left containers: 0
left dirs: []
containers during run: ['cdc137d2c4fc', '19c1fc16be2d']
…
foreign server 192.168.176.13: LB slot DOWN
cleanup: 2 probe container(s) removed, temporary key directory removed: True
left containers: 0
left dirs: []
```
`left containers` — `docker ps -aq --filter label=mtusi.mtls-check`, `left dirs` — каталоги
`mtusi-mtls-check-*` во временном каталоге системы. Во втором прогоне (первая версия команды)
прерывание печатало traceback `KeyboardInterrupt` после уборки; теперь — одна строка
«mtls-check: interrupted» и код 1 (в первом прогоне выше — ещё пустые скобки вместо причины,
исправлено на `SIGINT`).