Files
mtusi2026lab7-fork/scripts/audit_tls.py
T

141 lines
5.6 KiB
Python

"""Проверки TLS внутри сети Compose на закреплённых версиях клиентов."""
import asyncio
from pathlib import Path
import socket
import ssl
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
import aio_pika
import asyncpg
from aiormq.exceptions import ChannelAccessRefused
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
from app.core.jobs import JobSettings
from app.storage.broker import connect_broker
CERTS = Path("/certificates")
def context(identity=None):
tls = ssl.create_default_context(cafile=str(CERTS / "ca.crt"))
if identity:
tls.load_cert_chain(CERTS / f"{identity}.crt", CERTS / f"{identity}.key")
return tls
def http(host, port, path, identity=None, *, body=None):
request = Request(f"https://{host}:{port}{path}", data=body, headers={
"Content-Type": "application/x-protobuf",
})
try:
with urlopen(request, context=context(identity), timeout=4) as response:
return response.status
except HTTPError as error:
return error.code
except (ssl.SSLError, ConnectionError):
return 0
except URLError as error:
if isinstance(error.reason, (ssl.SSLError, ConnectionError)):
return 0
raise
def check_http():
for role in ("otel-api", "otel-worker", "otel-publisher"):
assert http("otel-collector", 4318, "/v1/traces", role, body=b"") == 200
assert http("otel-collector", 4318, "/v1/traces", "otel-wrong-role", body=b"") == 403
for role in (None, "foreign-client"):
assert http("otel-collector", 4318, "/v1/traces", role, body=b"") in (0, 400)
for port in (8888, 8889):
assert http("otel-collector", port, "/metrics", "otel-scraper") == 200
assert http("otel-collector", port, "/metrics", "otel-api") in (0, 400)
status = http("loki", 3100, "/loki/api/v1/labels", "otel-reader")
assert status == 200, ("loki", status)
status = http("tempo", 3200, "/api/search?limit=1", "otel-reader")
assert status == 200, ("tempo", status)
assert http("prometheus", 9090, "/-/ready", "otel-reader") == 200
assert http("tempo", 4318, "/v1/traces", "otel-writer", body=b"") == 200
assert http("tempo", 4318, "/v1/traces", "otel-reader", body=b"") == 0
logs = ExportLogsServiceRequest()
resource = logs.resource_logs.add()
resource.resource.attributes.add(key="service.name").value.string_value = "tls-audit"
event = resource.scope_logs.add().log_records.add(time_unix_nano=time.time_ns())
event.body.string_value = "synthetic TLS audit"
status = http("loki", 3100, "/otlp/v1/logs", "otel-writer", body=logs.SerializeToString())
assert status in (200, 204), ("loki ingest", status)
assert http("loki", 3100, "/ready", "otel-api") == 0
assert http("grafana", 3000, "/api/datasources") == 401
assert http("minio", 9000, "/minio/health/ready") == 200
assert http("openbao", 8200, "/v1/sys/health") == 200
for port in (14318, 8887, 13133):
try:
with socket.create_connection(("otel-collector", port), 2):
pass
except ConnectionRefusedError:
continue
raise AssertionError(f"Loopback-порт Collector {port} доступен извне")
async def check_broker():
async def connect(identity):
return await connect_broker(JobSettings(
broker_port=5671, broker_ca_file=str(CERTS / "ca.crt"),
broker_cert_file=str(CERTS / f"{identity}.crt"),
broker_key_file=str(CERTS / f"{identity}.key"),
))
for role in ("api-broker", "attachment-worker", "attachment-publisher"):
async with await connect(role) as connection:
assert not connection.is_closed
for role in ("broker-wrong-role", "foreign-client"):
try:
async with await connect(role):
pass
except (aio_pika.exceptions.AMQPException, OSError):
continue
raise AssertionError(f"RabbitMQ принял запрещённую identity: {role}")
try:
async with await aio_pika.connect(host="broker", port=5671, ssl=True,
ssl_context=context(), auth="external", timeout=4):
pass
except (aio_pika.exceptions.AMQPException, OSError):
pass
else:
raise AssertionError("RabbitMQ принял соединение без сертификата")
async with await connect("api-broker") as connection:
channel = await connection.channel()
try:
await channel.declare_queue("scope-audit-probe", auto_delete=True)
except ChannelAccessRefused:
pass
else:
raise AssertionError("Роль API смогла объявить очередь")
async def check_database():
try:
await asyncpg.connect(host="postgres", user="worker", database="postgres",
ssl=False, timeout=3)
except asyncpg.InvalidAuthorizationSpecificationError as error:
assert "rejects connection" in str(error)
else:
raise AssertionError("PostgreSQL принял plaintext")
with socket.create_connection(("redis", 6379), 3) as raw:
with context().wrap_socket(raw, server_hostname="redis") as tls:
tls.sendall(b"*1\r\n$4\r\nPING\r\n")
assert tls.recv(128).startswith(b"-NOAUTH")
if __name__ == "__main__":
check_http()
asyncio.run(check_broker())
asyncio.run(check_database())
print("PASS: TLS-зависимости, mTLS identity и ACL RabbitMQ/Collector")