356 lines
21 KiB
Python
356 lines
21 KiB
Python
"""lab7: TLS-аудит всей матрицы доверия — «кто ты» (contracts/trust-matrix.md, пункты 1–3).
|
||
|
||
make tls-matrix (контейнер sectest в сетях edge, backend, otlp, telemetry, vault)
|
||
|
||
Для каждой связи матрицы:
|
||
- правильная identity с нашим CA -> соединение и ответ сервиса (успех);
|
||
- клиент проверяет СЕРВЕР: пустой/чужой trust store и неверное имя -> ошибка проверки сертификата;
|
||
- сервер проверяет КЛИЕНТА (где mTLS): без сертификата, сертификат чужого CA (rogue-lb),
|
||
истёкший (lb-expired) -> отказ в рукопожатии; identity нашего CA, которой связь не разрешена
|
||
(intruder, worker вместо lb, ...) -> отказ после рукопожатия (закрытие, 403, вход отклонён).
|
||
Главное: сертификат нашего CA ещё не даёт прав. Пример — API: сертификат worker выдан тем же CA,
|
||
но реплика пускает только lb (TLS_ALLOWED_CLIENTS, src/messenger/tlsserver.py).
|
||
|
||
Каждый отказ должен быть именно ОТКАЗОМ ПРОВЕРКИ: TCP-соединение до сервера есть, а в ответ —
|
||
TLS alert, неверный сертификат сервера, закрытие после рукопожатия или HTTP 403. «Сервер
|
||
недоступен» (нет TCP, таймаут) засчитывается как FAIL: такой тест ничего не доказывает.
|
||
"""
|
||
import socket
|
||
import ssl
|
||
import sys
|
||
from typing import NamedTuple
|
||
|
||
import pika
|
||
import psycopg
|
||
|
||
from matrix import CA, ROGUE_CA, Matrix, bao_login, bao_secret, cert, short
|
||
|
||
# Идентичности для отрицательных проверок (scripts/pki.py, secrets/tls-test/).
|
||
NO_CERT, ROGUE, EXPIRED, INTRUDER = None, "rogue-lb", "lb-expired", "intruder"
|
||
BAD_CERTS = {"no client cert": NO_CERT, "foreign CA (rogue-lb)": ROGUE, "expired (lb-expired)": EXPIRED}
|
||
|
||
|
||
class Outcome(NamedTuple):
|
||
kind: str # unreachable | server-cert | tls-refused | closed | reply | http
|
||
detail: str
|
||
status: int = 0 # HTTP-статус для kind == "http"
|
||
|
||
|
||
def context(identity: str | None, trust: str = "ours") -> ssl.SSLContext:
|
||
"""trust: ours — наш CA; rogue — CA атакующего; empty — пустое хранилище."""
|
||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # check_hostname + CERT_REQUIRED
|
||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||
if trust == "ours":
|
||
ctx.load_verify_locations(CA)
|
||
elif trust == "rogue":
|
||
ctx.load_verify_locations(ROGUE_CA)
|
||
if identity:
|
||
ctx.load_cert_chain(*cert(identity))
|
||
return ctx
|
||
|
||
|
||
def probe(host: str, port: int, identity: str | None = None, trust: str = "ours", name: str | None = None,
|
||
http: tuple[str, str] | None = ("GET", "/"), send: bytes | None = None, headers: str = "") -> Outcome:
|
||
"""Одно TLS-подключение. http=(метод, путь) — HTTP/1.1-запрос; send — свои байты (AMQP и т.п.)."""
|
||
try:
|
||
raw = socket.create_connection((host, port), timeout=5)
|
||
except OSError as exc:
|
||
return Outcome("unreachable", short(exc))
|
||
try:
|
||
try:
|
||
tls = context(identity, trust).wrap_socket(raw, server_hostname=name or host)
|
||
except ssl.SSLCertVerificationError as exc:
|
||
return Outcome("server-cert", f"client rejected server cert: {exc.verify_message}")
|
||
except ssl.SSLError as exc:
|
||
return Outcome("tls-refused", f"handshake refused: {exc.reason or exc}")
|
||
except OSError:
|
||
return Outcome("tls-refused", "closed during handshake")
|
||
version = tls.version()
|
||
if http is None and send is None:
|
||
tls.close()
|
||
return Outcome("reply", f"handshake ok {version}")
|
||
if http is not None:
|
||
method, path = http
|
||
send = (f"{method} {path} HTTP/1.1\r\nHost: {name or host}\r\n{headers}"
|
||
f"Content-Length: 0\r\nConnection: close\r\n\r\n").encode()
|
||
try:
|
||
tls.sendall(send)
|
||
data = tls.recv(4096)
|
||
except ssl.SSLError as exc: # TLS 1.3: отказ клиентскому сертификату приходит после рукопожатия
|
||
return Outcome("tls-refused", f"server alert: {exc.reason or exc}")
|
||
except OSError:
|
||
return Outcome("closed", f"{version} ok, then closed by server")
|
||
finally:
|
||
tls.close()
|
||
if not data:
|
||
return Outcome("closed", f"{version} ok, then closed by server")
|
||
if http is not None and data.startswith(b"HTTP/"):
|
||
status = int(data.split()[1])
|
||
return Outcome("http", f"{version} HTTP {status}", status)
|
||
return Outcome("reply", f"{version} ok, server answered")
|
||
finally:
|
||
raw.close()
|
||
|
||
|
||
def plain(host: str, port: int, payload: bytes) -> Outcome:
|
||
"""Без TLS: открытого порта у сервиса быть не должно (или он отвечает отказом)."""
|
||
try:
|
||
with socket.create_connection((host, port), timeout=5) as sock:
|
||
sock.sendall(payload)
|
||
data = sock.recv(512)
|
||
except OSError as exc:
|
||
return Outcome("closed", f"plaintext: {short(exc)}")
|
||
if not data:
|
||
return Outcome("closed", "plaintext: closed by server")
|
||
first = data.split(b"\r\n")[0][:40].decode("latin-1")
|
||
if data.startswith(b"HTTP/"):
|
||
return Outcome("http", f"plaintext: {first}", int(data.split()[1]))
|
||
return Outcome("reply", f"plaintext answered: {first!r}")
|
||
|
||
|
||
# ---------- ожидания ----------
|
||
|
||
def ok_http(outcome: Outcome, statuses=(200,)) -> bool:
|
||
return outcome.kind == "http" and outcome.status in statuses
|
||
|
||
|
||
def refused(outcome: Outcome) -> bool:
|
||
"""Отказ проверки (не «недоступен»): TLS alert, закрытие после рукопожатия или 403."""
|
||
return outcome.kind in ("tls-refused", "closed") or (outcome.kind == "http" and outcome.status == 403)
|
||
|
||
|
||
def server_rejected(outcome: Outcome) -> bool:
|
||
return outcome.kind == "server-cert"
|
||
|
||
|
||
def server_checks(m: Matrix, who: str, host: str, port: int, name: str, http=("GET", "/")):
|
||
"""Клиент проверяет сервер: чужой/пустой trust store и неверное имя -> ошибка проверки сертификата."""
|
||
for trust, label in (("empty", "empty trust store"), ("rogue", "foreign CA trust store")):
|
||
result = probe(host, port, trust=trust, name=name, http=http)
|
||
m.row(who, f"{label} -> server cert", "verify-err", result.detail, server_rejected(result))
|
||
result = probe(host, port, name="wrong-name.invalid", http=http)
|
||
m.row(who, f"wrong hostname (not {name})", "verify-err", result.detail, server_rejected(result))
|
||
|
||
|
||
def client_checks(m: Matrix, target: str, host: str, port: int, name: str, http=("GET", "/"),
|
||
send: bytes | None = None, intruders=(INTRUDER,), headers: str = ""):
|
||
"""Сервер проверяет клиента: без сертификата / чужой CA / истёкший / не та identity -> отказ."""
|
||
for label, identity in list(BAD_CERTS.items()) + [(f"our CA, identity {i}", i) for i in intruders]:
|
||
result = probe(host, port, identity, name=name, http=http, send=send, headers=headers)
|
||
m.row(label.split(" (")[0] if identity is None else identity, f"-> {target}", "refuse", result.detail,
|
||
refused(result))
|
||
|
||
|
||
# ---------- связи матрицы ----------
|
||
|
||
def client_to_lb(m: Matrix):
|
||
m.section("1. client -> lb:8443 (external TLS; client verifies server identity lb)")
|
||
for name in ("lb",):
|
||
result = probe("lb", 8443, name=name, http=("GET", "/health/ready"))
|
||
m.row("client", f"our CA, hostname {name}, GET /health/ready", "200", result.detail, ok_http(result))
|
||
server_checks(m, "client", "lb", 8443, "lb", http=("GET", "/health/ready"))
|
||
m.row("client", "plaintext HTTP on :8443", "refuse", (r := plain("lb", 8443, b"GET / HTTP/1.1\r\n\r\n")).detail,
|
||
r.kind != "http" or r.status >= 400)
|
||
|
||
|
||
def lb_to_api(m: Matrix):
|
||
m.section("2. lb -> api:8080 (mTLS; replica allows ONLY identity lb, CRL checked)")
|
||
replicas = sorted({info[4][0] for info in socket.getaddrinfo("api", 8080, type=socket.SOCK_STREAM)})
|
||
m.row("dns", "api replicas", ">=1", ", ".join(replicas) or "-", bool(replicas))
|
||
for ip in replicas:
|
||
target = f"api@{ip}"
|
||
result = probe(ip, 8080, "lb", name="api", http=("GET", "/health/ready"))
|
||
m.row("lb", f"-> {target} GET /health/ready", "200", result.detail, ok_http(result))
|
||
# Реплика предъявляет identity api: если ждать от неё lb — проверка имени не проходит.
|
||
result = probe(ip, 8080, "lb", name="lb", http=("GET", "/health/ready"))
|
||
m.row("lb", f"-> {target} expecting name lb", "verify-err", result.detail, server_rejected(result))
|
||
# Сертификат нашего CA — но не lb: worker, api, grafana, intruder. Всех — отказ.
|
||
client_checks(m, target, ip, 8080, "api", http=("GET", "/health/ready"),
|
||
intruders=(INTRUDER, "worker", "api", "grafana", "otel-collector"))
|
||
|
||
|
||
def api_to_collector(m: Matrix):
|
||
m.section("3. api/worker -> otel-collector:4318 (mTLS gateway otlp-gw; allowlist CN api, worker)")
|
||
request = ("POST", "/v1/metrics")
|
||
headers = "Content-Type: application/x-protobuf\r\n"
|
||
for identity in ("api", "worker"):
|
||
result = probe("otel-collector", 4318, identity, http=request, headers=headers)
|
||
m.row(identity, "-> otel-collector POST /v1/metrics", "200", result.detail, ok_http(result))
|
||
server_checks(m, "api", "otel-collector", 4318, "otel-collector", http=request)
|
||
client_checks(m, "otel-collector", "otel-collector", 4318, "otel-collector", http=request, headers=headers,
|
||
intruders=(INTRUDER, "lb", "grafana", "prometheus"))
|
||
# Сам Collector слушает только 127.0.0.1:14318 общего namespace — из сети в обход шлюза не попасть.
|
||
try:
|
||
socket.create_connection(("otel-collector", 14318), timeout=3).close()
|
||
bypass = Outcome("reply", "port 14318 open")
|
||
except OSError:
|
||
bypass = Outcome("closed", "port 14318 closed")
|
||
m.row("any", "bypass gateway: otel-collector:14318", "closed", bypass.detail, bypass.kind == "closed")
|
||
|
||
|
||
def telemetry_backends(m: Matrix):
|
||
m.section("4. otel-collector / grafana -> prometheus, loki, tempo (mTLS)")
|
||
# buildinfo, а не /ready: проверяется транспорт, а не прогрев ring/ingester (там бывает 503).
|
||
# У каждого хранилища свой список разрешённых identity (contracts/trust-matrix.md):
|
||
# prometheus и loki — otel-collector (пишет) и grafana (читает); tempo:3200 (API запросов) читает
|
||
# только grafana, tempo:4318 (приём OTLP) пишет только otel-collector.
|
||
backends = [("prometheus", 9090, "/-/ready", ("otel-collector", "grafana")),
|
||
("loki", 3100, "/loki/api/v1/status/buildinfo", ("otel-collector", "grafana")),
|
||
("tempo", 3200, "/api/status/buildinfo", ("grafana",))]
|
||
for host, port, path, allowed in backends:
|
||
for identity in allowed:
|
||
result = probe(host, port, identity, http=("GET", path))
|
||
m.row(identity, f"-> {host}:{port} GET {path}", "200", result.detail, ok_http(result))
|
||
server_checks(m, allowed[0], host, port, host, http=("GET", path))
|
||
# Любая другая identity нашего CA (intruder, api, lb и не разрешённая здесь из пары
|
||
# otel-collector/grafana) должна получить отказ.
|
||
refused = tuple(i for i in ("otel-collector", "grafana") if i not in allowed)
|
||
client_checks(m, f"{host}:{port}", host, port, host, http=("GET", path),
|
||
intruders=(INTRUDER, "api", "lb") + refused)
|
||
# Приём OTLP у Tempo: пишет только Collector, grafana тоже должна получить отказ.
|
||
result = probe("tempo", 4318, "otel-collector", http=("POST", "/v1/traces"),
|
||
headers="Content-Type: application/x-protobuf\r\n")
|
||
m.row("otel-collector", "-> tempo:4318 POST /v1/traces", "200", result.detail, ok_http(result))
|
||
client_checks(m, "tempo:4318", "tempo", 4318, "tempo", http=("POST", "/v1/traces"),
|
||
headers="Content-Type: application/x-protobuf\r\n", intruders=(INTRUDER, "api", "lb", "grafana"))
|
||
|
||
|
||
def to_openbao(m: Matrix):
|
||
m.section("5. api/worker -> openbao:8200 (TLS + cert auth: role accepts only CN api / worker)")
|
||
result = probe("openbao", 8200, "api", http=("GET", "/v1/sys/health"))
|
||
m.row("api", "-> openbao GET /v1/sys/health", "200", result.detail, ok_http(result))
|
||
server_checks(m, "api", "openbao", 8200, "openbao", http=("GET", "/v1/sys/health"))
|
||
# Listener OpenBao клиентский сертификат только запрашивает (tls_require_and_verify_client_cert не
|
||
# включён: оператор ходит с root token без сертификата). Проверяет его cert auth при входе: цепочка
|
||
# до нашего CA, срок, CN из allowed_common_names роли. Поэтому отказ здесь — на login, а не в TLS.
|
||
for identity, role in ((None, "messenger-api"), (ROGUE, "messenger-api"), (EXPIRED, "messenger-api"),
|
||
(INTRUDER, "messenger-api"), ("lb", "messenger-worker"), ("worker", "messenger-api")):
|
||
error = ""
|
||
try:
|
||
status, payload = bao_login(identity, role)
|
||
error = (payload.get("errors") or [""])[0].replace("\n", " ")
|
||
outcome = Outcome("http", f"login HTTP {status}" + (f": {error[:60]}" if error else ""), status)
|
||
except ssl.SSLError as exc:
|
||
outcome = Outcome("tls-refused", f"handshake refused: {exc.reason}")
|
||
# Истёкший сертификат OpenBao 2.4 отклоняет с HTTP 500 ("certificate has expired"): токена нет,
|
||
# но 500 засчитываем только с такой причиной — иначе это мог быть просто сбой сервиса.
|
||
ok = outcome.kind == "tls-refused" or (outcome.kind == "http" and (
|
||
outcome.status in (400, 403) or (outcome.status == 500 and "certificate has expired" in error)))
|
||
m.row(identity or "no client cert", f"-> openbao login role {role}", "refuse", outcome.detail, ok)
|
||
for identity in ("api", "worker"):
|
||
status, _ = bao_login(identity, f"messenger-{identity}")
|
||
m.row(identity, f"-> openbao login role messenger-{identity}", "200", f"login HTTP {status}", status == 200)
|
||
|
||
|
||
AMQP_HEADER = b"AMQP\x00\x00\x09\x01"
|
||
|
||
|
||
def broker_login(identity: str) -> Outcome:
|
||
ctx = context(identity)
|
||
params = pika.ConnectionParameters(host="broker", port=5671, virtual_host="messenger",
|
||
credentials=pika.credentials.ExternalCredentials(),
|
||
ssl_options=pika.SSLOptions(ctx, server_hostname="broker"),
|
||
connection_attempts=1, socket_timeout=5)
|
||
try:
|
||
pika.BlockingConnection(params).close()
|
||
return Outcome("reply", "SASL EXTERNAL login ok")
|
||
except (pika.exceptions.ProbableAuthenticationError, pika.exceptions.ProbableAccessDeniedError,
|
||
pika.exceptions.AuthenticationError) as exc:
|
||
return Outcome("closed", f"login refused: {type(exc).__name__}")
|
||
except pika.exceptions.AMQPError as exc:
|
||
return Outcome("unreachable", short(exc))
|
||
|
||
|
||
def to_broker(m: Matrix):
|
||
m.section("6. api/worker -> broker:5671 (mTLS + SASL EXTERNAL: user = certificate CN)")
|
||
for identity in ("api", "worker"):
|
||
result = broker_login(identity)
|
||
m.row(identity, "-> broker login", "allow", result.detail, result.kind == "reply")
|
||
server_checks(m, "api", "broker", 5671, "broker", http=None)
|
||
for label, identity in BAD_CERTS.items():
|
||
result = probe("broker", 5671, identity, name="broker", http=None, send=AMQP_HEADER)
|
||
m.row(label.split(" (")[0] if identity is None else identity, "-> broker (TLS)", "refuse",
|
||
result.detail, refused(result))
|
||
# Сертификат нашего CA с CN, которого нет среди пользователей брокера: TLS проходит, вход — нет.
|
||
for identity in (INTRUDER, "lb", "grafana"):
|
||
result = broker_login(identity)
|
||
m.row(identity, "-> broker login", "refuse", result.detail, result.kind == "closed")
|
||
try:
|
||
socket.create_connection(("broker", 5672), timeout=3).close()
|
||
result = Outcome("reply", "5672 open")
|
||
except OSError:
|
||
result = Outcome("closed", "5672 closed")
|
||
m.row("any", "plaintext AMQP broker:5672", "closed", result.detail, result.kind == "closed")
|
||
|
||
|
||
def to_postgres(m: Matrix, secrets: dict):
|
||
m.section("7. api/worker -> postgres:5432 (TLS verify-full, hostssl only, SCRAM)")
|
||
|
||
def connect(user, password, host="postgres", **tls):
|
||
options = {"sslmode": "verify-full", "sslrootcert": CA} | tls
|
||
try:
|
||
with psycopg.connect(host=host, port=5432, dbname="messenger", user=user, password=password,
|
||
connect_timeout=5, **options) as conn:
|
||
version = conn.execute("SELECT version FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
|
||
return True, f"connected, {version[0] if version else 'no TLS?'}"
|
||
except psycopg.OperationalError as exc:
|
||
text = str(exc)
|
||
for marker, label in (("does not match host name", "hostname mismatch"),
|
||
("certificate verify failed", "server cert verify failed"),
|
||
("no encryption", "pg_hba: no encryption -> reject"),
|
||
("pg_hba.conf rejects", "pg_hba reject")):
|
||
if marker in text:
|
||
return False, label
|
||
return False, short(exc)
|
||
|
||
for identity, role in (("api", "messenger_api"), ("worker", "messenger_worker")):
|
||
ok, detail = connect(role, secrets[identity]["db_password"])
|
||
m.row(identity, f"-> postgres as {role} (verify-full)", "allow", detail, ok and "TLS" in detail)
|
||
password = secrets["api"]["db_password"]
|
||
ok, detail = connect("messenger_api", password, sslmode="disable", sslrootcert="")
|
||
m.row("api", "-> postgres without TLS (right password)", "refuse", detail, not ok and "pg_hba" in detail)
|
||
ok, detail = connect("messenger_api", password, sslrootcert=ROGUE_CA)
|
||
m.row("api", "-> postgres, foreign CA trust store", "verify-err", detail, not ok and "verify" in detail)
|
||
ip = socket.gethostbyname("postgres")
|
||
ok, detail = connect("messenger_api", password, host=ip)
|
||
m.row("api", f"-> postgres by IP {ip} (name != SAN)", "verify-err", detail, not ok and "hostname" in detail)
|
||
|
||
|
||
def to_valkey(m: Matrix):
|
||
m.section("8. api -> valkey:6379 (TLS; identity = ACL user, checked in acl_matrix.py)")
|
||
result = probe("valkey", 6379, http=None, send=b"PING\r\n")
|
||
m.row("api", "-> valkey TLS, PING without AUTH", "NOAUTH", result.detail, result.kind == "reply")
|
||
server_checks(m, "api", "valkey", 6379, "valkey", http=None)
|
||
result = plain("valkey", 6379, b"PING\r\n")
|
||
m.row("api", "-> valkey plaintext PING", "refuse", result.detail, result.kind == "closed")
|
||
|
||
|
||
def to_s3(m: Matrix):
|
||
m.section("9. api/worker -> s3:9000 (HTTPS; identity = S3 keys, checked in acl_matrix.py)")
|
||
result = probe("s3", 9000, http=("GET", "/healthz"))
|
||
m.row("api", "-> s3 GET /healthz", "200", result.detail, ok_http(result))
|
||
server_checks(m, "api", "s3", 9000, "s3", http=("GET", "/healthz"))
|
||
result = plain("s3", 9000, b"GET /healthz HTTP/1.1\r\nHost: s3\r\n\r\n")
|
||
m.row("api", "-> s3 plaintext HTTP", "refuse", result.detail, result.kind != "http" or result.status >= 400)
|
||
|
||
|
||
def main() -> int:
|
||
socket.setdefaulttimeout(10)
|
||
m = Matrix("TLS matrix (lab7): who may connect where")
|
||
client_to_lb(m)
|
||
lb_to_api(m)
|
||
api_to_collector(m)
|
||
telemetry_backends(m)
|
||
to_openbao(m)
|
||
to_broker(m)
|
||
secrets = {identity: bao_secret(identity) for identity in ("api", "worker")}
|
||
to_postgres(m, secrets)
|
||
to_valkey(m)
|
||
to_s3(m)
|
||
print("\n## 10. replication / cluster channels: N/A (single node PostgreSQL, Valkey, broker, OpenBao)")
|
||
return m.finish()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|