- student-tests: mTLS-матрица LB->API, broker и OTLP, ACL и scoped policy OpenBao, rehash, ротация/отзыв identity, sealed OpenBao, утечки в telemetry, rate limit с 429/Retry-After - заполнены REPORT.md (доказательства по уровням 3-4, эксперименты, scan triage), contracts/trust-matrix.md, security/THREAT_MODEL.md (10 угроз), RUNBOOK.md (bootstrap, ротация, unseal, диагностика) - Makefile: up/down/ps/logs/bootstrap/scan/test-lab7/rotate-* Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
231 lines
8.5 KiB
Python
231 lines
8.5 KiB
Python
#!/usr/bin/env python3
|
|
"""TLS/mTLS probes for lab7. Executed inside the `mtls-probe` container.
|
|
|
|
Every probe prints exactly one JSON object with a `result` field:
|
|
ok — expected positive outcome
|
|
http — HTTP response received (status in `status`)
|
|
access_denied — broker refused the operation (ACL)
|
|
tls_error — TLS handshake/validation failed
|
|
connect_error — connection refused/closed before protocol
|
|
denied — S3 returned AccessDenied
|
|
error — anything else (see `error`)
|
|
"""
|
|
import argparse
|
|
import json
|
|
import ssl
|
|
import sys
|
|
import uuid
|
|
|
|
|
|
def tls_context(ca, cert=None, key=None):
|
|
ctx = ssl.create_default_context(cafile=ca)
|
|
if cert:
|
|
ctx.load_cert_chain(cert, key)
|
|
return ctx
|
|
|
|
|
|
def emit(payload, code=0):
|
|
print(json.dumps(payload, ensure_ascii=False))
|
|
sys.exit(code)
|
|
|
|
|
|
def cmd_api(args):
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
url = "https://%s:%d%s" % (args.host, args.port, args.path)
|
|
try:
|
|
ctx = tls_context(args.ca, args.cert, args.key)
|
|
request = urllib.request.Request(url)
|
|
with urllib.request.urlopen(request, timeout=10, context=ctx) as resp:
|
|
emit({"result": "ok", "status": resp.status})
|
|
except urllib.error.HTTPError as exc:
|
|
emit({"result": "http", "status": exc.code})
|
|
except urllib.error.URLError as exc:
|
|
reason = exc.reason
|
|
if isinstance(reason, (ssl.SSLError, ssl.CertificateError)):
|
|
emit({"result": "tls_error", "error": type(reason).__name__})
|
|
emit({"result": "error", "error": type(reason).__name__})
|
|
except ssl.SSLError as exc:
|
|
emit({"result": "tls_error", "error": type(exc).__name__})
|
|
|
|
|
|
def cmd_broker(args):
|
|
import pika
|
|
|
|
try:
|
|
params = pika.ConnectionParameters(
|
|
host=args.host,
|
|
port=args.port,
|
|
virtual_host="/",
|
|
credentials=pika.ExternalCredentials(),
|
|
ssl_options=pika.SSLOptions(tls_context(args.ca, args.cert, args.key),
|
|
server_hostname=args.host),
|
|
connection_attempts=1,
|
|
socket_timeout=10,
|
|
heartbeat=0,
|
|
)
|
|
conn = pika.BlockingConnection(params)
|
|
except Exception as exc: # noqa: BLE001 - probe must classify any failure
|
|
emit({"result": "connect_error", "error": type(exc).__name__})
|
|
|
|
try:
|
|
channel = conn.channel()
|
|
if args.foreign_queue:
|
|
try:
|
|
channel.queue_declare("foreign.probe." + uuid.uuid4().hex[:8],
|
|
durable=False, auto_delete=True)
|
|
emit({"result": "forbidden_allowed"})
|
|
except pika.exceptions.ChannelClosedByBroker as exc:
|
|
emit({"result": "access_denied", "code": getattr(exc, "reply_code", None)})
|
|
channel.queue_declare("attachment.process.v1", passive=True)
|
|
emit({"result": "ok"})
|
|
except pika.exceptions.ChannelClosedByBroker as exc:
|
|
emit({"result": "access_denied", "code": getattr(exc, "reply_code", None)})
|
|
except Exception as exc: # noqa: BLE001
|
|
emit({"result": "error", "error": type(exc).__name__})
|
|
finally:
|
|
try:
|
|
conn.close()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
|
|
|
|
def cmd_otlp(args):
|
|
import http.client
|
|
|
|
try:
|
|
conn = http.client.HTTPSConnection(
|
|
args.host, args.port, timeout=10,
|
|
context=tls_context(args.ca, args.cert, args.key))
|
|
conn.request("POST", args.path, body=b"", headers={"Content-Type": "application/x-protobuf"})
|
|
response = conn.getresponse()
|
|
response.read()
|
|
emit({"result": "http", "status": response.status})
|
|
except ssl.SSLError as exc:
|
|
emit({"result": "tls_error", "error": type(exc).__name__})
|
|
except (OSError, http.client.HTTPException) as exc:
|
|
emit({"result": "error", "error": type(exc).__name__})
|
|
|
|
|
|
def cmd_s3(args):
|
|
import boto3
|
|
from botocore.config import Config
|
|
from botocore.exceptions import BotoCoreError, ClientError
|
|
|
|
client = boto3.client(
|
|
"s3",
|
|
endpoint_url=args.endpoint,
|
|
region_name="us-east-1",
|
|
aws_access_key_id=args.access_key,
|
|
aws_secret_access_key=args.secret,
|
|
verify=args.ca,
|
|
config=Config(signature_version="s3v4", s3={"addressing_style": "path"},
|
|
connect_timeout=5, read_timeout=10, retries={"max_attempts": 0}),
|
|
)
|
|
key = args.key_prefix.rstrip("/") + "/probe-" + uuid.uuid4().hex
|
|
try:
|
|
client.put_object(Bucket=args.bucket, Key=key, Body=b"probe", ContentType="image/png")
|
|
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})
|
|
except BotoCoreError as exc:
|
|
emit({"result": "error", "error": type(exc).__name__})
|
|
|
|
|
|
def cmd_leak(args):
|
|
import re
|
|
import urllib.request
|
|
|
|
ctx = tls_context(args.ca)
|
|
patterns = [
|
|
re.compile(r"(?i)(password|passwd|secret|token|authorization)\s*[=:]\s*\S{8,}"),
|
|
re.compile(r"(?i)bearer\s+[A-Za-z0-9._~+/=-]{16,}"),
|
|
re.compile(r"(?i)x-vault-token"),
|
|
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')
|
|
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"]]
|
|
except Exception as exc: # noqa: BLE001
|
|
emit({"result": "error", "error": type(exc).__name__})
|
|
|
|
for line in lines:
|
|
for pattern in patterns:
|
|
found = pattern.search(line)
|
|
if found:
|
|
matches.append(found.group(0)[:60])
|
|
|
|
labels = []
|
|
try:
|
|
with urllib.request.urlopen("https://prometheus:9090/api/v1/labels",
|
|
timeout=10, context=ctx) as resp:
|
|
labels = json.load(resp)["data"]
|
|
except Exception as exc: # noqa: BLE001
|
|
emit({"result": "error", "error": "prometheus:" + type(exc).__name__})
|
|
|
|
forbidden_labels = [lab for lab in labels
|
|
if lab in ("user_id", "chat_id", "message_id", "attachment_id",
|
|
"request_id", "filename")]
|
|
emit({"result": "leak" if (matches or forbidden_labels) else "ok",
|
|
"log_matches": matches[:10], "forbidden_labels": forbidden_labels,
|
|
"lines_scanned": len(lines)})
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
|
|
api = sub.add_parser("api")
|
|
api.add_argument("--host", default="api")
|
|
api.add_argument("--port", type=int, default=8443)
|
|
api.add_argument("--path", default="/health/live")
|
|
api.add_argument("--ca", default="/pki/trust/ca-clients-bundle.crt")
|
|
api.add_argument("--cert")
|
|
api.add_argument("--key")
|
|
api.set_defaults(func=cmd_api)
|
|
|
|
broker = sub.add_parser("broker")
|
|
broker.add_argument("--host", default="rabbitmq")
|
|
broker.add_argument("--port", type=int, default=5671)
|
|
broker.add_argument("--ca", default="/pki/trust/ca-clients-bundle.crt")
|
|
broker.add_argument("--cert")
|
|
broker.add_argument("--key")
|
|
broker.add_argument("--foreign-queue", action="store_true")
|
|
broker.set_defaults(func=cmd_broker)
|
|
|
|
otlp = sub.add_parser("otlp")
|
|
otlp.add_argument("--host", default="ingress")
|
|
otlp.add_argument("--port", type=int, default=4318)
|
|
otlp.add_argument("--path", default="/v1/logs")
|
|
otlp.add_argument("--ca", default="/pki/trust/ca-servers-bundle.crt")
|
|
otlp.add_argument("--cert")
|
|
otlp.add_argument("--key")
|
|
otlp.set_defaults(func=cmd_otlp)
|
|
|
|
s3 = sub.add_parser("s3")
|
|
s3.add_argument("--endpoint", default="https://minio:9000")
|
|
s3.add_argument("--ca", default="/pki/trust/ca-servers-bundle.crt")
|
|
s3.add_argument("--bucket", default="messenger-attachments")
|
|
s3.add_argument("--access-key", required=True)
|
|
s3.add_argument("--secret", required=True)
|
|
s3.add_argument("--key-prefix", required=True, choices=["staging", "originals"])
|
|
s3.set_defaults(func=cmd_s3)
|
|
|
|
leak = sub.add_parser("leak")
|
|
leak.add_argument("--ca", default="/pki/trust/ca-servers-bundle.crt")
|
|
leak.set_defaults(func=cmd_leak)
|
|
|
|
args = parser.parse_args()
|
|
args.func(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|