Files
mtusi2026lab7-safronov/infra/audit/audit.py
T
ricoromaandClaude Opus 5.5 7b2defab01 feat: audit the whole trust matrix in one command and complete the threat model
- make security_audit runs the existing negative checks per trust-matrix
  row plus an ingress TLS probe and prints one summary
- close the threat model TODOs and stale references
- re-take the coverage exclusion evidence on the lab 7 stand

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 07:08:10 +03:00

611 lines
23 KiB
Python
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.
#!/usr/bin/env python3
"""Аудит матрицы доверия одной командой: make security_audit [REPORT=1].
Каждая строка `contracts/trust-matrix.md` (столбец «Связь») — строка сводки
с проверками, которые её доказывают: TLS (версия, проверка сертификата,
отказ открытого текста и чужого CA), identity и ACL (роли PostgreSQL, ACL
Valkey, права брокера, политики OpenBao, префиксы S3). Ещё три строки вне
таблицы — каналы scrape / health / bootstrap, ограничения контейнеров и
утечки в телеметрии (секреты, токены, тела в журнале, трассах и метриках).
Логики проверок здесь нет: команды драйвера скилла run-mtusi-messenger
(`mtls-check`, `storage-tls-check`, `storage-roles-check`, `s3-check`,
`broker-mtls-check`, `telemetry-tls-check`, `openbao-check`,
`hardening-check`, `auth-storage`, `telemetry-check`) и публичный
`tests/security.py` идут подпроцессами по одной, каждая — один раз, их коды
0 / 1 / 2 сводятся по строкам. Своя проба — только внешний TLS ingress
(`ingress-tls`): доверенный CA и `localhost` — 200; пустое хранилище корней и
`127.0.0.1` — ошибка проверки сертификата; HTTP без TLS — нет ответа HTTP;
TLS 1.1 — отказ сервера `protocol version`.
У `telemetry-check` для строки утечек берутся только строки пробы
приватности (`… in telemetry`, проба нашла записи и трассы); остальные его
расхождения названы в примечании строки и вердикт утечек не меняют.
Что аудит не проверяет (меняет стенд или нужен особый стенд) — поле «вне
аудита» строки: ротация и отзыв (`make rotation_check`), сессии и предел
входа (`make student_test`, `make failure_checks`), scan (`make scan`).
Коды: 0 — все проверки прошли; 1 — есть нарушение (FAIL); 2 — проверка не
выполнена (стенда нет, сбой окружения) при отсутствии FAIL; 130 — сигнал.
`--report` — та же сводка без вердикта, код 0. `--only a,b` — только эти
проверки (остальные — «not run»), `--logs DIR` — сохранить вывод каждой.
Только stdlib и синтаксис Python 3.9 (системный python3, как драйвер).
Секретов команда не читает и не печатает: в выводе — имена проверок, коды,
секунды и строки FAIL проверок (они секретов не печатают).
"""
# аннотации — строками: системный python3 3.9 `X | None` не вычисляет
from __future__ import annotations
import argparse
import os
import re
import shutil
import signal
import socket
import ssl
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
import warnings
from pathlib import Path
from typing import NamedTuple
ROOT = Path(__file__).resolve().parents[2]
DRIVER = ROOT / ".claude" / "skills" / "run-mtusi-messenger" / "driver.py"
SECURITY_PY = ROOT / "tests" / "security.py"
MATRIX = ROOT / "contracts" / "trust-matrix.md"
# предел одной проверки: самая долгая (hardening-check) — минуты
CHECK_TIMEOUT_S = 1800
PROBE_TIMEOUT_S = 5.0
class Edge(NamedTuple):
"""Строка сводки: связь, (что доказывает, проверка), что вне аудита."""
name: str
checks: tuple[tuple[str, str], ...]
outside: str = ""
# строки таблицы contracts/trust-matrix.md — имена дословно из столбца
# «Связь» (быстрый тест test_security_audit.py: лишняя или недостающая —
# красный)
MATRIX_EDGES: tuple[Edge, ...] = (
Edge(
"Клиент → ingress/LB",
(
("TLS ≥ 1.2, CA и hostname, нет HTTP", "ingress-tls"),
("пустое хранилище корней — отказ", "test-security"),
("журнал API без credentials", "auth-storage"),
),
"сессии, предел входа, предел тела — make student_test, "
"make failure_checks; ротация ingress — make rotation_check",
),
Edge(
"LB → API (все реплики)",
(("mTLS 1.3, allowlist haproxy, чужой сервер api", "mtls-check"),),
"ротация leaf haproxy / api — make rotation_check",
),
Edge(
"API/worker → PostgreSQL",
(
("TLS 1.3 verify-full, нет hostnossl", "storage-tls-check"),
(
"роли процессов = матрица, DDL и чужое — 42501",
"storage-roles-check",
),
("пароль роли только из OpenBao", "openbao-check"),
),
"ротация пароля — make rotation_check",
),
Edge(
"API/worker → S3",
(
("HTTPS, чужой CA и имя — отказ", "storage-tls-check"),
("пользователи и префиксы, gRPC шлюза mTLS", "s3-check"),
("ключи только из OpenBao", "openbao-check"),
),
"ротация ключа — make rotation_check",
),
Edge(
"API/worker → broker",
(("mTLS 1.3, EXTERNAL, права relay / worker", "broker-mtls-check"),),
"отзыв identity брокера — make rotation_check",
),
Edge(
"API/worker → Collector",
(
(
"mTLS шлюза OTLP, allowlist api / worker / relay",
"telemetry-tls-check",
),
),
),
Edge(
"Collector → telemetry backends",
(("mTLS шлюзов, allowlist и права по пути", "telemetry-tls-check"),),
),
Edge(
"Grafana → data sources",
(("grafana-client только чтение", "telemetry-tls-check"),),
),
Edge(
"API/worker/agent → OpenBao",
(("mTLS, cert auth, политика на процесс", "openbao-check"),),
"отзыв токенов и CRL под нагрузкой — make rotation_check",
),
Edge(
"Оператор → OpenBao/Grafana/S3 admin",
(
(
"OpenBao на 127.0.0.1, root token не у сервисов",
"openbao-check",
),
("Grafana только HTTPS на 127.0.0.1", "telemetry-tls-check"),
("служебные порты S3 из сети закрыты", "s3-check"),
("CLI брокера только на loopback", "broker-mtls-check"),
("публикации только 127.0.0.1", "hardening-check"),
),
),
Edge(
"API → Redis/Valkey, если используется",
(
("TLS 1.3, нет порта без TLS", "storage-tls-check"),
("ACL api, default off", "storage-roles-check"),
),
"ротация пароля — make rotation_check",
),
Edge(
"Replication/кластерные каналы, если добавлены",
(
("N/A: raft OpenBao 8201 из сети закрыт", "openbao-check"),
("N/A: master / filer S3 на loopback", "s3-check"),
),
),
)
# строки вне таблицы: каналы под ней, контейнеры, утечки в телеметрии
EXTRA_EDGES: tuple[Edge, ...] = (
Edge(
"Каналы scrape, health и bootstrap",
(
(":8404 LB, :8888 / :8889, :8405, :14318", "telemetry-tls-check"),
("health 8210 OpenBao из сети закрыт", "openbao-check"),
("распределение Erlang на loopback", "broker-mtls-check"),
("слушатели хранилищ вне loopback", "storage-tls-check"),
("слушатели всех контейнеров = список", "hardening-check"),
),
),
Edge(
"Контейнеры: capabilities, root, корень, pids",
(("docker inspect, процессы, EROFS, pids", "hardening-check"),),
"уязвимости образов — make scan",
),
Edge(
"Утечки в телеметрии",
(
(
"Loki, Tempo, Prometheus без credentials и тел",
"telemetry-leaks",
),
("журнал API без credentials", "auth-storage"),
("аудит OpenBao без токенов", "openbao-check"),
),
),
)
EDGES = MATRIX_EDGES + EXTRA_EDGES
# команды драйвера (аргументы после глобальных --ca-file / --port)
DRIVER_CHECKS: dict[str, tuple[str, ...]] = {
"mtls-check": ("mtls-check",),
"storage-tls-check": ("storage-tls-check",),
"storage-roles-check": ("storage-roles-check",),
"s3-check": ("s3-check",),
"broker-mtls-check": ("broker-mtls-check",),
"telemetry-tls-check": ("telemetry-tls-check",),
"openbao-check": ("openbao-check",),
"auth-storage": ("auth-storage",),
"telemetry-leaks": ("telemetry-check",),
"hardening-check": ("hardening-check",),
}
# порядок: дешёвые сначала; telemetry-check перезапускает хранилища
# телеметрии, hardening-check читает журналы — последними
ORDER = (
"ingress-tls",
"test-security",
"mtls-check",
"storage-tls-check",
"storage-roles-check",
"s3-check",
"broker-mtls-check",
"telemetry-tls-check",
"openbao-check",
"auth-storage",
"telemetry-leaks",
"hardening-check",
)
CHECKS = frozenset(ORDER)
# строки пробы приватности telemetry-check
LEAK_ROW = re.compile(r"^\S.* in telemetry\s+expected ")
PROBE_ROW = re.compile(r"^privacy probe: (\d+) Loki records, (\d+) traces")
class Result(NamedTuple):
code: int
seconds: float
fails: tuple[str, ...] = ()
note: str = ""
def matrix_edges(path: Path = MATRIX) -> list[str]:
"""Столбец «Связь» основной таблицы матрицы доверия."""
lines = path.read_text(encoding="utf-8").splitlines()
edges: list[str] = []
inside = False
for line in lines:
if line.startswith("| Связь |"):
inside = True
continue
if not inside:
continue
if not line.startswith("|"):
break
cell = line.split("|")[1].strip()
if cell and not set(cell) <= set("-: "):
edges.append(cell)
return edges
def coverage_problems(
matrix: list[str],
edges: tuple[Edge, ...] = MATRIX_EDGES,
) -> list[str]:
"""Строки матрицы без строки сводки и наоборот; неизвестные проверки."""
names = [edge.name for edge in edges]
problems = [
f"matrix row without audit row: {n}" for n in matrix if n not in names
]
problems += [
f"audit row not in matrix: {n}" for n in names if n not in matrix
]
problems += [
f"unknown check {check} in row {edge.name}"
for edge in edges + EXTRA_EDGES
for _, check in edge.checks
if check not in CHECKS
]
problems += [
f"row without checks: {edge.name}" for edge in edges if not edge.checks
]
return problems
def fail_lines(output: str) -> tuple[str, ...]:
"""Строки вывода проверки с признаком нарушения."""
return tuple(
line.strip()
for line in output.splitlines()
if line.rstrip().endswith("FAIL") or line.startswith("FAIL")
)
def leaks_result(code: int, output: str, seconds: float) -> Result:
"""Строка утечек из вывода telemetry-check: только проба приватности."""
if code not in (0, 1):
return Result(
2,
seconds,
fail_lines(output),
"telemetry-check: no verdict",
)
probe = next(
(m for m in map(PROBE_ROW.match, output.splitlines()) if m),
None,
)
rows = [line for line in output.splitlines() if LEAK_ROW.match(line)]
if probe is None or not rows:
return Result(2, seconds, (), "privacy probe not reached")
if int(probe.group(1)) == 0 or int(probe.group(2)) == 0:
return Result(2, seconds, (), "privacy probe found no records")
leaked = tuple(
line.strip() for line in rows if line.rstrip().endswith("FAIL")
)
others = tuple(
line
for line in fail_lines(output)
if line not in leaked and not line.startswith("FAIL:")
)
note = f"{len(rows)} needles in {probe.group(1)} records, {probe.group(2)} traces"
if others:
note += "; other telemetry-check rows FAIL: " + "; ".join(
line.split(" expected")[0].strip() for line in others
)
return Result(1 if leaked else 0, seconds, leaked, note)
def tls_error(context: ssl.SSLContext, host: str, port: int, name: str) -> str:
"""Причина отказа рукопожатия или «ok»."""
try:
with (
socket.create_connection(
(host, port),
timeout=PROBE_TIMEOUT_S,
) as raw,
context.wrap_socket(raw, server_hostname=name),
):
return "ok"
except ssl.SSLCertVerificationError as exc:
return f"verify: {exc.verify_message}"
except ssl.SSLError as exc:
return f"tls: {exc.reason}"
except OSError as exc:
return f"os: {exc.__class__.__name__}"
def plain_http_answer(port: int) -> str:
"""Первые байты ответа на HTTP без TLS (пусто — ответа нет)."""
try:
with socket.create_connection(
("127.0.0.1", port),
timeout=PROBE_TIMEOUT_S,
) as s:
s.sendall(b"GET /health/ready HTTP/1.1\r\nHost: localhost\r\n\r\n")
data = s.recv(64)
except OSError:
return ""
return data.decode("latin-1")
def ingress_rows(port: int, ca_file: str) -> list[tuple[str, str, str]]:
"""Проба внешнего TLS: (проверка, ожидаемо, получено)."""
rows: list[tuple[str, str, str]] = []
trusted = ssl.create_default_context(cafile=ca_file)
url = f"https://localhost:{port}/health/ready"
try:
with urllib.request.urlopen(
url,
context=trusted,
timeout=PROBE_TIMEOUT_S,
) as r:
status = str(r.status)
except urllib.error.HTTPError as exc:
status = str(exc.code)
except (urllib.error.URLError, OSError) as exc:
status = f"error {exc.__class__.__name__}"
rows.append(("stand CA, localhost: /health/ready", "200", status))
empty = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
got = tls_error(empty, "127.0.0.1", port, "localhost")
rows.append(("empty trust store", "verify", got.split(":")[0]))
got = tls_error(trusted, "127.0.0.1", port, "127.0.0.1")
rows.append(
(
"stand CA, name 127.0.0.1",
"hostname mismatch",
"hostname mismatch" if "mismatch" in got.lower() else got,
),
)
answer = plain_http_answer(port)
rows.append(
(
"HTTP without TLS",
"no HTTP response",
"HTTP response"
if answer.startswith("HTTP/")
else "no HTTP response",
),
)
old = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
old.load_verify_locations(ca_file)
# TLS 1.1 у клиента разрешён понижением уровня безопасности: отказ —
# alert сервера, а не локальная библиотека
old.set_ciphers("DEFAULT:@SECLEVEL=0")
with warnings.catch_warnings():
# TLSv1_1 объявлен устаревшим — он и нужен пробе
warnings.simplefilter("ignore", DeprecationWarning)
old.minimum_version = ssl.TLSVersion.TLSv1_1
old.maximum_version = ssl.TLSVersion.TLSv1_1
got = tls_error(old, "127.0.0.1", port, "localhost")
rows.append(
(
"TLS 1.1 only",
"protocol version alert",
"protocol version alert"
if "PROTOCOL_VERSION" in got.upper()
else got,
),
)
return rows
def run_ingress(port: int, ca_file: str, log: Path | None) -> Result:
started = time.monotonic()
rows = ingress_rows(port, ca_file)
text = "\n".join(
f"{name:<36} expected {exp:<24} got {got}"
+ ("" if exp == got else " FAIL")
for name, exp, got in rows
)
if log is not None:
log.write_text(text + "\n", encoding="utf-8")
seconds = time.monotonic() - started
if rows[0][2].startswith("error"):
return Result(2, seconds, (), f"no stand on https://localhost:{port}")
return Result(1 if fail_lines(text) else 0, seconds, fail_lines(text))
def run_process(argv: list[str], log: Path | None) -> tuple[int, str, float]:
started = time.monotonic()
proc = subprocess.Popen(
argv,
cwd=ROOT,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
start_new_session=True,
)
try:
output, _ = proc.communicate(timeout=CHECK_TIMEOUT_S)
code = proc.returncode
except subprocess.TimeoutExpired:
# SIGINT — проверки драйвера убирают свои контейнеры в finally
os.killpg(proc.pid, signal.SIGINT)
output, _ = proc.communicate()
output += f"\naudit: timeout {CHECK_TIMEOUT_S} s\n"
code = 2
except KeyboardInterrupt:
os.killpg(proc.pid, signal.SIGINT)
proc.communicate()
raise
if log is not None:
log.write_text(output, encoding="utf-8")
return code, output, time.monotonic() - started
def run_check(name: str, port: int, ca_file: str, logs: Path | None) -> Result:
log = logs / f"{name}.log" if logs is not None else None
if name == "ingress-tls":
return run_ingress(port, ca_file, log)
if name == "test-security":
argv = [
sys.executable,
str(SECURITY_PY),
"--base-url",
f"https://localhost:{port}",
"--ca-file",
ca_file,
]
else:
argv = [
sys.executable,
str(DRIVER),
"--ca-file",
ca_file,
"--port",
str(port),
*DRIVER_CHECKS[name],
]
code, output, seconds = run_process(argv, log)
if name == "telemetry-leaks":
return leaks_result(code, output, seconds)
if name == "test-security":
# публичный скрипт: 0 — PASS, иначе сообщение FAIL / ошибка стенда
last = output.strip().splitlines()[-1:] or [""]
return Result(
0 if code == 0 else 1,
seconds,
() if code == 0 else tuple(last),
)
return Result(code if code in (0, 1) else 2, seconds, fail_lines(output))
def row_verdict(edge: Edge, results: dict[str, Result]) -> str:
codes = [results[c].code for _, c in edge.checks if c in results]
if not codes:
return "not run"
if 1 in codes:
return "FAIL"
if any(code != 0 for code in codes):
return "ERROR"
if len(codes) < len(edge.checks):
return "PASS (partial)"
return "PASS"
def print_summary(results: dict[str, Result]) -> None:
print("\nsummary: matrix row → check → result", flush=True)
for title, edges in (
("trust matrix", MATRIX_EDGES),
("outside the table", EXTRA_EDGES),
):
print(f"\n[{title}]")
for edge in edges:
print(f"{edge.name}: {row_verdict(edge, results)}")
for aspect, check in edge.checks:
result = results.get(check)
got = (
"not run"
if result is None
else {0: "PASS", 1: "FAIL"}.get(result.code, "ERROR")
)
print(f" - {aspect} → {check}: {got}")
if edge.outside:
print(f" outside the audit: {edge.outside}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--port", type=int, default=8443)
parser.add_argument("--ca-file", required=True)
parser.add_argument("--report", action="store_true")
parser.add_argument("--only", default="")
parser.add_argument("--logs")
args = parser.parse_args()
problems = coverage_problems(matrix_edges())
if problems:
print("\n".join(problems))
return 2
only = [c for c in args.only.split(",") if c]
unknown = [c for c in only if c not in CHECKS]
if unknown:
print(
f"unknown checks: {', '.join(unknown)}; known: {', '.join(ORDER)}",
)
return 2
if not Path(args.ca_file).is_file():
print(f"no CA file {args.ca_file}: make pki_stand")
return 2
logs: Path | None = None
temp: Path | None = None
if args.logs:
logs = Path(args.logs).resolve()
logs.mkdir(parents=True, exist_ok=True)
else:
temp = Path(tempfile.mkdtemp(prefix="mtusi-audit-"))
logs = temp
results: dict[str, Result] = {}
try:
for name in ORDER:
if only and name not in only:
continue
print(f"check {name} ...", flush=True)
result = run_check(name, args.port, args.ca_file, logs)
results[name] = result
verdict = {0: "PASS", 1: "FAIL"}.get(result.code, "ERROR")
line = f"check {name}: {verdict} (code {result.code}, {result.seconds:.0f} s)"
if result.note:
line += f"; {result.note}"
print(line, flush=True)
for fail in result.fails[:20]:
print(f" {fail}", flush=True)
except KeyboardInterrupt:
print("audit interrupted", flush=True)
return 130
finally:
if temp is not None:
shutil.rmtree(temp, ignore_errors=True)
print_summary(results)
if args.logs:
print(f"\nlogs: {logs}")
codes = {r.code for r in results.values()}
code = 1 if 1 in codes else 2 if codes - {0} else 0
if args.report:
print(f"\nREPORT: verdict not applied (would be code {code})")
return 0
print(
"\nPASS: every matrix row is proven by its checks"
if code == 0
else f"\n{'FAIL' if code == 1 else 'ERROR'}: audit code {code}",
)
return code
if __name__ == "__main__":
sys.exit(main())