forked from mtusi2026/mtusi2026lab7
Перенесена реализация lab6; бизнес-API без изменений, транспорт — HTTPS. - Внешний HTTPS (public-ca) на 127.0.0.1:8443; HSTS, TLS >= 1.2. - Обязательное mTLS LB -> каждая API-реплика: API проверяет цепочку internal-ca и SAN клиента (allowlist: lb); health только на 127.0.0.1. - TLS с проверкой сервера ко всем зависимостям: PostgreSQL verify-full (pg_hba только hostssl), HTTPS S3, AMQPS, OTLP/HTTPS с client cert, mTLS Collector -> Prometheus/Loki/Tempo, Grafana -> datasources, scrape. - OpenBao 2.7.2 не в dev-mode: Raft на volume, init/unseal оператором, auth/cert с ролью и policy на сервис, TTL 15 мин + renew/re-login. - Отдельные роли PostgreSQL с грантами по таблицам; разные ключи S3 и пользователи брокера выдаются из OpenBao. - Argon2id (m=19 MiB, t=2, p=1, замер на стенде) и rehash при входе. - Случайный X-Instance-Id; hardening контейнеров (non-root, cap_drop ALL, no-new-privileges, read-only, лимиты); TCP_NODELAY на сокете API. - Модель угроз, trust matrix, отрицательные тесты TLS/mTLS, API, OpenBao, hardening; evidence, в т.ч. прогон из чистого clone.
274 lines
14 KiB
Python
274 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Lab7: положительные и отрицательные проверки TLS/mTLS по contracts/trust-matrix.md.
|
|
|
|
Запуск ВНУТРИ стенда (сервис checks видит сети apinet/backend/telemetry/vault):
|
|
docker compose --profile tools run --rm -T checks /app/student-tests/lab7_tls_matrix.py \
|
|
--output /app/evidence/lab7-tls-matrix.json
|
|
|
|
Для каждой связи различаются причины отказа: ошибка проверки сертификата, отказ handshake
|
|
сервером (нет/чужой client cert), закрытие соединения после handshake (запрещённая identity),
|
|
отказ plaintext. Сетевой timeout НЕ засчитывается как правильный отказ (FAIL).
|
|
|
|
Identities (Docker secrets сервиса checks, только для тестов):
|
|
lb.crt/key — разрешённая identity LB (internal-ca) -> положительный путь к API
|
|
intruder.crt/key — internal-ca, SAN intruder (доверенный CA, чужая роль) -> должен быть отказ
|
|
rogue-lb.crt/key — rogue CA, SAN lb (правильное имя, чужой CA) -> должен быть отказ
|
|
"""
|
|
import argparse
|
|
import json
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
S = "/run/secrets/"
|
|
CA = S + "internal-ca.crt"
|
|
PUBLIC_CA = S + "public-ca.crt"
|
|
ROGUE_CA = S + "rogue-ca.crt"
|
|
ID = {"lb": (S + "lb.crt", S + "lb.key"), "intruder": (S + "intruder.crt", S + "intruder.key"),
|
|
"rogue-lb": (S + "rogue-lb.crt", S + "rogue-lb.key"), None: None}
|
|
RESULTS = []
|
|
|
|
|
|
def ctx(identity=None, cafile=CA, hostname_check=True):
|
|
c = ssl.create_default_context(cafile=cafile)
|
|
c.check_hostname = hostname_check
|
|
c.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
if identity:
|
|
c.load_cert_chain(*ID[identity])
|
|
return c
|
|
|
|
|
|
def classify(exc):
|
|
if isinstance(exc, ssl.SSLCertVerificationError):
|
|
return "server_cert_rejected_by_client:" + (exc.verify_message or "")
|
|
if isinstance(exc, (socket.timeout, TimeoutError)):
|
|
return "TIMEOUT"
|
|
if isinstance(exc, ConnectionRefusedError):
|
|
return "connection_refused"
|
|
if isinstance(exc, ssl.SSLError):
|
|
return "tls_alert:" + (exc.reason or type(exc).__name__)
|
|
if isinstance(exc, (ConnectionResetError, BrokenPipeError)):
|
|
return "reset_by_server"
|
|
if isinstance(exc, socket.gaierror):
|
|
return "dns:" + str(exc)
|
|
return type(exc).__name__ + ":" + str(exc)[:80]
|
|
|
|
|
|
def https_probe(host, port, path, identity=None, server_hostname=None, cafile=CA, ip=None):
|
|
"""TLS + HTTP/1.1 GET. -> ("ok", status) | ("fail", reason)."""
|
|
target = ip or host
|
|
try:
|
|
with socket.create_connection((target, port), timeout=4) as raw:
|
|
with ctx(identity, cafile).wrap_socket(raw, server_hostname=server_hostname or host) as tls:
|
|
req = "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % (path, host)
|
|
tls.sendall(req.encode())
|
|
data = b""
|
|
while True:
|
|
chunk = tls.recv(65536)
|
|
if not chunk:
|
|
break
|
|
data += chunk
|
|
if len(data) > 1 << 20:
|
|
break
|
|
if not data:
|
|
return "fail", "closed_after_handshake_no_http_response"
|
|
status = int(data.split(b" ", 2)[1])
|
|
return "ok", status
|
|
except Exception as exc:
|
|
return "fail", classify(exc)
|
|
|
|
|
|
def plaintext_probe(host, port, payload=b"GET / HTTP/1.1\r\nHost: x\r\n\r\n"):
|
|
"""Plaintext к TLS/закрытому порту: refused или не-HTTP ответ/закрытие = отказ plaintext."""
|
|
try:
|
|
with socket.create_connection((host, port), timeout=4) as s:
|
|
s.sendall(payload)
|
|
s.settimeout(4)
|
|
data = s.recv(200)
|
|
if data.startswith(b"HTTP/") and b" 400" in data[:20] and b"HTTPS" in data:
|
|
return "fail", "http_400_plain_http_sent_to_https_port"
|
|
if data.startswith(b"HTTP/1.") and (b" 200" in data[:16] or b" 401" in data[:16] or b" 404" in data[:16]):
|
|
return "ok", data[:30].decode("latin1")
|
|
if not data:
|
|
return "fail", "closed_without_plaintext_response"
|
|
return "fail", "non_http_or_tls_alert_bytes:%s" % data[:8].hex()
|
|
except Exception as exc:
|
|
return "fail", classify(exc)
|
|
|
|
|
|
def record(link, case, outcome, expect, note=""):
|
|
status, detail = outcome
|
|
passed = (status == expect) and not (status == "fail" and str(detail) == "TIMEOUT")
|
|
RESULTS.append({"link": link, "case": case, "expect": expect, "observed": status, "detail": detail,
|
|
"pass": passed, "note": note})
|
|
print("%s %-28s %-48s expect=%-4s got=%s %s" % ("PASS" if passed else "FAIL", link, case, expect, status, detail))
|
|
|
|
|
|
def api_ips():
|
|
return sorted({ai[4][0] for ai in socket.getaddrinfo("api", 8443, proto=socket.IPPROTO_TCP)})
|
|
|
|
|
|
def check_api():
|
|
ips = api_ips()
|
|
print("API replicas:", len(ips))
|
|
RESULTS.append({"link": "LB->API", "case": "replicas_resolved", "pass": len(ips) >= 2, "detail": len(ips)})
|
|
for i, ip in enumerate(ips):
|
|
link = "LB->API[%d]" % i
|
|
record(link, "no client cert", https_probe("api", 8443, "/health/ready", None, "api", ip=ip), "fail")
|
|
record(link, "client cert of rogue CA, SAN lb", https_probe("api", 8443, "/health/ready", "rogue-lb", "api", ip=ip), "fail")
|
|
record(link, "trusted CA, identity intruder", https_probe("api", 8443, "/health/ready", "intruder", "api", ip=ip), "fail")
|
|
record(link, "plaintext HTTP to 8443", plaintext_probe(ip, 8443), "fail")
|
|
record(link, "health listener 8081 from network", plaintext_probe(ip, 8081), "fail")
|
|
record(link, "server cert, wrong expected hostname", https_probe("api", 8443, "/health/ready", "lb", "db", ip=ip), "fail")
|
|
ok = https_probe("api", 8443, "/health/ready", "lb", "api", ip=ip)
|
|
record(link, "identity lb -> /health/ready", ok, "ok", "status=%s" % (ok[1],))
|
|
biz = https_probe("api", 8443, "/api/v1/users/me", "lb", "api", ip=ip)
|
|
record(link, "identity lb, no Bearer -> business API", biz, "ok",
|
|
"mTLS не заменяет сессию: ожидается 401, получено %s" % (biz[1],))
|
|
if biz[0] == "ok" and biz[1] != 401:
|
|
RESULTS[-1]["pass"] = False
|
|
|
|
|
|
def check_pg():
|
|
import psycopg
|
|
base = dict(host="db", dbname="messenger", user="api_svc", password="wrong-password-for-probe", connect_timeout=4)
|
|
|
|
def attempt(**kw):
|
|
try:
|
|
psycopg.connect(**{**base, **kw}).close()
|
|
return "ok", "connected"
|
|
except psycopg.OperationalError as exc:
|
|
msg = str(exc).lower()
|
|
if "password authentication failed" in msg:
|
|
return "ok", "tls_ok_then_password_rejected"
|
|
if "no pg_hba.conf entry" in msg and "no encryption" in msg:
|
|
return "fail", "pg_hba_reject_plaintext"
|
|
if "certificate verify failed" in msg or "does not match host name" in msg or "server certificate" in msg:
|
|
return "fail", "server_cert_rejected_by_client"
|
|
if "timeout" in msg:
|
|
return "fail", "TIMEOUT"
|
|
return "fail", msg.strip()[:120]
|
|
|
|
record("API/worker->PostgreSQL", "sslmode=disable (plaintext)", attempt(sslmode="disable"), "fail")
|
|
record("API/worker->PostgreSQL", "verify-full, rogue CA as trust", attempt(sslmode="verify-full", sslrootcert=ROGUE_CA), "fail")
|
|
ip = socket.gethostbyname("db")
|
|
record("API/worker->PostgreSQL", "verify-full by IP (SAN mismatch)", attempt(host=ip, sslmode="verify-full", sslrootcert=CA), "fail")
|
|
record("API/worker->PostgreSQL", "verify-full, internal CA, wrong pwd", attempt(sslmode="verify-full", sslrootcert=CA), "ok",
|
|
"TLS проверен; дальше SCRAM отклоняет неверный пароль")
|
|
|
|
|
|
def check_s3():
|
|
record("API/worker->S3", "plaintext HTTP", plaintext_probe("s3", 8333), "fail")
|
|
record("API/worker->S3", "HTTPS, rogue CA as trust", https_probe("s3", 8333, "/", cafile=ROGUE_CA), "fail")
|
|
anon = https_probe("s3", 8333, "/messenger-attachments/")
|
|
record("API/worker->S3", "HTTPS verified, anonymous list", anon, "ok", "TLS ok; анонимно: %s (ожидается 403)" % (anon[1],))
|
|
if anon[0] == "ok" and anon[1] not in (401, 403):
|
|
RESULTS[-1]["pass"] = False
|
|
|
|
|
|
def amqp_tls(identity=None, cafile=CA):
|
|
try:
|
|
with socket.create_connection(("broker", 5671), timeout=4) as raw:
|
|
with ctx(identity, cafile).wrap_socket(raw, server_hostname="broker") as tls:
|
|
tls.sendall(b"AMQP\x00\x00\x09\x01")
|
|
data = tls.recv(16)
|
|
return ("ok", "amqp_connection_start") if data[:1] == b"\x01" else ("fail", data[:8].hex())
|
|
except Exception as exc:
|
|
return "fail", classify(exc)
|
|
|
|
|
|
def check_broker():
|
|
record("API/worker->broker", "plaintext AMQP 5672", plaintext_probe("broker", 5672, b"AMQP\x00\x00\x09\x01"), "fail")
|
|
record("API/worker->broker", "AMQPS, rogue CA as trust", amqp_tls(cafile=ROGUE_CA), "fail")
|
|
record("API/worker->broker", "AMQPS, client cert of rogue CA", amqp_tls(identity="rogue-lb"), "fail",
|
|
"verify_peer: предъявленный чужой сертификат отвергается")
|
|
record("API/worker->broker", "AMQPS verified (без cert), Connection.Start", amqp_tls(), "ok",
|
|
"далее аутентификация паролем + ACL vhost (проверка прав — broker_permissions)")
|
|
try:
|
|
import pika
|
|
params = pika.ConnectionParameters(host="broker", port=5671, virtual_host="messenger",
|
|
credentials=pika.PlainCredentials("worker", "wrong-password"),
|
|
ssl_options=pika.SSLOptions(ctx(), server_hostname="broker"),
|
|
connection_attempts=1, socket_timeout=4)
|
|
pika.BlockingConnection(params).close()
|
|
out = ("ok", "LOGIN_ACCEPTED")
|
|
except pika.exceptions.ProbableAuthenticationError:
|
|
out = ("fail", "auth_refused")
|
|
except Exception as exc:
|
|
out = ("fail", type(exc).__name__)
|
|
record("API/worker->broker", "AMQPS, user worker, wrong password", out, "fail")
|
|
record("Prometheus->broker metrics", "HTTPS 15691 without client cert", https_probe("broker", 15691, "/metrics"), "fail")
|
|
record("Prometheus->broker metrics", "plaintext 15692 from network", plaintext_probe("broker", 15692), "fail")
|
|
|
|
|
|
def check_telemetry():
|
|
for host, port, link in (("otel-collector", 4318, "API/worker->Collector"),
|
|
("prometheus", 9090, "Collector/Grafana->Prometheus"),
|
|
("loki", 3100, "Collector/Grafana->Loki"),
|
|
("tempo", 3200, "Grafana->Tempo"),
|
|
("tempo", 4317, "Collector->Tempo OTLP gRPC"),
|
|
("lb", 8404, "Prometheus->LB metrics")):
|
|
record(link, "plaintext", plaintext_probe(host, port), "fail")
|
|
record(link, "TLS without client cert", https_probe(host, port, "/", None), "fail")
|
|
record(link, "TLS, client cert of rogue CA", https_probe(host, port, "/", "rogue-lb"), "fail")
|
|
record(link, "TLS, wrong expected hostname", https_probe(host, port, "/", "intruder", server_hostname="api"), "fail")
|
|
for host, port in (("otel-collector", 4317), ("otel-collector", 8888), ("otel-collector", 13133), ("loki", 9095), ("tempo", 9096)):
|
|
record("internal-only port", "%s:%d from network" % (host, port), plaintext_probe(host, port), "fail")
|
|
# Уровень 3: Collector/backends проверяют CA, но не роль клиента -> intruder (internal-ca) принят.
|
|
got = https_probe("otel-collector", 4318, "/v1/logs", "intruder")
|
|
RESULTS.append({"link": "API/worker->Collector", "case": "trusted CA, foreign identity (intruder)",
|
|
"expect": "documented", "observed": got[0], "detail": got[1], "pass": True,
|
|
"note": "level 3: CA-only mTLS; разграничение identity — уровень 4 (см. trust-matrix)"})
|
|
print("INFO API/worker->Collector intruder cert:", got)
|
|
|
|
|
|
def bao_login(identity):
|
|
c = ctx(identity)
|
|
req = urllib.request.Request("https://openbao:8200/v1/auth/cert/login", data=b'{"name":"api"}', method="POST",
|
|
headers={"Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=4, context=c) as r:
|
|
return "ok", r.status
|
|
except urllib.error.HTTPError as exc:
|
|
return "fail", "http_%d" % exc.code
|
|
except Exception as exc:
|
|
return "fail", classify(getattr(exc, "reason", exc))
|
|
|
|
|
|
def check_openbao():
|
|
record("services->OpenBao", "plaintext HTTP", plaintext_probe("openbao", 8200), "fail")
|
|
record("services->OpenBao", "TLS, rogue CA as trust", https_probe("openbao", 8200, "/v1/sys/health", cafile=ROGUE_CA), "fail")
|
|
record("services->OpenBao", "TLS verified, /v1/sys/health", https_probe("openbao", 8200, "/v1/sys/health"), "ok")
|
|
record("services->OpenBao", "cert login as role api with intruder cert", bao_login("intruder"), "fail")
|
|
record("services->OpenBao", "cert login as role api with lb cert", bao_login("lb"), "fail",
|
|
"сертификат того же CA, но SAN не api -> роль не подходит")
|
|
record("services->OpenBao", "cert login without client cert", bao_login(None), "fail")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--output")
|
|
args = ap.parse_args()
|
|
started = time.time()
|
|
for fn in (check_api, check_pg, check_s3, check_broker, check_telemetry, check_openbao):
|
|
try:
|
|
fn()
|
|
except Exception as exc:
|
|
RESULTS.append({"link": fn.__name__, "case": "crashed", "pass": False, "detail": repr(exc)[:200]})
|
|
print("FAIL", fn.__name__, repr(exc)[:200])
|
|
failed = [r for r in RESULTS if not r.get("pass")]
|
|
summary = {"checked_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(started)),
|
|
"total": len(RESULTS), "failed": len(failed), "results": RESULTS}
|
|
if args.output:
|
|
with open(args.output, "w") as f:
|
|
json.dump(summary, f, ensure_ascii=False, indent=1)
|
|
print("%s: %d checks, %d failed" % ("PASS" if not failed else "FAIL", len(RESULTS), len(failed)))
|
|
sys.exit(1 if failed else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|