forked from mtusi2026/mtusi2026lab7
ЛР7
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
"""Общее для tls_matrix.py и acl_matrix.py: пути к сертификатам, TLS-контексты, вход в OpenBao, таблица.
|
||||
|
||||
Оба скрипта выполняются в контейнере sectest (make tls-matrix / make acl-matrix): он в сетях
|
||||
edge, backend, otlp, telemetry, vault и видит сертификаты только на чтение:
|
||||
/pki/tls/<identity>/tls.{crt,key} сертификаты сервисов (наш CA)
|
||||
/pki/tls/ca/ca.crt наш CA
|
||||
/pki/test/intruder наш CA, но identity, которой нет в матрице
|
||||
/pki/test/rogue-lb identity "lb", но выдан ЧУЖИМ CA
|
||||
/pki/test/lb-expired identity "lb" нашего CA, срок истёк
|
||||
Хост-утилит (docker, psql) здесь нет: всё проверяется по сети, как это видит любой сервис стенда.
|
||||
Значения секретов не печатаются никогда — только «есть / нет / разрешено / запрещено».
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PKI = Path(os.environ.get("PKI_DIR", "/pki"))
|
||||
CA = str(PKI / "tls" / "ca" / "ca.crt")
|
||||
ROGUE_CA = str(PKI / "test" / "rogue-ca" / "ca.crt")
|
||||
BAO = "https://openbao:8200"
|
||||
|
||||
|
||||
def cert(identity: str) -> tuple[str, str]:
|
||||
"""(cert, key) identity: сервисы — из /pki/tls, тестовые intruder/rogue-lb/lb-expired — из /pki/test."""
|
||||
base = PKI / ("test" if identity in ("intruder", "rogue-lb", "lb-expired") else "tls") / identity
|
||||
return str(base / "tls.crt"), str(base / "tls.key")
|
||||
|
||||
|
||||
def client_context(identity: str | None = None, cafile: str = CA, hostname: bool = True) -> ssl.SSLContext:
|
||||
"""Клиентский TLS: сервер проверяется нашим CA (и по имени), клиент предъявляет identity (если задана)."""
|
||||
context = ssl.create_default_context(cafile=cafile)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = hostname
|
||||
if identity:
|
||||
context.load_cert_chain(*cert(identity))
|
||||
return context
|
||||
|
||||
|
||||
class Matrix:
|
||||
"""Строки «кто -> куда: действие | ожидание | результат». В конце — итог и код выхода."""
|
||||
|
||||
def __init__(self, title: str):
|
||||
self.title, self.rows, self.failed = title, 0, []
|
||||
print(title)
|
||||
print("=" * len(title))
|
||||
|
||||
def section(self, name: str):
|
||||
print(f"\n## {name}")
|
||||
|
||||
def row(self, who: str, what: str, expect: str, got: str, ok: bool):
|
||||
self.rows += 1
|
||||
mark = "OK " if ok else "FAIL"
|
||||
print(f"{mark} {who:<16} {what:<52} expect {expect:<8} got {got}")
|
||||
if not ok:
|
||||
self.failed.append(f"{who}: {what} (expect {expect}, got {got})")
|
||||
|
||||
def allow(self, who: str, what: str, outcome: tuple[bool, str]):
|
||||
self.row(who, what, "allow", outcome[1], outcome[0])
|
||||
|
||||
def deny(self, who: str, what: str, outcome: tuple[bool, str]):
|
||||
"""outcome = (allowed?, подробность). Для deny успех — когда НЕ разрешено."""
|
||||
self.row(who, what, "deny", outcome[1], not outcome[0])
|
||||
|
||||
def finish(self) -> int:
|
||||
print()
|
||||
if self.failed:
|
||||
print(f"FAIL: {len(self.failed)} of {self.rows} checks")
|
||||
for line in self.failed:
|
||||
print(" - " + line)
|
||||
return 1
|
||||
print(f"PASS: {self.rows} checks")
|
||||
return 0
|
||||
|
||||
|
||||
def bao_call(method: str, path: str, identity: str | None = None, token: str | None = None,
|
||||
body: dict | None = None, cafile: str = CA) -> tuple[int, dict]:
|
||||
"""HTTP к OpenBao. Возвращает (status, json). Ошибку TLS-рукопожатия пробрасывает как ssl.SSLError."""
|
||||
request = urllib.request.Request(f"{BAO}/v1/{path}", method=method,
|
||||
data=None if body is None else json.dumps(body).encode())
|
||||
request.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
request.add_header("X-Vault-Token", token)
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=client_context(identity, cafile), timeout=10) as response:
|
||||
raw, status = response.read(), response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw, status = exc.read(), exc.code
|
||||
except urllib.error.URLError as exc:
|
||||
if isinstance(exc.reason, ssl.SSLError):
|
||||
raise exc.reason from None
|
||||
raise
|
||||
try:
|
||||
return status, json.loads(raw or b"{}")
|
||||
except ValueError:
|
||||
return status, {}
|
||||
|
||||
|
||||
def bao_login(identity: str, role: str) -> tuple[int, dict]:
|
||||
"""POST auth/cert/login {"name": role} с сертификатом identity."""
|
||||
return bao_call("POST", "auth/cert/login", identity=identity, body={"name": role})
|
||||
|
||||
|
||||
def bao_secret(identity: str) -> dict:
|
||||
"""Секрет своей роли (api -> messenger-api, worker -> messenger-worker): нужен для проверок БД/S3/Valkey."""
|
||||
status, payload = bao_login(identity, f"messenger-{identity}")
|
||||
if status != 200:
|
||||
sys.exit(f"cannot log in to OpenBao as {identity}: HTTP {status} (is OpenBao unsealed? make bao-unseal)")
|
||||
token = payload["auth"]["client_token"]
|
||||
status, payload = bao_call("GET", f"secret/data/messenger/{identity}", token=token)
|
||||
if status != 200:
|
||||
sys.exit(f"cannot read the secret of {identity}: HTTP {status}")
|
||||
return payload["data"]["data"]
|
||||
|
||||
|
||||
def short(exc: BaseException) -> str:
|
||||
"""Короткое имя ошибки без значений (в тексте исключений драйверов бывает DSN)."""
|
||||
text = str(exc).strip().splitlines()[0] if str(exc).strip() else ""
|
||||
for word in ("password", "secret"):
|
||||
if word in text.lower():
|
||||
text = ""
|
||||
return f"{type(exc).__name__}{': ' + text[:70] if text else ''}"
|
||||
Reference in New Issue
Block a user