forked from mtusi2026/mtusi2026lab7
258 lines
9.9 KiB
Python
258 lines
9.9 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
|
||
from pika.credentials import ExternalCredentials
|
||
|
||
try:
|
||
params = pika.ConnectionParameters(
|
||
host=args.host,
|
||
port=args.port,
|
||
virtual_host="/",
|
||
credentials=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", "")
|
||
# Отозванный/удалённый ключ 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)
|
||
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 = []
|
||
# Ограниченное окно и 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=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:
|
||
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=20, 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()
|