lab7: mTLS-границы, OpenBao raft, TLS-телеметрия, evidence уровней 3-4

This commit is contained in:
2026-11-27 23:05:20 +03:00
parent 6b44b067c4
commit cf6b78f899
31 changed files with 572 additions and 116 deletions
+36 -9
View File
@@ -52,13 +52,14 @@ def cmd_api(args):
def cmd_broker(args):
import pika
from pika.credentials import ExternalCredentials
try:
params = pika.ConnectionParameters(
host=args.host,
port=args.port,
virtual_host="/",
credentials=pika.ExternalCredentials(),
credentials=ExternalCredentials(),
ssl_options=pika.SSLOptions(tls_context(args.ca, args.cert, args.key),
server_hostname=args.host),
connection_attempts=1,
@@ -129,14 +130,19 @@ def cmd_s3(args):
emit({"result": "ok", "key": key})
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
emit({"result": "denied" if code in ("AccessDenied", "403", "AllAccessDisabled") else "error",
"code": code})
# Отозванный/удалённый ключ MinIO отвергает как InvalidAccessKeyId —
# это тоже отказ в доступе, а не сбой пробы.
denied_codes = ("AccessDenied", "403", "AllAccessDisabled",
"InvalidAccessKeyId", "SignatureDoesNotMatch", "InvalidToken")
emit({"result": "denied" if code in denied_codes else "error", "code": code})
except BotoCoreError as exc:
emit({"result": "error", "error": type(exc).__name__})
def cmd_leak(args):
import re
import time
import urllib.parse
import urllib.request
ctx = tls_context(args.ca)
@@ -147,14 +153,35 @@ def cmd_leak(args):
re.compile(r"(?i)-----BEGIN [A-Z ]*PRIVATE KEY-----"),
]
matches = []
url = ('https://loki:3100/loki/api/v1/query_range?'
'query=%7Bservice_name%3D%22messenger-api%22%7D&limit=500')
# Ограниченное окно и backward-чтение: без start/end Loki сканирует весь
# retention и на объёмных логах легко не укладывается в таймаут.
end_ns = int(time.time() * 1e9)
start_ns = end_ns - 30 * 60 * 10**9
url = "https://loki:3100/loki/api/v1/query_range?" + urllib.parse.urlencode({
"query": '{service_name="messenger-api"}',
"start": str(start_ns),
"end": str(end_ns),
"limit": "200",
"direction": "backward",
})
try:
with urllib.request.urlopen(url, timeout=15, context=ctx) as resp:
lines = [json.loads(item)[1] for stream in
json.load(resp)["data"]["result"] for item in stream["values"]]
with urllib.request.urlopen(url, timeout=45, context=ctx) as resp:
raw = resp.read()
except urllib.error.HTTPError as exc:
body = exc.read()[:200].decode("utf-8", "replace")
emit({"result": "error", "error": "loki_http_%d" % exc.code, "body": body})
except Exception as exc: # noqa: BLE001
emit({"result": "error", "error": type(exc).__name__})
try:
payload = json.loads(raw)
# В query_range values — это [[ns_timestamp, line], ...], строки уже
# разобраны (json.loads нужен только для push-формата).
lines = [item[1]
for stream in (payload.get("data", {}).get("result") or [])
for item in stream["values"]]
except Exception as exc: # noqa: BLE001
emit({"result": "error", "error": "loki_payload_" + type(exc).__name__,
"body": raw[:200].decode("utf-8", "replace")})
for line in lines:
for pattern in patterns:
@@ -165,7 +192,7 @@ def cmd_leak(args):
labels = []
try:
with urllib.request.urlopen("https://prometheus:9090/api/v1/labels",
timeout=10, context=ctx) as resp:
timeout=20, context=ctx) as resp:
labels = json.load(resp)["data"]
except Exception as exc: # noqa: BLE001
emit({"result": "error", "error": "prometheus:" + type(exc).__name__})
+18 -6
View File
@@ -69,17 +69,22 @@ def http(method, path, body=None, headers=None, token=None, base=None, ca=None,
for key, value in (headers or {}).items():
request.add_header(key, value)
context = ssl.create_default_context(cafile=ca or CA_PUBLIC)
# h11/uvicorn отдают имена заголовков в нижнем регистре; dict() сделал бы
# поиск регистрозависимым, поэтому нормализуем ключи сами.
def _headers(message):
return {key.lower(): value for key, value in message.items()}
try:
with urllib.request.urlopen(request, timeout=timeout, context=context) as resp:
raw = resp.read()
return resp.status, dict(resp.headers), json.loads(raw) if raw else None
return resp.status, _headers(resp.headers), json.loads(raw) if raw else None
except urllib.error.HTTPError as exc:
raw = exc.read()
try:
parsed = json.loads(raw) if raw else None
except ValueError:
parsed = None
return exc.code, dict(exc.headers), parsed
return exc.code, _headers(exc.headers), parsed
def new_user(prefix="probe"):
@@ -145,6 +150,9 @@ def hostname_probe():
except ssl.SSLCertVerificationError as exc:
return "cert_error:" + (exc.verify_message or type(exc).__name__)
except urllib.error.URLError as exc:
# urlopen оборачивает ошибку проверки сертификата в URLError.
if isinstance(exc.reason, ssl.SSLCertVerificationError):
return "cert_error:" + (exc.reason.verify_message or type(exc.reason).__name__)
return "url_error:" + type(exc.reason).__name__
@@ -268,8 +276,12 @@ def main():
check("OTLP ingress: same-CA foreign identity rejected",
otlp_rogue.get("result") == "http" and otlp_rogue.get("status") == 403, str(otlp_rogue))
otlp_none = probe("otlp")
# nginx с `ssl_verify_client on` на отсутствие сертификата отвечает 400
# (внутренний 496), а не рвёт TLS-рукопожатие — отказ всё равно есть.
check("OTLP ingress: no client certificate rejected",
otlp_none.get("result") == "tls_error", str(otlp_none))
otlp_none.get("result") == "tls_error"
or (otlp_none.get("result") == "http" and otlp_none.get("status") in (400, 403)),
str(otlp_none))
# 6. S3: TLS + раздельные scoped credentials.
api_key = (ROOT / "secrets/s3_api_access_key").read_text().strip()
@@ -448,10 +460,10 @@ def main():
for _ in range(40):
status, headers, _ = login(lim_name, "wrong-password-" + uuid.uuid4().hex)
statuses.append(status)
if headers.get("X-Instance-Id"):
instances.add(headers["X-Instance-Id"])
if headers.get("x-instance-id"):
instances.add(headers["x-instance-id"])
if status == 429:
retry_after = headers.get("Retry-After")
retry_after = headers.get("retry-after")
break
check("rate limit: 429 returned", 429 in statuses,
"statuses=" + ",".join(map(str, statuses[-5:])))