Files
mtusi2026lab7/app/serve.py
alenchha 861e7722b5 ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

96 lines
4.1 KiB
Python

"""API process entrypoint (lab7): uvicorn behind MANDATORY mutual TLS with an identity allowlist.
TLS layer (ssl.SSLContext, CERT_REQUIRED): the client must present a certificate chained to the lab root CA.
Identity layer (this module, right after the handshake, for every connection including resumed TLS sessions):
* DNS SAN must be in ALLOWED_CLIENT_IDENTITIES (only the LB: lb.client.messenger);
* the certificate serial must not be in REVOKED_SERIALS_FILE (re-read when it changes, no restart needed).
A certificate from the same CA with another identity (worker, api, intruder) is closed before any HTTP byte is read.
There is no plaintext listener on the network; the Docker healthcheck uses 127.0.0.1:8081 (app.main).
"""
import logging
import os
import ssl
import time
import uvicorn
from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol
from app import config, telemetry
log = logging.getLogger("messenger.mtls")
class Revocations:
def __init__(self, path: str) -> None:
self.path, self.mtime, self.checked, self.serials = path, None, 0.0, frozenset()
def current(self) -> frozenset:
now = time.monotonic()
if self.path and now - self.checked > 1.0:
self.checked = now
try:
mtime = os.stat(self.path).st_mtime
if mtime != self.mtime:
with open(self.path, encoding="utf-8") as handle:
self.serials = frozenset(line.strip().upper() for line in handle if line.strip())
self.mtime = mtime
log.info("mtls_revocations_loaded count=%d", len(self.serials))
except OSError:
pass # keep the last known list
return self.serials
REVOKED = Revocations(config.REVOKED_SERIALS_FILE)
rejected = telemetry.meter.create_counter("messenger.mtls.rejected", unit="{connection}",
description="API mTLS connections closed by the identity check, by reason")
def identity_check(cert: dict) -> tuple:
"""(allowed, reason, identity, serial) for a validated peer certificate dict (ssl.getpeercert())."""
sans = [value for kind, value in cert.get("subjectAltName", ()) if kind == "DNS"]
serial = str(cert.get("serialNumber", "")).upper()
identity = sans[0] if sans else "-"
if serial in REVOKED.current():
return False, "revoked", identity, serial
if not config.ALLOWED_CLIENT_IDENTITIES.intersection(sans):
return False, "identity_not_allowed", identity, serial
return True, "ok", identity, serial
class MutualTLSProtocol(HttpToolsProtocol):
def connection_made(self, transport) -> None:
super().connection_made(transport)
ssl_object = transport.get_extra_info("ssl_object")
cert = ssl_object.getpeercert() if ssl_object is not None else None
allowed, reason, identity, serial = identity_check(cert or {}) if cert else (False, "no_certificate", "-", "-")
if not allowed:
rejected.add(1, {"reason": reason})
log.warning("mtls_client_rejected reason=%s identity=%s serial=%s", reason, identity, serial)
transport.abort()
def ssl_context() -> ssl.SSLContext:
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=config.TLS_CA_FILE)
ctx.load_cert_chain(config.TLS_SERVER_CERT_FILE, config.TLS_SERVER_KEY_FILE)
ctx.verify_mode = ssl.CERT_REQUIRED
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
return ctx
class Config(uvicorn.Config):
def load(self) -> None:
super().load()
self.ssl = ssl_context() # replace uvicorn's context: CA + CERT_REQUIRED + TLS >= 1.2
def main() -> None:
cfg = Config("app.main:app", host=os.environ.get("APP_HOST", "0.0.0.0"), port=int(os.environ.get("APP_PORT", "8080")),
http=MutualTLSProtocol, access_log=False, timeout_graceful_shutdown=int(config.GRACEFUL_TIMEOUT),
ssl_certfile=config.TLS_SERVER_CERT_FILE, ssl_keyfile=config.TLS_SERVER_KEY_FILE,
ssl_ca_certs=config.TLS_CA_FILE, ssl_cert_reqs=ssl.CERT_REQUIRED)
uvicorn.Server(cfg).run()
if __name__ == "__main__":
main()