forked from mtusi2026/mtusi2026lab7
lab 7
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check actual containers, restricted mounts and telemetry without printing secrets."""
|
||||
|
||||
# ruff: noqa: E402 -- repository scripts are imported after setting their path.
|
||||
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client
|
||||
from securitylib import LOCAL, OPERATOR, compose, request, root_token, tls
|
||||
|
||||
|
||||
def main():
|
||||
rows = []
|
||||
|
||||
def ok(check, **values):
|
||||
rows.append({"check": check, "result": "PASS", **values})
|
||||
|
||||
containers = compose("ps", "-q", capture=True).split()
|
||||
details = json.loads(subprocess.check_output(["docker", "inspect", *containers], text=True))
|
||||
for item in details:
|
||||
role = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
config = item["HostConfig"]
|
||||
assert not config["Privileged"] and config["NetworkMode"] != "host"
|
||||
assert all("docker.sock" not in mount["Source"] for mount in item["Mounts"])
|
||||
assert "no-new-privileges:true" in config["SecurityOpt"]
|
||||
assert config["Memory"] > 0 and config["NanoCpus"] > 0
|
||||
for binding in (config.get("PortBindings") or {}).values():
|
||||
assert all(entry["HostIp"] == "127.0.0.1" for entry in binding)
|
||||
if role != "postgres":
|
||||
assert config["ReadonlyRootfs"] and "ALL" in config["CapDrop"]
|
||||
if role in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
assert item["Config"]["User"] == "10001:10001"
|
||||
assert config["ReadonlyRootfs"] and "ALL" in config["CapDrop"]
|
||||
assert all("/operator" not in mount["Source"] for mount in item["Mounts"])
|
||||
env = dict(value.split("=", 1) for value in item["Config"]["Env"])
|
||||
assert not any(
|
||||
name in env
|
||||
for name in [
|
||||
"DATABASE_URL",
|
||||
"ADMIN_PASSWORD",
|
||||
"MINIO_ROOT_PASSWORD",
|
||||
"BAO_TOKEN",
|
||||
"S3_SECRET_ACCESS_KEY",
|
||||
]
|
||||
)
|
||||
ok("container-hardening:" + role)
|
||||
c = Client("https://localhost:8443", str(LOCAL / "trust/ca.crt"))
|
||||
actor = c.user("leak")
|
||||
response = c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
traceid = response["headers"]["X-Trace-Id"]
|
||||
forbidden = []
|
||||
values = json.loads((OPERATOR / "credentials.json").read_text())
|
||||
forbidden.extend(values.values())
|
||||
forbidden.extend([actor["token"], actor["registration"]["password"], root_token()])
|
||||
for role in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
data = request("secret/data/messenger/" + role, token=root_token())["data"]["data"]
|
||||
for name, value in data.items():
|
||||
if "PASSWORD" in name or "SECRET_ACCESS_KEY" in name:
|
||||
forbidden.append(value)
|
||||
if name.endswith("_URL"):
|
||||
password = urllib.parse.urlsplit(value).password
|
||||
if password:
|
||||
forbidden.append(password)
|
||||
sources = {}
|
||||
sources["container-logs"] = subprocess.check_output(
|
||||
["docker", "compose", "logs", "--no-color"], cwd=ROOT, text=True, stderr=subprocess.DEVNULL
|
||||
)
|
||||
|
||||
def fetch(base, path):
|
||||
with urllib.request.urlopen(base + path, context=tls(), timeout=15) as response:
|
||||
return response.read().decode()
|
||||
|
||||
sources["metrics"] = fetch(
|
||||
"https://localhost:19090",
|
||||
"/api/v1/query?" + urllib.parse.urlencode({"query": "http_server_requests_total"}),
|
||||
)
|
||||
sources["logs"] = fetch(
|
||||
"https://localhost:13100",
|
||||
"/loki/api/v1/query_range?"
|
||||
+ urllib.parse.urlencode(
|
||||
{
|
||||
"query": '{service_name=~"messenger-.*"}',
|
||||
"limit": 200,
|
||||
"start": str(time.time_ns() - 120_000_000_000),
|
||||
}
|
||||
),
|
||||
)
|
||||
# Search includes real recent traces; specific trace may still be in the export buffer.
|
||||
sources["traces"] = fetch("https://localhost:13200", "/api/search?limit=20")
|
||||
for name, text in sources.items():
|
||||
assert not any(value and value in text for value in forbidden), "Secret found in " + name
|
||||
assert "-----BEGIN PRIVATE KEY-----" not in text
|
||||
ok("no-secrets:" + name)
|
||||
metrics = json.loads(sources["metrics"])["data"]["result"]
|
||||
assert metrics
|
||||
for series in metrics:
|
||||
assert not {
|
||||
"chat_id",
|
||||
"user_id",
|
||||
"message_id",
|
||||
"attachment_id",
|
||||
"request_id",
|
||||
"trace_id",
|
||||
}.intersection(series["metric"])
|
||||
ok("metric-labels-bounded")
|
||||
# Persist only safe counts and a synthetic trace id, not response bodies.
|
||||
assert json.loads(sources["logs"])["data"]["result"]
|
||||
assert json.loads(sources["traces"])["traces"]
|
||||
ok("live-telemetry-all-three-signals", sample_trace_id=traceid)
|
||||
admin = base64.b64encode(("admin:" + values["grafana"]).encode()).decode()
|
||||
for uid, path in [
|
||||
("prometheus", "/api/v1/query?query=up"),
|
||||
("loki", "/loki/api/v1/labels"),
|
||||
("tempo", "/api/search?limit=1"),
|
||||
]:
|
||||
req = urllib.request.Request(
|
||||
"https://localhost:13000/api/datasources/proxy/uid/" + uid + path,
|
||||
headers={"Authorization": "Basic " + admin},
|
||||
)
|
||||
with urllib.request.urlopen(req, context=tls(None), timeout=10) as response:
|
||||
data = json.load(response)
|
||||
assert response.status == 200
|
||||
ok("grafana-real-datasource-query:" + uid)
|
||||
|
||||
original = Path("/Users/andrejkamenskij/Downloads/mtusi2026lab7")
|
||||
if original.exists():
|
||||
count = 0
|
||||
for folder in ["tests", "contracts"]:
|
||||
for source in (original / folder).rglob("*"):
|
||||
if source.is_file() and "__pycache__" not in source.parts:
|
||||
relative = source.relative_to(original)
|
||||
# trust matrix is intentionally filled as required by assignment.
|
||||
if str(relative) == "contracts/trust-matrix.md":
|
||||
continue
|
||||
assert (ROOT / relative).read_bytes() == source.read_bytes(), str(relative)
|
||||
count += 1
|
||||
ok("public-tests-and-contracts-unchanged", files=count)
|
||||
(ROOT / "evidence/audit-summary.json").write_text(
|
||||
json.dumps({"checks": rows, "passed": len(rows)}, indent=2) + "\n"
|
||||
)
|
||||
print("PASS:", len(rows), "container/telemetry/public-file audit checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user