forked from mtusi2026/mtusi2026lab7
913 lines
45 KiB
Python
913 lines
45 KiB
Python
#!/usr/bin/env python3
|
||
"""Отрицательные (и контрольные положительные) проверки ВНУТРЕННЕЙ матрицы доверия lab7 — contracts/trust-matrix.md.
|
||
|
||
Запуск (оператор; контейнер probe профиля tests видит внутренние сети и тестовые identity):
|
||
docker compose --profile tests run --rm probe # всё
|
||
docker compose --profile tests run --rm probe student-tests/internal_security.py --only lb,nats
|
||
|
||
Для каждой связи: нет клиентского сертификата / сертификат ЧУЖОГО CA / сертификат НАШЕГО CA, но запрещённой
|
||
identity (rogue, другой сервис) / истёкший / отозванный → отказ; разрешённая identity → успех; затем права
|
||
(ACL/policy) разрешённой identity: разрешено только нужное. Отказ «по сертификату» отличается от «сервис
|
||
недоступен»: каждая проверка печатает конкретную причину (TLS alert, 403, NOPERM, permission denied).
|
||
Секреты (пароли из OpenBao, токены) используются только в памяти и не печатаются.
|
||
"""
|
||
import argparse
|
||
import asyncio
|
||
import http.client
|
||
import json
|
||
import os
|
||
import socket
|
||
import ssl
|
||
import sys
|
||
import time
|
||
import traceback
|
||
import urllib.error
|
||
import urllib.request
|
||
import uuid
|
||
|
||
sys.path.insert(0, "/app/src")
|
||
import logging # noqa: E402
|
||
logging.getLogger("asyncio").setLevel(logging.ERROR) # шум «eof_received()» при отказах TLS
|
||
import warnings # noqa: E402
|
||
warnings.filterwarnings("ignore", category=DeprecationWarning) # ssl.TLSVersion.TLSv1_1 — намеренно (проверка отказа)
|
||
|
||
TLS = os.environ.get("PROBE_TLS_DIR", "/secrets/tls")
|
||
TEST = os.environ.get("PROBE_TEST_DIR", "/secrets/test")
|
||
BAO = os.environ.get("PROBE_BAO_DIR", "/secrets/bao")
|
||
CA = TLS + "/trust/ca.crt"
|
||
FOREIGN_CA = TEST + "/foreign-ca.crt"
|
||
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||
|
||
ID = { # каталоги сертификатов
|
||
"lb": TLS + "/lb", "api": TLS + "/api", "worker": TLS + "/worker", "bootstrap": TLS + "/bootstrap",
|
||
"otel-collector": TLS + "/otel-collector", "grafana": TLS + "/grafana", "prometheus": TLS + "/prometheus",
|
||
"tempo": TLS + "/tempo", "migrate": TLS + "/migrate",
|
||
"rogue": TEST + "/rogue", "expired-lb": TEST + "/expired-lb", "revoked-lb": TEST + "/revoked-lb",
|
||
"foreign-lb": TEST + "/foreign-lb", "foreign-worker": TEST + "/foreign-worker", "foreign-api": TEST + "/foreign-api",
|
||
"foreign-otel-collector": TEST + "/foreign-otel-collector", "foreign-grafana": TEST + "/foreign-grafana",
|
||
"old-lb": TEST + "/old-lb", # копия сертификата LB ДО ротации (создаёт test_lifecycle.py)
|
||
}
|
||
RESULTS = []
|
||
|
||
|
||
class Fail(Exception):
|
||
pass
|
||
|
||
|
||
def check(cond, msg):
|
||
if not cond:
|
||
raise Fail(msg)
|
||
|
||
|
||
def case(group, title):
|
||
def deco(fn):
|
||
RESULTS.append([group, title, fn, None, None])
|
||
return fn
|
||
return deco
|
||
|
||
|
||
def ctx(identity=None, ca=CA, hostname_check=True):
|
||
c = ssl.create_default_context(cafile=ca)
|
||
c.check_hostname = hostname_check
|
||
if identity:
|
||
d = ID[identity]
|
||
c.load_cert_chain(d + "/tls.crt", d + "/tls.key")
|
||
return c
|
||
|
||
|
||
def https(host, port, path="/", identity=None, method="GET", body=None, headers=None, server_hostname=None,
|
||
ca=CA, timeout=5):
|
||
"""Результат: ('http', status, body) | ('tls', причина) | ('closed', причина) | ('net', причина)."""
|
||
c = ctx(identity, ca)
|
||
try:
|
||
raw = socket.create_connection((host, port), timeout=timeout)
|
||
except OSError as e:
|
||
return ("net", type(e).__name__)
|
||
try:
|
||
s = c.wrap_socket(raw, server_hostname=server_hostname or host)
|
||
except ssl.SSLCertVerificationError as e:
|
||
raw.close()
|
||
return ("tls", "server cert: " + (e.verify_message or str(e))[:80])
|
||
except (ssl.SSLError, OSError) as e:
|
||
raw.close()
|
||
return ("tls", getattr(e, "reason", None) or type(e).__name__)
|
||
# TLS 1.3: клиентское рукопожатие завершается раньше, чем сервер проверит НАШ сертификат, поэтому
|
||
# отказ по сертификату приходит алертом чуть позже — ждём его коротко, чтобы назвать причину точно.
|
||
try:
|
||
s.settimeout(0.3)
|
||
if s.recv(1) == b"":
|
||
s.close()
|
||
return ("closed", "EOF after handshake")
|
||
except ssl.SSLError as e:
|
||
s.close()
|
||
return ("tls", getattr(e, "reason", None) or str(e)[:80])
|
||
except (socket.timeout, TimeoutError):
|
||
pass
|
||
except (ConnectionResetError, BrokenPipeError) as e:
|
||
s.close()
|
||
return ("closed", type(e).__name__)
|
||
s.settimeout(timeout)
|
||
try:
|
||
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||
conn.sock = s
|
||
conn.request(method, path, body=body, headers=dict({"Host": server_hostname or host}, **(headers or {})))
|
||
r = conn.getresponse()
|
||
data = r.read(4096)
|
||
return ("http", r.status, data)
|
||
except ssl.SSLError as e: # TLS 1.3: отказ сервера по сертификату приходит алертом после рукопожатия
|
||
return ("tls", getattr(e, "reason", None) or str(e)[:80])
|
||
except (http.client.RemoteDisconnected, ConnectionResetError, BrokenPipeError, http.client.BadStatusLine) as e:
|
||
return ("closed", type(e).__name__)
|
||
except OSError as e:
|
||
return ("net", type(e).__name__)
|
||
finally:
|
||
s.close()
|
||
|
||
|
||
def denied_tls(res, what):
|
||
check(res[0] in ("tls", "closed"), "%s: expected TLS/connection rejection, got %s" % (what, res[:2]))
|
||
return "%s: %s" % (res[0], res[1])
|
||
|
||
|
||
def status(res, want, what):
|
||
check(res[0] == "http" and res[1] == want, "%s: expected HTTP %s, got %s" % (what, want, res[:2]))
|
||
return "HTTP %s" % want
|
||
|
||
|
||
# ======================================================================================= OpenBao
|
||
def bao_call(method, path, body=None, token=None, ca=CA):
|
||
req = urllib.request.Request("https://openbao:8200/v1/" + path, method=method,
|
||
data=json.dumps(body).encode() if body is not None else None,
|
||
headers={"Content-Type": "application/json"})
|
||
if token:
|
||
req.add_header("X-Vault-Token", token)
|
||
try:
|
||
with urllib.request.urlopen(req, context=ctx(None, ca), timeout=5) as r:
|
||
return r.status, json.loads(r.read() or b"{}")
|
||
except urllib.error.HTTPError as e:
|
||
return e.code, json.loads(e.read() or b"{}")
|
||
|
||
|
||
_TOKENS = {}
|
||
|
||
|
||
def bao_login(svc):
|
||
if svc not in _TOKENS:
|
||
rid = open(BAO + "/%s/role_id" % svc).read().strip()
|
||
sid = open(BAO + "/%s/secret_id" % svc).read().strip()
|
||
st, body = bao_call("POST", "auth/approle/login", {"role_id": rid, "secret_id": sid})
|
||
check(st == 200, "AppRole login %s: HTTP %s" % (svc, st))
|
||
_TOKENS[svc] = body["auth"]
|
||
return _TOKENS[svc]
|
||
|
||
|
||
def kv(svc):
|
||
tok = bao_login(svc)["client_token"]
|
||
st, body = bao_call("GET", "secret/data/messenger/" + svc, token=tok)
|
||
check(st == 200, "read own KV %s: HTTP %s" % (svc, st))
|
||
return body["data"]["data"]
|
||
|
||
|
||
@case("openbao", "TLS: сервер проверяется по CA и имени; plaintext HTTP не обслуживается")
|
||
def _():
|
||
out = []
|
||
r = https("openbao", 8200, "/v1/sys/health", server_hostname="openbao")
|
||
check(r[0] == "http", "trusted TLS failed: %s" % (r,))
|
||
out.append("trusted=HTTP %s" % r[1])
|
||
r = https("openbao", 8200, "/v1/sys/health", ca=FOREIGN_CA)
|
||
out.append("foreign CA → " + denied_tls(r, "foreign trust store"))
|
||
try:
|
||
c = http.client.HTTPConnection("openbao", 8200, timeout=3)
|
||
c.request("GET", "/v1/sys/health")
|
||
resp = c.getresponse()
|
||
check(resp.status == 400, "plaintext got %s" % resp.status)
|
||
out.append("plaintext → HTTP 400 (TLS-only listener)")
|
||
except (ConnectionResetError, http.client.RemoteDisconnected, http.client.BadStatusLine) as e:
|
||
out.append("plaintext → " + type(e).__name__)
|
||
return "; ".join(out)
|
||
|
||
|
||
@case("openbao", "AppRole: токен api — только policy messenger-api, TTL ≤ 5 мин, без default policy")
|
||
def _():
|
||
a = bao_login("api")
|
||
check(a["policies"] == ["messenger-api"] and a["token_policies"] == ["messenger-api"], "policies %s" % a["policies"])
|
||
check(0 < a["lease_duration"] <= 300 and a["renewable"], "ttl %s renewable %s" % (a["lease_duration"], a["renewable"]))
|
||
st, body = bao_call("GET", "auth/token/lookup-self", token=a["client_token"])
|
||
check(st == 200 and body["data"].get("path") == "auth/approle/login", "lookup-self %s" % st)
|
||
check("root" not in body["data"]["policies"], "root policy!")
|
||
return "policies=%s ttl=%ss bound_cidrs=%s" % (a["policies"], a["lease_duration"], body["data"].get("bound_cidrs"))
|
||
|
||
|
||
@case("openbao", "policy api: свой путь — да; чужой путь, list, запись, sys/*, создание токенов — 403")
|
||
def _():
|
||
t = bao_login("api")["client_token"]
|
||
rows = []
|
||
for method, path, body, want in (
|
||
("GET", "secret/data/messenger/api", None, 200),
|
||
("GET", "secret/data/messenger/worker", None, 403),
|
||
("LIST", "secret/metadata/messenger", None, 403),
|
||
("GET", "secret/metadata/messenger/api", None, 403),
|
||
("POST", "secret/data/messenger/api", {"data": {"x": "1"}}, 403),
|
||
("PUT", "sys/policies/acl/evil", {"policy": 'path "*" {capabilities=["sudo"]}'}, 403),
|
||
("GET", "sys/mounts", None, 403),
|
||
("POST", "auth/token/create", {}, 403),
|
||
("GET", "auth/approle/role/messenger-worker/role-id", None, 403),
|
||
("POST", "auth/approle/role/messenger-api/secret-id", {}, 403)):
|
||
st, _ = bao_call(method, path, body, token=t)
|
||
check(st == want, "%s %s: expected %s got %s" % (method, path, want, st))
|
||
rows.append("%s %s→%s" % (method, path.replace("secret/data/messenger/", "kv:"), st))
|
||
return ", ".join(rows)
|
||
|
||
|
||
@case("openbao", "policy worker: только messenger/worker; секреты API (Redis, роль БД API) недоступны")
|
||
def _():
|
||
t = bao_login("worker")["client_token"]
|
||
st1, b1 = bao_call("GET", "secret/data/messenger/worker", token=t)
|
||
st2, _ = bao_call("GET", "secret/data/messenger/api", token=t)
|
||
check(st1 == 200 and st2 == 403, "worker own=%s api=%s" % (st1, st2))
|
||
keys = sorted(b1["data"]["data"])
|
||
check(not any(k.startswith("redis") for k in keys) and b1["data"]["data"]["db_user"].startswith("messenger_worker"),
|
||
"worker KV keys %s" % keys)
|
||
return "own=200 api=403; worker keys=%s (нет admin/owner/redis)" % keys
|
||
|
||
|
||
@case("openbao", "неверный/чужой SecretID и чужой role_id → вход отклонён")
|
||
def _():
|
||
rid = open(BAO + "/api/role_id").read().strip()
|
||
wsid = open(BAO + "/worker/secret_id").read().strip()
|
||
st1, _ = bao_call("POST", "auth/approle/login", {"role_id": rid, "secret_id": str(uuid.uuid4())})
|
||
st2, _ = bao_call("POST", "auth/approle/login", {"role_id": rid, "secret_id": wsid})
|
||
check(st1 in (400, 403) and st2 in (400, 403), "login with bad secret_id: %s/%s" % (st1, st2))
|
||
return "random SecretID → %s; SecretID worker с role_id api → %s" % (st1, st2)
|
||
|
||
|
||
# ======================================================================================= LB → API
|
||
API_HOSTS = None
|
||
|
||
|
||
def api_ips():
|
||
global API_HOSTS
|
||
if API_HOSTS is None:
|
||
API_HOSTS = sorted({a[4][0] for a in socket.getaddrinfo("api", 8443, proto=socket.IPPROTO_TCP)})
|
||
return API_HOSTS
|
||
|
||
|
||
def api_req(ip, identity, path="/health/ready", **kw):
|
||
return https(ip, 8443, path, identity=identity, server_hostname="api", **kw)
|
||
|
||
|
||
@case("lb", "каждая реплика API: identity lb → /health/ready 200; бизнес-API доступен (401 без Bearer)")
|
||
def _():
|
||
ips = api_ips()
|
||
check(len(ips) >= 2, "expected ≥2 API replicas, DNS gives %s" % ips)
|
||
for ip in ips:
|
||
status(api_req(ip, "lb"), 200, ip + " ready")
|
||
status(api_req(ip, "lb", "/api/v1/users/me"), 401, ip + " /users/me")
|
||
return "%d реплик: mTLS lb → 200/401" % len(ips)
|
||
|
||
|
||
@case("lb", "без клиентского сертификата → TLS-отказ (certificate required)")
|
||
def _():
|
||
return "; ".join(denied_tls(api_req(ip, None), ip) for ip in api_ips())
|
||
|
||
|
||
@case("lb", "сертификат ЧУЖОГО CA с identity lb → TLS-отказ (unknown CA)")
|
||
def _():
|
||
return "; ".join(denied_tls(api_req(ip, "foreign-lb"), ip) for ip in api_ips())
|
||
|
||
|
||
@case("lb", "НАШ CA, но identity не lb (worker, api, rogue) → соединение закрыто до HTTP")
|
||
def _():
|
||
out = []
|
||
for ident in ("worker", "api", "rogue", "otel-collector"):
|
||
for ip in api_ips():
|
||
r = api_req(ip, ident, "/api/v1/users/me")
|
||
check(r[0] in ("closed", "tls"), "%s via %s: got %s (identity must be rejected)" % (ident, ip, r[:2]))
|
||
out.append("%s→%s" % (ident, r[0]))
|
||
return ", ".join(out)
|
||
|
||
|
||
@case("lb", "истёкший сертификат lb (тот же CA) → TLS-отказ; отозванный (CRL) → закрыто")
|
||
def _():
|
||
out = []
|
||
for ip in api_ips():
|
||
out.append("expired " + denied_tls(api_req(ip, "expired-lb"), ip))
|
||
r = api_req(ip, "revoked-lb")
|
||
check(r[0] in ("closed", "tls"), "revoked lb accepted by %s: %s" % (ip, r[:2]))
|
||
out.append("revoked → %s" % r[0])
|
||
return "; ".join(out[-2:])
|
||
|
||
|
||
@case("lb", "после ротации leaf LB старый сертификат (отозван в CRL) → закрыто; новый — 200")
|
||
def _():
|
||
if not os.path.exists(ID["old-lb"] + "/tls.crt"):
|
||
return "SKIP: ротация ещё не выполнялась (нет secrets/test/old-lb)"
|
||
for ip in api_ips():
|
||
r = api_req(ip, "old-lb")
|
||
check(r[0] in ("closed", "tls"), "old (rotated) lb cert accepted by %s: %s" % (ip, r[:2]))
|
||
status(api_req(ip, "lb"), 200, ip + " new lb")
|
||
return "old lb → %s на всех репликах; new lb → 200" % r[0]
|
||
|
||
|
||
@case("lb", "сервер API проверяется клиентом: чужое имя (SAN ≠ evil) → ошибка проверки сертификата")
|
||
def _():
|
||
r = https(api_ips()[0], 8443, "/health/ready", identity="lb", server_hostname="evil.example")
|
||
check(r[0] == "tls" and "server cert" in r[1], "hostname mismatch not detected: %s" % (r,))
|
||
return r[1]
|
||
|
||
|
||
@case("lb", "обхода нет: plaintext на :8443 не обслуживается, health-listener :8081 снаружи недоступен")
|
||
def _():
|
||
ip = api_ips()[0]
|
||
out = []
|
||
try:
|
||
c = http.client.HTTPConnection(ip, 8443, timeout=3)
|
||
c.request("GET", "/api/v1/users/me")
|
||
r = c.getresponse()
|
||
raise Fail("plaintext HTTP answered %s" % r.status)
|
||
except (ConnectionResetError, http.client.RemoteDisconnected, http.client.BadStatusLine, OSError) as e:
|
||
out.append("plaintext :8443 → %s" % type(e).__name__)
|
||
try:
|
||
socket.create_connection((ip, 8081), timeout=2).close()
|
||
raise Fail("health listener reachable from network")
|
||
except OSError as e:
|
||
out.append(":8081 → %s" % type(e).__name__)
|
||
return "; ".join(out)
|
||
|
||
|
||
# ======================================================================================= NATS
|
||
def nats_handshake(identity, ca=CA):
|
||
"""Сырой протокол NATS: INFO (plaintext) → TLS с сертификатом identity → CONNECT+PING. None — сервер ответил,
|
||
иначе причина отказа. Нужен ДО nats-py: после закрытия соединения сервером (certificate not pinned) цикл
|
||
чтения nats-py может зациклиться и заблокировать event loop (wait_for не срабатывает)."""
|
||
try:
|
||
raw = socket.create_connection(("nats", 4222), timeout=3)
|
||
raw.settimeout(3)
|
||
raw.recv(4096) # INFO {...}
|
||
s = ctx(identity, ca).wrap_socket(raw, server_hostname="nats")
|
||
s.sendall(b'CONNECT {"verbose":false,"pedantic":false,"tls_required":true,"lang":"python","version":"probe",'
|
||
b'"protocol":1}\r\nPING\r\n')
|
||
data = b""
|
||
while b"\r\n" not in data:
|
||
chunk = s.recv(4096)
|
||
if not chunk:
|
||
return "connection closed by server (certificate not pinned / no user)"
|
||
data += chunk
|
||
s.close()
|
||
line = data.split(b"\r\n")[0].decode(errors="replace")
|
||
return None if line.startswith(("PONG", "INFO", "+OK")) else line[:80]
|
||
except ssl.SSLError as e:
|
||
return "TLS: " + (e.reason or str(e))[:60]
|
||
except OSError as e:
|
||
return type(e).__name__ + ": " + str(e)[:60]
|
||
|
||
|
||
async def nats_try(identity, ca=CA, inbox="_INBOX", actions=None, url="tls://nats:4222"):
|
||
import nats
|
||
errors = []
|
||
|
||
async def ecb(e):
|
||
errors.append(str(e)[:120])
|
||
kw = {}
|
||
if url.startswith("tls://"):
|
||
why = nats_handshake(identity, ca)
|
||
if why:
|
||
return {"connected": False, "error": "refused: " + why, "errors": errors}
|
||
kw = {"tls": ctx(identity, ca), "tls_hostname": "nats"}
|
||
try:
|
||
nc = await asyncio.wait_for(nats.connect(url, connect_timeout=2, allow_reconnect=False, max_reconnect_attempts=0,
|
||
error_cb=ecb, inbox_prefix=inbox.encode(), **kw), 5)
|
||
await nc.flush(timeout=2)
|
||
except BaseException as e: # noqa: BLE001
|
||
return {"connected": False, "error": type(e).__name__ + ": " + str(e)[:80], "errors": errors}
|
||
out = {"connected": True, "errors": errors, "results": {}}
|
||
for name, fn in (actions or {}).items():
|
||
try:
|
||
out["results"][name] = await fn(nc)
|
||
except BaseException as e: # noqa: BLE001
|
||
out["results"][name] = "ERR " + type(e).__name__
|
||
await asyncio.sleep(0.2)
|
||
try:
|
||
await nc.close()
|
||
except BaseException: # noqa: BLE001
|
||
pass
|
||
return out
|
||
|
||
|
||
async def js_req(nc, subject, body=b""):
|
||
try:
|
||
r = await nc.request(subject, body, timeout=1.5)
|
||
return "ok:" + r.data[:60].decode(errors="replace")
|
||
except BaseException as e: # noqa: BLE001
|
||
return "no-response(" + type(e).__name__ + ")"
|
||
|
||
|
||
async def sub_try(nc, subject):
|
||
await nc.subscribe(subject)
|
||
await nc.flush(timeout=1)
|
||
await asyncio.sleep(0.3)
|
||
return "subscribed"
|
||
|
||
|
||
def run(coro):
|
||
return asyncio.run(coro)
|
||
|
||
|
||
@case("nats", "без сертификата / чужой CA / plaintext → отказ подключения")
|
||
def _():
|
||
a = run(nats_try(None))
|
||
b = run(nats_try("foreign-worker", inbox="_INBOX_worker"))
|
||
c = run(nats_try(None, url="nats://nats:4222"))
|
||
for name, r in (("no cert", a), ("foreign CA", b), ("plaintext", c)):
|
||
check(not r["connected"], "%s connected!" % name)
|
||
return "no-cert: %s | foreign: %s | plaintext: %s" % (a["error"][:50], b["error"][:50], c["error"][:50])
|
||
|
||
|
||
@case("nats", "НАШ CA, но не клиент NATS (rogue, lb) → отказ (pinned_certs + нет пользователя)")
|
||
def _():
|
||
out = []
|
||
for ident in ("rogue", "lb"):
|
||
r = run(nats_try(ident, actions={"info": lambda nc: js_req(nc, "$JS.API.STREAM.INFO.ATTACHMENT_JOBS")}))
|
||
ok = (not r["connected"]) or (r["results"].get("info", "").startswith(("no-response", "ERR")))
|
||
check(ok, "%s got access: %s" % (ident, r))
|
||
out.append("%s → %s" % (ident, (r.get("error") or r["results"].get("info"))[:60]))
|
||
return "; ".join(out)
|
||
|
||
|
||
@case("nats", "identity api: публикация заданий — да; consumer/stream admin/чужой inbox — запрещено")
|
||
def _():
|
||
acts = {
|
||
"stream_info": lambda nc: js_req(nc, "$JS.API.STREAM.INFO.ATTACHMENT_JOBS"),
|
||
"fetch_as_consumer": lambda nc: js_req(nc, "$JS.API.CONSUMER.MSG.NEXT.ATTACHMENT_JOBS.attachment-workers",
|
||
b'{"batch":1,"no_wait":true}'),
|
||
"purge_stream": lambda nc: js_req(nc, "$JS.API.STREAM.PURGE.ATTACHMENT_JOBS"),
|
||
"delete_consumer": lambda nc: js_req(nc, "$JS.API.CONSUMER.DELETE.ATTACHMENT_JOBS.attachment-workers"),
|
||
"sub_worker_inbox": lambda nc: sub_try(nc, "_INBOX_worker.>"),
|
||
"sub_jobs": lambda nc: sub_try(nc, "attachments.>"),
|
||
}
|
||
r = run(nats_try("api", inbox="_INBOX_api", actions=acts))
|
||
check(r["connected"], "api cannot connect: %s" % r.get("error"))
|
||
res = r["results"]
|
||
check(res["stream_info"].startswith("ok:"), "stream info denied: %s" % res["stream_info"])
|
||
for k in ("fetch_as_consumer", "purge_stream", "delete_consumer"):
|
||
check(res[k].startswith(("no-response", "ERR")), "api %s allowed: %s" % (k, res[k]))
|
||
viol = [e for e in r["errors"] if "ermission" in e]
|
||
check(len(viol) >= 5, "expected permission violations, got %s" % r["errors"])
|
||
return "stream_info ok; denied: fetch, purge, delete consumer, sub _INBOX_worker.>, sub attachments.> (%d violations)" % len(viol)
|
||
|
||
|
||
@case("nats", "identity worker: свой consumer (info) — да; purge/delete/создание consumer/inbox api — запрещено")
|
||
def _():
|
||
acts = {
|
||
"consumer_info": lambda nc: js_req(nc, "$JS.API.CONSUMER.INFO.ATTACHMENT_JOBS.attachment-workers"),
|
||
"purge_stream": lambda nc: js_req(nc, "$JS.API.STREAM.PURGE.ATTACHMENT_JOBS"),
|
||
"delete_stream": lambda nc: js_req(nc, "$JS.API.STREAM.DELETE.ATTACHMENT_JOBS"),
|
||
"create_consumer": lambda nc: js_req(nc, "$JS.API.CONSUMER.CREATE.ATTACHMENT_JOBS.evil", b"{}"),
|
||
"sub_api_inbox": lambda nc: sub_try(nc, "_INBOX_api.>"),
|
||
}
|
||
r = run(nats_try("worker", inbox="_INBOX_worker", actions=acts))
|
||
check(r["connected"], "worker cannot connect: %s" % r.get("error"))
|
||
res = r["results"]
|
||
check(res["consumer_info"].startswith("ok:"), "consumer info denied: %s" % res["consumer_info"])
|
||
for k in ("purge_stream", "delete_stream", "create_consumer"):
|
||
check(res[k].startswith(("no-response", "ERR")), "worker %s allowed: %s" % (k, res[k]))
|
||
viol = [e for e in r["errors"] if "ermission" in e]
|
||
check(len(viol) >= 4, "expected permission violations, got %s" % r["errors"])
|
||
return "consumer_info ok; denied: purge, delete stream, create consumer, sub _INBOX_api.> (%d violations)" % len(viol)
|
||
|
||
|
||
# ======================================================================================= Collector
|
||
def otlp_logs(marker, service="messenger-api"):
|
||
now = str(time.time_ns())
|
||
return json.dumps({"resourceLogs": [{"resource": {"attributes": [
|
||
{"key": "service.name", "value": {"stringValue": service}}]},
|
||
"scopeLogs": [{"logRecords": [{"timeUnixNano": now, "observedTimeUnixNano": now, "severityNumber": 9,
|
||
"body": {"stringValue": marker}}]}]}]}).encode()
|
||
|
||
|
||
def collector(identity, path="/v1/logs", body=None, ca=CA, port=4318):
|
||
return https("otel-collector", port, path, identity=identity, method="POST" if body is not None else "GET",
|
||
body=body, headers={"Content-Type": "application/json"} if body is not None else None, ca=ca)
|
||
|
||
|
||
@case("collector", "без сертификата / чужой CA → TLS-отказ; rogue и lb (наш CA) → 403")
|
||
def _():
|
||
body = otlp_logs("probe")
|
||
out = ["no-cert " + denied_tls(collector(None, body=body), "no cert"),
|
||
"foreign " + denied_tls(collector("foreign-api", body=body), "foreign")]
|
||
for ident in ("rogue", "lb", "grafana"):
|
||
out.append("%s %s" % (ident, status(collector(ident, body=body), 403, ident)))
|
||
return "; ".join(out)
|
||
|
||
|
||
@case("collector", "api и worker → OTLP 200; self-метрики :8888 — только prometheus")
|
||
def _():
|
||
status(collector("api", body=otlp_logs("probe-ok")), 200, "api")
|
||
status(collector("worker", body=otlp_logs("probe-ok", "messenger-worker")), 200, "worker")
|
||
status(collector("api", "/metrics", port=8888), 403, "api → :8888")
|
||
status(collector("prometheus", "/metrics", port=8888), 200, "prometheus → :8888")
|
||
return "api 200, worker 200; :8888 api 403, prometheus 200"
|
||
|
||
|
||
def loki_query(identity, logql, since=300):
|
||
import urllib.parse
|
||
q = urllib.parse.urlencode({"query": logql, "start": str(int((time.time() - since) * 1e9)),
|
||
"end": str(int(time.time() * 1e9)), "limit": "20"})
|
||
return https("loki", 3100, "/loki/api/v1/query_range?" + q, identity=identity)
|
||
|
||
|
||
@case("collector", "подмена service.name: worker шлёт как messenger-api → сохранено как messenger-worker")
|
||
def _():
|
||
marker = "impersonation-probe-" + uuid.uuid4().hex
|
||
status(collector("worker", body=otlp_logs(marker, "messenger-api")), 200, "worker post")
|
||
deadline = time.time() + 40
|
||
while time.time() < deadline:
|
||
r = loki_query("grafana", '{service_name=~".+"} |= "%s"' % marker)
|
||
if r[0] == "http" and r[1] == 200:
|
||
streams = json.loads(r[2])["data"]["result"]
|
||
if streams:
|
||
labels = streams[0]["stream"]
|
||
check(labels.get("service_name") == "messenger-worker", "stored as %s" % labels.get("service_name"))
|
||
return "Loki: service_name=%s (identity из сертификата, не из данных клиента)" % labels["service_name"]
|
||
time.sleep(2)
|
||
raise Fail("marker not found in Loki in 40s")
|
||
|
||
|
||
# ======================================================================================= telemetry backends
|
||
@case("backends", "Collector только пишет: чтение Loki/Prometheus/Tempo — 403")
|
||
def _():
|
||
out = []
|
||
for host, port, path in (("loki", 3100, "/loki/api/v1/labels"), ("prometheus", 9090, "/api/v1/query?query=up"),
|
||
("tempo", 3200, "/api/search")):
|
||
out.append("%s %s" % (host, status(https(host, port, path, identity="otel-collector"), 403, host)))
|
||
return "; ".join(out)
|
||
|
||
|
||
@case("backends", "Grafana только читает: push Loki, remote write/OTLP/admin Prometheus, OTLP Tempo — 403; query — 200")
|
||
def _():
|
||
out = []
|
||
for host, port, method, path in (("loki", 3100, "POST", "/otlp/v1/logs"), ("loki", 3100, "POST", "/loki/api/v1/push"),
|
||
("prometheus", 9090, "POST", "/api/v1/write"),
|
||
("prometheus", 9090, "POST", "/api/v1/otlp/v1/metrics"),
|
||
("prometheus", 9090, "POST", "/api/v1/admin/tsdb/delete_series?match[]=up"),
|
||
("tempo", 4318, "POST", "/v1/traces")):
|
||
r = https(host, port, path, identity="grafana", method=method, body=b"{}")
|
||
out.append("%s %s %s" % (host, path, status(r, 403, host + path)))
|
||
status(https("prometheus", 9090, "/api/v1/query?query=up", identity="grafana"), 200, "grafana query")
|
||
status(loki_query("grafana", '{service_name="messenger-api"}', 60), 200, "grafana loki query")
|
||
status(https("tempo", 3200, "/api/echo", identity="grafana"), 200, "grafana tempo")
|
||
return "; ".join(out) + "; queries 200"
|
||
|
||
|
||
@case("backends", "rogue/foreign/no-cert к шлюзам → отказ; порты самих backend'ов из сети недоступны")
|
||
def _():
|
||
out = []
|
||
for host, port in (("loki", 3100), ("prometheus", 9090), ("tempo", 3200)):
|
||
check(https(host, port, "/", identity="rogue")[1] == 403, host + " rogue")
|
||
denied_tls(https(host, port, "/", identity="foreign-grafana"), host + " foreign")
|
||
denied_tls(https(host, port, "/", identity=None), host + " no cert")
|
||
out.append("rogue 403, foreign/no-cert TLS-отказ (loki, prometheus, tempo)")
|
||
for host, port in (("loki", 3101), ("prometheus", 9091), ("tempo", 3201), ("tempo", 4319), ("otel-collector", 14318)):
|
||
try:
|
||
socket.create_connection((host, port), timeout=2).close()
|
||
raise Fail("%s:%d reachable" % (host, port))
|
||
except OSError:
|
||
pass
|
||
out.append("loopback-порты 3101/9091/3201/4319/14318 из сети закрыты")
|
||
return "; ".join(out)
|
||
|
||
|
||
# ======================================================================================= PostgreSQL
|
||
def pg(user, password, identity="api", sslmode="verify-full", host="postgres", ca=CA, dbname="messenger"):
|
||
import psycopg
|
||
from messenger.tlsconf import private_key_copy
|
||
kw = {"host": host, "dbname": dbname, "user": user, "sslmode": sslmode, "connect_timeout": 3}
|
||
if password:
|
||
kw["password"] = password
|
||
if sslmode != "disable":
|
||
kw["sslrootcert"] = ca
|
||
if identity:
|
||
kw["sslcert"] = ID[identity] + "/tls.crt"
|
||
kw["sslkey"] = private_key_copy(ID[identity] + "/tls.key")
|
||
return psycopg.connect(**kw, autocommit=True)
|
||
|
||
|
||
def pg_fail(fn):
|
||
try:
|
||
conn = fn()
|
||
conn.close()
|
||
return None
|
||
except Exception as e: # noqa: BLE001
|
||
msg = " ".join(str(e).split()) or type(e).__name__
|
||
return msg.rsplit("failed: ", 1)[-1][:110]
|
||
|
||
|
||
@case("postgres", "plaintext, hostname≠SAN, без client cert, чужой CA, суперпользователь по сети → отказ")
|
||
def _():
|
||
w = kv("worker")
|
||
out = []
|
||
for name, fn in (
|
||
("plaintext", lambda: pg(w["db_user"], w["db_password"], None, sslmode="disable")),
|
||
("hostname mismatch", lambda: pg(w["db_user"], w["db_password"], "worker",
|
||
host=socket.gethostbyname("postgres"))),
|
||
("no client cert", lambda: pg(w["db_user"], w["db_password"], None)),
|
||
("foreign CA cert", lambda: pg(w["db_user"], w["db_password"], "foreign-worker")),
|
||
("wrong password", lambda: pg(w["db_user"], "wrong-" + uuid.uuid4().hex, "worker")),
|
||
("superuser postgres", lambda: pg("postgres", "x", "worker")),
|
||
("owner by worker cert", lambda: pg("messenger_owner", None, "worker"))):
|
||
err = pg_fail(fn)
|
||
check(err is not None, "%s: connection succeeded!" % name)
|
||
out.append("%s: %s" % (name, err[:70]))
|
||
return " | ".join(out)
|
||
|
||
|
||
def pg_try(conn, sql):
|
||
try:
|
||
with conn.transaction():
|
||
conn.execute(sql)
|
||
raise RuntimeError("rollback")
|
||
except RuntimeError:
|
||
return "allowed"
|
||
except Exception as e: # noqa: BLE001
|
||
return type(e).__name__
|
||
|
||
|
||
@case("postgres", "роль worker: только данные вложений/заданий; users/sessions/messages/DDL — permission denied")
|
||
def _():
|
||
w = kv("worker")
|
||
conn = pg(w["db_user"], w["db_password"], "worker")
|
||
rows = {}
|
||
for name, sql, want in (
|
||
("SELECT users.password_hash", "SELECT password_hash FROM users LIMIT 1", "InsufficientPrivilege"),
|
||
("SELECT sessions", "SELECT token_hash FROM sessions LIMIT 1", "InsufficientPrivilege"),
|
||
("SELECT messages", "SELECT text FROM messages LIMIT 1", "InsufficientPrivilege"),
|
||
("SELECT chat_members", "SELECT 1 FROM chat_members LIMIT 1", "InsufficientPrivilege"),
|
||
("UPDATE attachments.owner_id", "UPDATE attachments SET owner_id = owner_id", "InsufficientPrivilege"),
|
||
("DELETE attachments", "DELETE FROM attachments", "InsufficientPrivilege"),
|
||
("CREATE TABLE", "CREATE TABLE evil (x int)", "InsufficientPrivilege"),
|
||
("TRUNCATE job_events", "TRUNCATE job_events", "InsufficientPrivilege"),
|
||
("SELECT attachments", "SELECT id, status FROM attachments LIMIT 1", "allowed"),
|
||
("UPDATE attachments.status", "UPDATE attachments SET status = status WHERE false", "allowed"),
|
||
("SELECT attachment_jobs", "SELECT job_id FROM attachment_jobs LIMIT 1", "allowed")):
|
||
got = pg_try(conn, sql)
|
||
check(got == want, "%s: expected %s got %s" % (name, want, got))
|
||
rows[name] = got
|
||
conn.close()
|
||
return "; ".join("%s→%s" % (k, "ok" if v == "allowed" else "denied") for k, v in rows.items())
|
||
|
||
|
||
@case("postgres", "роль api: нет DDL/DELETE пользователей/смены username/статуса вложений; DML своего пути — да")
|
||
def _():
|
||
a = kv("api")
|
||
conn = pg(a["db_user"], a["db_password"], "api")
|
||
rows = {}
|
||
for name, sql, want in (
|
||
("DELETE users", "DELETE FROM users", "InsufficientPrivilege"),
|
||
("UPDATE users.username", "UPDATE users SET username = username", "InsufficientPrivilege"),
|
||
("UPDATE attachments.status", "UPDATE attachments SET status = status", "InsufficientPrivilege"),
|
||
("INSERT attachment_variants", "INSERT INTO attachment_variants SELECT * FROM attachment_variants LIMIT 0",
|
||
"InsufficientPrivilege"),
|
||
("DROP TABLE", "DROP TABLE messages", "InsufficientPrivilege"),
|
||
("SELECT users", "SELECT id FROM users LIMIT 1", "allowed"),
|
||
("UPDATE users.password_hash", "UPDATE users SET password_hash = password_hash WHERE false", "allowed")):
|
||
got = pg_try(conn, sql)
|
||
check(got == want, "%s: expected %s got %s" % (name, want, got))
|
||
rows[name] = got
|
||
who = conn.execute("SELECT current_user, ssl, version, client_dn FROM pg_stat_ssl JOIN pg_stat_activity USING (pid)"
|
||
" WHERE pid = pg_backend_pid()").fetchone()
|
||
conn.close()
|
||
return "; ".join("%s→%s" % (k, "ok" if v == "allowed" else "denied") for k, v in rows.items()) + \
|
||
"; session: user=%s ssl=%s %s client_dn=%s" % who
|
||
|
||
|
||
# ======================================================================================= Redis
|
||
def redis_client(user, password, identity="api", ca=CA):
|
||
import redis
|
||
kw = dict(host="redis", port=6379, ssl=True, ssl_ca_certs=ca, ssl_cert_reqs="required", ssl_check_hostname=True,
|
||
socket_timeout=3, socket_connect_timeout=3, username=user, password=password)
|
||
if identity:
|
||
kw.update(ssl_certfile=ID[identity] + "/tls.crt", ssl_keyfile=ID[identity] + "/tls.key")
|
||
return redis.Redis(**kw)
|
||
|
||
|
||
def rtry(fn):
|
||
try:
|
||
fn()
|
||
return "allowed"
|
||
except Exception as e: # noqa: BLE001
|
||
return type(e).__name__
|
||
|
||
|
||
@case("redis", "plaintext/без client cert/чужой CA → отказ; default-пользователь выключен")
|
||
def _():
|
||
import redis
|
||
a = kv("api")
|
||
out = {}
|
||
out["plaintext"] = rtry(lambda: redis.Redis(host="redis", port=6379, socket_timeout=2).ping())
|
||
out["no client cert"] = rtry(lambda: redis_client(a["redis_username"], a["redis_password"], None).ping())
|
||
out["foreign CA cert"] = rtry(lambda: redis_client(a["redis_username"], a["redis_password"], "foreign-api").ping())
|
||
out["default user"] = rtry(lambda: redis_client(None, None).ping())
|
||
out["wrong password"] = rtry(lambda: redis_client(a["redis_username"], "wrong").ping())
|
||
for k, v in out.items():
|
||
check(v != "allowed", "%s allowed" % k)
|
||
return "; ".join("%s→%s" % kv_ for kv_ in out.items())
|
||
|
||
|
||
@case("redis", "ACL messenger-api: ключи sess:/rl: — да; KEYS, CONFIG, FLUSHALL, чужие ключи — NOPERM")
|
||
def _():
|
||
a = kv("api")
|
||
r = redis_client(a["redis_username"], a["redis_password"])
|
||
k = "rl:v1:probe:" + uuid.uuid4().hex
|
||
out = {"INCR rl:*": rtry(lambda: r.execute_command("INCR", k)), "GET sess:*": rtry(lambda: r.get("sess:v1:" + uuid.uuid4().hex)),
|
||
"DEL own": rtry(lambda: r.delete(k)),
|
||
"SET other key": rtry(lambda: r.set("evil:" + uuid.uuid4().hex, "1")), "KEYS *": rtry(lambda: r.keys("*")),
|
||
"CONFIG GET": rtry(lambda: r.config_get("*")), "FLUSHALL": rtry(lambda: r.flushall()),
|
||
"ACL LIST": rtry(lambda: r.acl_list()), "PUBLISH": rtry(lambda: r.publish("chan", "x"))}
|
||
for name in ("INCR rl:*", "GET sess:*", "DEL own"):
|
||
check(out[name] == "allowed", "%s: %s" % (name, out[name]))
|
||
for name in ("SET other key", "KEYS *", "CONFIG GET", "FLUSHALL", "ACL LIST", "PUBLISH"):
|
||
check(out[name] in ("NoPermissionError", "ResponseError"), "%s: %s" % (name, out[name]))
|
||
return "; ".join("%s→%s" % (n, "ok" if v == "allowed" else v) for n, v in out.items())
|
||
|
||
|
||
# ======================================================================================= S3
|
||
def s3c(svc):
|
||
from messenger.s3 import S3Client
|
||
d = kv(svc)
|
||
return S3Client("https://s3:9000", "us-east-1", d["s3_access_key_id"], d["s3_secret_access_key"], timeout=5)
|
||
|
||
|
||
async def s3try(coro):
|
||
from messenger.s3 import S3Error
|
||
try:
|
||
r = await coro
|
||
if hasattr(r, "aclose"):
|
||
await r.aclose()
|
||
return "allowed"
|
||
except S3Error as e:
|
||
return e.code or str(e.status)
|
||
|
||
|
||
async def alist(gen):
|
||
return [o async for o in gen]
|
||
|
||
|
||
@case("s3", "TLS: plaintext не обслуживается; чужое имя/CA → ошибка проверки; аноним → 403")
|
||
def _():
|
||
out = []
|
||
try:
|
||
c = http.client.HTTPConnection("s3", 9000, timeout=3)
|
||
c.request("GET", "/" + BUCKET)
|
||
r = c.getresponse()
|
||
check(r.status == 400, "plaintext got %s" % r.status)
|
||
out.append("plaintext → HTTP 400 (TLS-only)")
|
||
except (ConnectionResetError, http.client.RemoteDisconnected, http.client.BadStatusLine) as e:
|
||
out.append("plaintext → " + type(e).__name__)
|
||
r = https(socket.gethostbyname("s3"), 9000, "/", server_hostname="evil.example")
|
||
check(r[0] == "tls", "hostname mismatch accepted %s" % (r,))
|
||
out.append("SAN≠имя → " + r[1][:40])
|
||
out.append("foreign CA → " + denied_tls(https("s3", 9000, "/", ca=FOREIGN_CA), "foreign"))
|
||
status(https("s3", 9000, "/" + BUCKET + "?list-type=2"), 403, "anonymous list")
|
||
out.append("anonymous list → 403")
|
||
return "; ".join(out)
|
||
|
||
|
||
@case("s3", "prefix-права: api не пишет originals/variants и не листит; worker не читает variants и не листит originals")
|
||
def _():
|
||
async def go():
|
||
api, wrk = s3c("api"), s3c("worker")
|
||
key = "probe-" + uuid.uuid4().hex
|
||
res = {
|
||
"api PUT originals/": await s3try(api.put_object(BUCKET, "originals/" + key, b"x")),
|
||
"api PUT variants/": await s3try(api.put_object(BUCKET, "variants/" + key, b"x")),
|
||
"api LIST": await s3try(alist(api.list_objects(BUCKET, "", page_size=1))),
|
||
"api PUT other bucket": await s3try(api.put_object("other-bucket", key, b"x")),
|
||
"worker GET variants/": await s3try(wrk.get_object_stream(BUCKET, "variants/" + key)),
|
||
"worker LIST originals/": await s3try(alist(wrk.list_objects(BUCKET, "originals/", page_size=1))),
|
||
"worker PUT staging→evil/": await s3try(wrk.put_object(BUCKET, "evil/" + key, b"x")),
|
||
"worker CreateBucket": await s3try(wrk.create_bucket("evil-" + key[:8])),
|
||
"api PUT staging/ (own)": await s3try(api.put_object(BUCKET, "staging/" + key, b"x")),
|
||
"worker LIST staging/ (own)": await s3try(alist(wrk.list_objects(BUCKET, "staging/", page_size=1))),
|
||
"worker DELETE staging/ (own)": await s3try(wrk.delete_object(BUCKET, "staging/" + key)),
|
||
}
|
||
await api.aclose()
|
||
await wrk.aclose()
|
||
return res
|
||
res = run(go())
|
||
for k, v in res.items():
|
||
if "(own)" in k:
|
||
check(v == "allowed", "%s: %s" % (k, v))
|
||
else:
|
||
check(v != "allowed", "%s allowed!" % k)
|
||
return "; ".join("%s→%s" % (k, "ok" if v == "allowed" else v) for k, v in res.items())
|
||
|
||
|
||
# ======================================================================================= TLS-аудит всей матрицы
|
||
AUDIT = [ # (endpoint, порт, identity для рукопожатия, требуется ли client cert)
|
||
("api", 8443, "lb", True), ("otel-collector", 4318, "api", True), ("otel-collector", 8888, "prometheus", True),
|
||
("prometheus", 9090, "grafana", True), ("loki", 3100, "grafana", True), ("tempo", 3200, "grafana", True),
|
||
("tempo", 4318, "otel-collector", True), ("redis", 6379, "api", True), ("s3", 9000, None, False),
|
||
("openbao", 8200, None, False), ("grafana", 3000, None, False)]
|
||
|
||
|
||
def tls_details(host, port, identity):
|
||
from cryptography import x509
|
||
raw = socket.create_connection((host, port), timeout=5)
|
||
s = ctx(identity).wrap_socket(raw, server_hostname=host)
|
||
der = s.getpeercert(binary_form=True)
|
||
ver, cipher = s.version(), s.cipher()[0]
|
||
s.close()
|
||
cert = x509.load_der_x509_certificate(der)
|
||
san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
|
||
names = san.get_values_for_type(x509.DNSName)
|
||
days = (cert.not_valid_after_utc - __import__("datetime").datetime.now(__import__("datetime").timezone.utc)).days
|
||
return ver, cipher, names, days, cert.issuer.rfc4514_string()
|
||
|
||
|
||
@case("audit", "TLS-аудит: все TLS-endpoint'ы — TLS ≥ 1.2, наш CA, SAN = имя сервиса, срок > 0; где нужно — mTLS обязателен")
|
||
def _():
|
||
rows = []
|
||
for host, port, ident, need_cert in AUDIT:
|
||
ver, cipher, names, days, issuer = tls_details(host, port, ident)
|
||
check(ver in ("TLSv1.2", "TLSv1.3"), "%s:%d %s" % (host, port, ver))
|
||
check(host in names, "%s:%d SAN %s" % (host, port, names))
|
||
check(days > 0 and "MTUCI lab7 local CA" in issuer, "%s:%d days=%s issuer=%s" % (host, port, days, issuer))
|
||
mtls = "-"
|
||
if need_cert:
|
||
r = https(host, port, "/", identity=None)
|
||
check(r[0] in ("tls", "closed"), "%s:%d accepts clients without certificate: %s" % (host, port, r[:2]))
|
||
mtls = "required"
|
||
old = ssl.create_default_context(cafile=CA)
|
||
old.maximum_version = ssl.TLSVersion.TLSv1_1
|
||
try:
|
||
old.wrap_socket(socket.create_connection((host, port), timeout=3), server_hostname=host).close()
|
||
raise Fail("%s:%d accepts TLS 1.1" % (host, port))
|
||
except ssl.SSLError:
|
||
pass
|
||
rows.append("%s:%d %s %s mTLS=%s days=%d" % (host, port, ver, cipher, mtls, days))
|
||
# протоколы с собственным согласованием TLS: PostgreSQL (SSLRequest), NATS (INFO → TLS)
|
||
w = kv("worker")
|
||
conn = pg(w["db_user"], w["db_password"], "worker")
|
||
v = conn.execute("SELECT version, cipher, client_dn FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
|
||
conn.close()
|
||
rows.append("postgres:5432 %s %s client=%s (hostnossl → reject)" % v)
|
||
r = run(nats_try("worker", inbox="_INBOX_worker"))
|
||
check(r["connected"], "nats worker")
|
||
rows.append("nats:4222 TLS (verify_and_map + pinned_certs) mTLS=required")
|
||
return "; ".join(rows)
|
||
|
||
|
||
@case("audit", "служебные/кластерные порты из сети закрыты: raft OpenBao, SeaweedFS master/volume/filer/gRPC, "
|
||
"мониторинг и cluster/leafnode NATS, plaintext Redis, health API")
|
||
def _():
|
||
targets = [("openbao", 8201), ("s3", 9333), ("s3", 19333), ("s3", 8080), ("s3", 18080), ("s3", 8888),
|
||
("s3", 18888), ("nats", 8222), ("nats", 6222), ("nats", 7422), ("redis", 6380)]
|
||
targets += [(ip, 8081) for ip in api_ips()]
|
||
opened = []
|
||
for host, port in targets:
|
||
try:
|
||
socket.create_connection((host, port), timeout=2).close()
|
||
opened.append("%s:%d" % (host, port))
|
||
except OSError:
|
||
pass
|
||
check(not opened, "reachable: %s" % opened)
|
||
return "закрыты: " + ", ".join("%s:%d" % t for t in targets[:11]) + " и :8081 всех реплик API"
|
||
|
||
|
||
# ======================================================================================= main
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--only", default="", help="группы через запятую: openbao,lb,nats,collector,backends,postgres,redis,s3,audit")
|
||
ap.add_argument("--json", help="сохранить сводку (без секретов)")
|
||
a = ap.parse_args()
|
||
only = {x for x in a.only.split(",") if x}
|
||
print("## internal trust matrix (probe container, %s)" % time.strftime("%Y-%m-%d %H:%M:%S"))
|
||
passed = failed = 0
|
||
for row in RESULTS:
|
||
group, title, fn = row[0], row[1], row[2]
|
||
if only and group not in only:
|
||
continue
|
||
t0 = time.monotonic()
|
||
try:
|
||
detail = fn() or ""
|
||
row[3], row[4] = "PASS", detail
|
||
passed += 1
|
||
except Fail as e:
|
||
row[3], row[4] = "FAIL", str(e)
|
||
failed += 1
|
||
except Exception as e: # noqa: BLE001
|
||
row[3], row[4] = "FAIL", "%s: %s" % (type(e).__name__, str(e)[:200])
|
||
traceback.print_exc(limit=2)
|
||
failed += 1
|
||
print("%s [%s] %s (%.1fs)\n %s" % (row[3], group, title, time.monotonic() - t0, row[4]), flush=True)
|
||
print("summary: %d passed, %d failed" % (passed, failed))
|
||
if a.json:
|
||
with open(a.json, "w") as fh:
|
||
json.dump([{"group": r[0], "check": r[1], "result": r[3], "detail": r[4]} for r in RESULTS if r[3]], fh,
|
||
ensure_ascii=False, indent=1)
|
||
sys.exit(1 if failed else 0)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|