forked from mtusi2026/mtusi2026lab7
388 lines
17 KiB
Python
388 lines
17 KiB
Python
"""Отрицательные и положительные проверки матрицы доверия lab7.
|
|
|
|
Запускается внутри security-probe (сеть стенда, сертификаты и AppRole files
|
|
смонтированы read-only). Секреты не печатаются: только имена проверок,
|
|
ожидаемый/наблюдаемый класс результата и HTTP-код там, где он есть.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import http.client
|
|
import json
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
CERTS = Path("/certs")
|
|
BAO = Path("/bao")
|
|
RESULTS: list[dict] = []
|
|
|
|
|
|
def record(name: str, ok: bool, detail: str) -> None:
|
|
RESULTS.append({"name": name, "ok": bool(ok), "detail": detail})
|
|
print(("PASS " if ok else "FAIL ") + name + ": " + detail, flush=True)
|
|
|
|
|
|
def context(ca: Path, cert: Path | None = None, key: Path | None = None) -> ssl.SSLContext:
|
|
ctx = ssl.create_default_context(cafile=str(ca))
|
|
ctx.check_hostname = True
|
|
ctx.verify_mode = ssl.CERT_REQUIRED
|
|
if cert is not None:
|
|
ctx.load_cert_chain(str(cert), str(key) if key else None)
|
|
return ctx
|
|
|
|
|
|
def read_file(path: Path) -> str:
|
|
return path.read_text(encoding="utf-8").strip()
|
|
|
|
|
|
def http_call(
|
|
host: str,
|
|
port: int,
|
|
path: str,
|
|
ctx: ssl.SSLContext,
|
|
*,
|
|
timeout: float = 5.0,
|
|
body: bytes | None = None,
|
|
method: str = "GET",
|
|
headers: dict[str, str] | None = None,
|
|
) -> tuple[int, bytes]:
|
|
conn = http.client.HTTPSConnection(host, port, context=ctx, timeout=timeout)
|
|
conn.request(method, path, body=body, headers=headers or {})
|
|
response = conn.getresponse()
|
|
data = response.read()
|
|
conn.close()
|
|
return response.status, data
|
|
|
|
|
|
def expect_http(name: str, call, expected: set[int], detail: str) -> None:
|
|
try:
|
|
status, _ = call()
|
|
record(name, status in expected, f"HTTP {status}; {detail}")
|
|
except ssl.SSLError as exc:
|
|
record(name, False, f"TLS error instead of HTTP: {exc.__class__.__name__}")
|
|
except OSError as exc:
|
|
record(name, False, f"network error: {exc.__class__.__name__}")
|
|
|
|
|
|
def expect_denied(name: str, call, detail: str) -> None:
|
|
"""Отрицательная проверка: либо TLS/handshake, либо HTTP 403."""
|
|
try:
|
|
status, _ = call()
|
|
record(name, status == 403, f"HTTP {status}; {detail}")
|
|
except (ssl.SSLError, OSError) as exc:
|
|
record(name, True, f"connection rejected: {exc.__class__.__name__}; {detail}")
|
|
|
|
|
|
def expect_tls_failure(name: str, ca: Path, host: str, port: int, cert: Path | None = None, key: Path | None = None, hostname: str | None = None) -> None:
|
|
try:
|
|
ctx = context(ca, cert, key)
|
|
with socket.create_connection((host, port), timeout=5) as raw:
|
|
with ctx.wrap_socket(raw, server_hostname=hostname or host):
|
|
pass
|
|
record(name, False, "handshake unexpectedly succeeded")
|
|
except ssl.SSLError as exc:
|
|
record(name, True, f"TLS rejected: {exc.reason or exc.__class__.__name__}")
|
|
except OSError as exc:
|
|
record(name, False, f"unexpected network error: {exc.__class__.__name__}")
|
|
|
|
|
|
def expect_tls_ok(name: str, ca: Path, host: str, port: int, cert: Path | None = None, key: Path | None = None, hostname: str | None = None) -> socket.socket | None:
|
|
try:
|
|
ctx = context(ca, cert, key)
|
|
raw = socket.create_connection((host, port), timeout=5)
|
|
return ctx.wrap_socket(raw, server_hostname=hostname or host)
|
|
except (ssl.SSLError, OSError) as exc:
|
|
record(name, False, f"TLS failed: {exc.__class__.__name__}")
|
|
return None
|
|
|
|
|
|
def external_tls() -> None:
|
|
ca = CERTS / "ca.crt"
|
|
try:
|
|
with urllib.request.urlopen("https://traefik:8443/health/ready", context=context(ca), timeout=5) as response:
|
|
record("external_tls_trusted", response.status == 200, f"HTTP {response.status}")
|
|
except Exception as exc: # noqa: BLE001
|
|
record("external_tls_trusted", False, type(exc).__name__)
|
|
try:
|
|
urllib.request.urlopen("https://traefik:8443/health/ready", context=context(CERTS / "foreign-ca.crt"), timeout=5)
|
|
record("external_tls_untrusted_ca", False, "untrusted CA accepted")
|
|
except urllib.error.URLError as exc:
|
|
reason = getattr(exc, "reason", exc)
|
|
record("external_tls_untrusted_ca", isinstance(reason, ssl.SSLError), f"rejected: {type(reason).__name__}")
|
|
except ssl.SSLError as exc:
|
|
record("external_tls_untrusted_ca", True, f"rejected: {exc.__class__.__name__}")
|
|
try:
|
|
ctx = context(ca)
|
|
with socket.create_connection(("traefik", 8443), timeout=5) as raw:
|
|
with ctx.wrap_socket(raw, server_hostname="wrong.messenger.internal"):
|
|
pass
|
|
record("external_tls_wrong_hostname", False, "wrong hostname accepted")
|
|
except ssl.SSLError as exc:
|
|
record("external_tls_wrong_hostname", True, f"rejected: {exc.reason or exc.__class__.__name__}")
|
|
|
|
|
|
def api_mtls() -> None:
|
|
ca = CERTS / "ca.crt"
|
|
expect_denied(
|
|
"api_no_client_cert",
|
|
lambda: http_call("api", 8081, "/health/ready", context(ca)),
|
|
"no client certificate",
|
|
)
|
|
expect_denied(
|
|
"api_foreign_ca_client",
|
|
lambda: http_call("api", 8081, "/health/ready", context(ca, CERTS / "tests" / "foreign-ca-client.crt", CERTS / "tests" / "foreign-ca-client.key")),
|
|
"client signed by foreign CA",
|
|
)
|
|
# Доверенный CA, но чужая identity: TLS проходит, шлюз обязан вернуть 403.
|
|
expect_http(
|
|
"api_trusted_ca_wrong_identity",
|
|
lambda: http_call("api", 8081, "/health/ready", context(ca, CERTS / "tests" / "foreign-client.crt", CERTS / "tests" / "foreign-client.key")),
|
|
{403},
|
|
"foreign.messenger.internal must be denied",
|
|
)
|
|
expect_http(
|
|
"api_lb_identity_allowed",
|
|
lambda: http_call("api", 8081, "/health/ready", context(ca, CERTS / "traefik" / "lb-client.crt", CERTS / "traefik" / "lb-client.key")),
|
|
{200},
|
|
"lb.messenger.internal ready",
|
|
)
|
|
|
|
|
|
def exchange_amqp(host: str, port: int, cert: Path | None = None, key: Path | None = None) -> bytes:
|
|
ctx = context(CERTS / "ca.crt", cert, key)
|
|
with socket.create_connection((host, port), timeout=5) as raw:
|
|
with ctx.wrap_socket(raw, server_hostname="internal-gateway") as tls:
|
|
tls.sendall(b"AMQP\x00\x00\x09\x01")
|
|
tls.settimeout(3)
|
|
try:
|
|
return tls.recv(64)
|
|
except (socket.timeout, ConnectionError):
|
|
return b""
|
|
|
|
|
|
def broker_mtls() -> None:
|
|
ca = CERTS / "ca.crt"
|
|
expect_denied(
|
|
"broker_no_client_cert",
|
|
lambda: (lambda data=exchange_amqp("internal-gateway", 5671): (403 if not data else 200, data))(),
|
|
"no client certificate",
|
|
)
|
|
api_cert = CERTS / "api" / "api-client.crt"
|
|
api_key = CERTS / "api" / "api-client.key"
|
|
worker_cert = CERTS / "worker" / "worker-client.crt"
|
|
worker_key = CERTS / "worker" / "worker-client.key"
|
|
expect_http(
|
|
"broker_wrong_identity_on_producer",
|
|
lambda: (lambda data=exchange_amqp("internal-gateway", 5671, worker_cert, worker_key): (403, data))(),
|
|
{403},
|
|
"worker identity on producer port must be closed",
|
|
)
|
|
expect_http(
|
|
"broker_api_on_consumer_port",
|
|
lambda: (lambda data=exchange_amqp("internal-gateway", 5672, api_cert, api_key): (403, data))(),
|
|
{403},
|
|
"api identity on consumer port must be closed",
|
|
)
|
|
try:
|
|
data = exchange_amqp("internal-gateway", 5671, api_cert, api_key)
|
|
# RabbitMQ после protocol header отвечает AMQP-фреймом Connection.Start
|
|
# (первый байт 0x01), а не эхом заголовка; важен непустой ответ.
|
|
record("broker_api_identity_allowed", bool(data), f"AMQP Connection.Start bytes={len(data)}")
|
|
except Exception as exc: # noqa: BLE001
|
|
record("broker_api_identity_allowed", False, type(exc).__name__)
|
|
|
|
|
|
def otel_mtls() -> None:
|
|
ca = CERTS / "ca.crt"
|
|
api_cert = CERTS / "api" / "api-client.crt"
|
|
api_key = CERTS / "api" / "api-client.key"
|
|
worker_cert = CERTS / "worker" / "worker-client.crt"
|
|
worker_key = CERTS / "worker" / "worker-client.key"
|
|
expect_http(
|
|
"collector_api_identity_allowed",
|
|
lambda: http_call("internal-gateway", 4318, "/v1/traces", context(ca, api_cert, api_key)),
|
|
{200, 202, 400, 404, 405},
|
|
"api identity reaches collector",
|
|
)
|
|
expect_http(
|
|
"collector_worker_on_api_port",
|
|
lambda: http_call("internal-gateway", 4318, "/v1/traces", context(ca, worker_cert, worker_key)),
|
|
{403},
|
|
"worker identity on api port must be denied",
|
|
)
|
|
expect_http(
|
|
"collector_worker_identity_allowed",
|
|
lambda: http_call("internal-gateway", 4319, "/v1/traces", context(ca, worker_cert, worker_key)),
|
|
{200, 202, 400, 404, 405},
|
|
"worker identity reaches collector",
|
|
)
|
|
|
|
|
|
def telemetry_mtls() -> None:
|
|
ca = CERTS / "ca.crt"
|
|
collector = context(ca, CERTS / "telemetry" / "telemetry-client.crt", CERTS / "telemetry" / "telemetry-client.key")
|
|
grafana = context(ca, CERTS / "telemetry" / "grafana-client.crt", CERTS / "telemetry" / "grafana-client.key")
|
|
foreign = context(ca, CERTS / "tests" / "foreign-client.crt", CERTS / "tests" / "foreign-client.key")
|
|
expect_http("loki_collector_allowed", lambda: http_call("loki-tls", 8443, "/metrics", collector), {200}, "collector reads Loki")
|
|
expect_http("loki_foreign_identity_denied", lambda: http_call("loki-tls", 8443, "/ready", foreign), {403}, "foreign identity denied")
|
|
expect_http("prometheus_grafana_allowed", lambda: http_call("prometheus-tls", 8443, "/-/ready", grafana), {200}, "Grafana reads Prometheus")
|
|
expect_http("prometheus_collector_denied", lambda: http_call("prometheus-tls", 8443, "/-/ready", collector), {403}, "collector cert on Grafana port denied")
|
|
expect_http("collector_metrics_prometheus_allowed", lambda: http_call("collector-tls", 8889, "/metrics", context(ca, CERTS / "telemetry" / "prometheus-client.crt", CERTS / "telemetry" / "prometheus-client.key")), {200}, "Prometheus scrapes collector over mTLS")
|
|
expect_http("collector_metrics_grafana_denied", lambda: http_call("collector-tls", 8889, "/metrics", grafana), {403}, "Grafana cert on scrape port denied")
|
|
|
|
|
|
def openbao_call(addr: str, path: str, token: str | None, payload: dict | None = None, method: str = "GET") -> tuple[int, dict]:
|
|
body = None if payload is None else json.dumps(payload).encode()
|
|
request = urllib.request.Request("https://" + addr + path, data=body, method=method)
|
|
request.add_header("Content-Type", "application/json")
|
|
if token:
|
|
request.add_header("X-Vault-Token", token)
|
|
try:
|
|
with urllib.request.urlopen(request, context=context(CERTS / "ca.crt"), timeout=5) as response:
|
|
return response.status, json.loads(response.read() or b"{}")
|
|
except urllib.error.HTTPError as exc:
|
|
return exc.code, {}
|
|
|
|
|
|
def login(role: str) -> str:
|
|
role_id = read_file(BAO / f"{role}_role_id")
|
|
secret_id = read_file(BAO / f"{role}_secret_id")
|
|
status, body = openbao_call("openbao:8200", "/v1/auth/approle/login", None, {"role_id": role_id, "secret_id": secret_id}, "POST")
|
|
if status != 200 or not (body.get("auth") or {}).get("client_token"):
|
|
raise RuntimeError(f"AppRole {role} login failed: {status}")
|
|
return str(body["auth"]["client_token"])
|
|
|
|
|
|
def openbao_policy() -> None:
|
|
api_token = login("api")
|
|
worker_token = login("worker")
|
|
status, _ = openbao_call("openbao:8200", "/v1/kv/data/messenger/api", api_token)
|
|
record("openbao_api_own_secret_allowed", status == 200, f"HTTP {status}")
|
|
status, _ = openbao_call("openbao:8200", "/v1/kv/data/messenger/worker", api_token)
|
|
record("openbao_api_foreign_secret_denied", status == 403, f"HTTP {status}")
|
|
status, _ = openbao_call("openbao:8200", "/v1/sys/policies/acl/messenger-api", api_token, {"policy": 'path "secret/*" { capabilities = ["read"] }'}, "PUT")
|
|
record("openbao_api_policy_write_denied", status == 403, f"HTTP {status}")
|
|
status, _ = openbao_call("openbao:8200", "/v1/sys/policies/acl", api_token)
|
|
record("openbao_api_policy_list_denied", status == 403, f"HTTP {status}")
|
|
status, _ = openbao_call("openbao:8200", "/v1/kv/data/messenger/api", worker_token)
|
|
record("openbao_worker_foreign_secret_denied", status == 403, f"HTTP {status}")
|
|
|
|
|
|
async def db_checks() -> None:
|
|
import asyncpg
|
|
|
|
ca = CERTS / "ca.crt"
|
|
api_token = login("api")
|
|
worker_token = login("worker")
|
|
_, api_body = openbao_call("openbao:8200", "/v1/kv/data/messenger/api", api_token)
|
|
_, worker_body = openbao_call("openbao:8200", "/v1/kv/data/messenger/worker", worker_token)
|
|
api_url = str((api_body.get("data") or {}).get("data", {}).get("DATABASE_URL", ""))
|
|
worker_url = str((worker_body.get("data") or {}).get("data", {}).get("DATABASE_URL", ""))
|
|
ctx = context(ca)
|
|
api_url = api_url.replace("postgresql+asyncpg://", "postgresql://")
|
|
worker_url = worker_url.replace("postgresql+asyncpg://", "postgresql://")
|
|
api_conn = await asyncpg.connect(api_url, ssl=ctx, timeout=5)
|
|
try:
|
|
await api_conn.fetchval("SELECT 1")
|
|
record("postgres_api_tls_allowed", True, "verified TLS + SELECT 1")
|
|
finally:
|
|
await api_conn.close()
|
|
worker_conn = await asyncpg.connect(worker_url, ssl=ctx, timeout=5)
|
|
try:
|
|
await worker_conn.fetchval("SELECT count(*) FROM jobs")
|
|
record("postgres_worker_jobs_allowed", True, "worker reads jobs")
|
|
denied = False
|
|
try:
|
|
await worker_conn.fetch("SELECT username, password_hash FROM users LIMIT 1")
|
|
except asyncpg.InsufficientPrivilegeError:
|
|
denied = True
|
|
record("postgres_worker_users_denied", denied, "users/password_hash denied")
|
|
denied = False
|
|
try:
|
|
await worker_conn.execute("CREATE TABLE lab7_probe_forbidden (id int)")
|
|
except asyncpg.InsufficientPrivilegeError:
|
|
denied = True
|
|
record("postgres_worker_ddl_denied", denied, "CREATE TABLE denied")
|
|
finally:
|
|
await worker_conn.close()
|
|
# Plaintext host connection must be rejected by pg_hba (hostnossl reject).
|
|
plain_denied = False
|
|
try:
|
|
plain = await asyncpg.connect(api_url, ssl=False, timeout=5)
|
|
await plain.close()
|
|
except (asyncpg.PostgresError, OSError):
|
|
plain_denied = True
|
|
record("postgres_plaintext_rejected", plain_denied, "ssl=False rejected")
|
|
|
|
|
|
def s3_checks() -> None:
|
|
import boto3
|
|
from botocore.exceptions import ClientError
|
|
|
|
ca = CERTS / "ca.crt"
|
|
token = login("api")
|
|
_, body = openbao_call("openbao:8200", "/v1/kv/data/messenger/api", token)
|
|
data = (body.get("data") or {}).get("data", {})
|
|
endpoint = str(data.get("S3_ENDPOINT", "https://minio:9000"))
|
|
client = boto3.client(
|
|
"s3",
|
|
endpoint_url=endpoint,
|
|
region_name="us-east-1",
|
|
aws_access_key_id=str(data["S3_ACCESS_KEY_ID"]),
|
|
aws_secret_access_key=str(data["S3_SECRET_ACCESS_KEY"]),
|
|
verify=str(ca),
|
|
)
|
|
try:
|
|
client.list_objects_v2(Bucket="messenger-attachments", Prefix="attachments/staging/", MaxKeys=1)
|
|
record("s3_api_tls_allowed", True, "TLS + ListBucket staging")
|
|
except Exception as exc: # noqa: BLE001
|
|
record("s3_api_tls_allowed", False, type(exc).__name__)
|
|
denied = False
|
|
try:
|
|
client.put_object(Bucket="messenger-attachments", Key="attachments/other/forbidden", Body=b"x")
|
|
except ClientError as exc:
|
|
denied = exc.response.get("Error", {}).get("Code") == "AccessDenied"
|
|
record("s3_api_foreign_prefix_denied", denied, "attachments/other/* denied")
|
|
try:
|
|
bad = boto3.client(
|
|
"s3",
|
|
endpoint_url=endpoint,
|
|
region_name="us-east-1",
|
|
aws_access_key_id=str(data["S3_ACCESS_KEY_ID"]),
|
|
aws_secret_access_key=str(data["S3_SECRET_ACCESS_KEY"]),
|
|
verify=str(CERTS / "foreign-ca.crt"),
|
|
)
|
|
bad.list_objects_v2(Bucket="messenger-attachments", Prefix="attachments/staging/", MaxKeys=1)
|
|
record("s3_untrusted_ca_rejected", False, "untrusted CA accepted")
|
|
except Exception as exc: # noqa: BLE001
|
|
record("s3_untrusted_ca_rejected", True, type(exc).__name__)
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--json-out", default="")
|
|
args = parser.parse_args()
|
|
external_tls()
|
|
api_mtls()
|
|
broker_mtls()
|
|
otel_mtls()
|
|
telemetry_mtls()
|
|
openbao_policy()
|
|
asyncio.run(db_checks())
|
|
s3_checks()
|
|
failed = [item for item in RESULTS if not item["ok"]]
|
|
summary = {"checks": RESULTS, "passed": len(RESULTS) - len(failed), "failed": len(failed)}
|
|
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
|
|
if args.json_out:
|
|
Path(args.json_out).write_text(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
|
|
return 0 if not failed else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|