forked from mtusi2026/mtusi2026lab7
test(security): retain reproducible lifecycle and image scan evidence
This commit is contained in:
@@ -0,0 +1,240 @@
|
||||
"""Summarize only completed PKI observations and their actual time intervals."""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import statistics
|
||||
from collections import Counter
|
||||
from itertools import pairwise
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def quantile(values, fraction):
|
||||
ordered = sorted(values)
|
||||
return (
|
||||
ordered[max(0, math.ceil(len(ordered) * fraction) - 1)]
|
||||
if ordered
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("input", type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
report = json.loads(args.input.read_text())
|
||||
assert report["complete"], (
|
||||
"An incomplete experiment cannot yield a final analysis"
|
||||
)
|
||||
with args.input.with_name(
|
||||
args.input.stem + "-requests.csv"
|
||||
).open() as stream:
|
||||
rows = list(csv.DictReader(stream))
|
||||
for row in rows:
|
||||
row["started_at"] = float(row["started_at"])
|
||||
row["duration_seconds"] = float(row["duration_seconds"])
|
||||
row["status"] = int(row["status"])
|
||||
phases = []
|
||||
for phase in report["phases"]:
|
||||
observed = [
|
||||
r
|
||||
for r in rows
|
||||
if phase["started_at"] <= r["started_at"] < phase["ended_at"]
|
||||
]
|
||||
successful = [
|
||||
r["duration_seconds"] for r in observed if r["status"] == 201
|
||||
]
|
||||
duration = phase["ended_at"] - phase["started_at"]
|
||||
phases.append(
|
||||
{
|
||||
"phase": phase["name"],
|
||||
"seconds": round(duration, 3),
|
||||
"scheduled_messages": len(observed),
|
||||
"statuses": dict(Counter(str(r["status"]) for r in observed)),
|
||||
"successful_rps": round(len(successful) / duration, 4),
|
||||
"http_errors": sum(
|
||||
r["status"] not in {201, 0, -1} for r in observed
|
||||
),
|
||||
"transport_errors": sum(r["status"] == 0 for r in observed),
|
||||
"client_backpressure_drops": sum(
|
||||
r["status"] == -1 for r in observed
|
||||
),
|
||||
"attempted_request_error_fraction": (
|
||||
sum(r["status"] not in {201, -1} for r in observed)
|
||||
/ sum(r["status"] != -1 for r in observed)
|
||||
)
|
||||
if any(r["status"] != -1 for r in observed)
|
||||
else None,
|
||||
**{
|
||||
f"success_p{int(q * 100)}_seconds": quantile(successful, q)
|
||||
for q in [0.5, 0.95, 0.99]
|
||||
},
|
||||
}
|
||||
)
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
summary = {
|
||||
"source_commit": report["source_commit"],
|
||||
"complete": True,
|
||||
"phase_assignment": "actual request start within measured phase wall-clock bounds",
|
||||
"preservation": report["preservation"],
|
||||
"phases": phases,
|
||||
"all_statuses": dict(Counter(str(r["status"]) for r in rows)),
|
||||
}
|
||||
resources = {}
|
||||
for sample in report.get("resource_samples", []):
|
||||
for observation in sample["containers"]:
|
||||
name = observation["Name"]
|
||||
result = resources.setdefault(
|
||||
name,
|
||||
{
|
||||
"observations": 0,
|
||||
"maximum_observed_cpu_cores": 0,
|
||||
"maximum_observed_memory_mib": 0,
|
||||
},
|
||||
)
|
||||
result["observations"] += 1
|
||||
result["maximum_observed_cpu_cores"] = max(
|
||||
result["maximum_observed_cpu_cores"],
|
||||
float(observation["CPUPerc"].rstrip("%")) / 100,
|
||||
)
|
||||
value, unit = re.fullmatch(
|
||||
r"([\d.]+)([KMGT]?i?B)",
|
||||
observation["MemUsage"].split("/")[0].strip(),
|
||||
).groups()
|
||||
factor = {
|
||||
"B": 1,
|
||||
"KiB": 1024,
|
||||
"MiB": 1024**2,
|
||||
"GiB": 1024**3,
|
||||
"TiB": 1024**4,
|
||||
"kB": 1000,
|
||||
"MB": 1000**2,
|
||||
"GB": 1000**3,
|
||||
}[unit]
|
||||
result["maximum_observed_memory_mib"] = max(
|
||||
result["maximum_observed_memory_mib"],
|
||||
float(value) * factor / 1024**2,
|
||||
)
|
||||
samples = report.get("resource_samples", [])
|
||||
intervals = [
|
||||
b["started_at"] - a["started_at"] for a, b in pairwise(samples)
|
||||
]
|
||||
summary["sampling_intervals_seconds"] = (
|
||||
{
|
||||
"min": min(intervals),
|
||||
"median": statistics.median(intervals),
|
||||
"max": max(intervals),
|
||||
}
|
||||
if intervals
|
||||
else None
|
||||
)
|
||||
summary["resources"] = {
|
||||
"measurement": report.get("resource_measurement"),
|
||||
"limits": report.get("resource_limits"),
|
||||
"sampled_maxima_not_absolute_peaks": resources,
|
||||
"sampling_errors": report.get("resource_sampling_errors", []),
|
||||
}
|
||||
(args.output / "summary.json").write_text(
|
||||
json.dumps(summary, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
with (args.output / "phases.csv").open("w") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(phases[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(
|
||||
{**p, "statuses": json.dumps(p["statuses"])} for p in phases
|
||||
)
|
||||
origin = report["phases"][0]["started_at"]
|
||||
finish = max(r["started_at"] + r["duration_seconds"] for r in rows)
|
||||
count = math.ceil((finish - origin) / 10)
|
||||
windows = [
|
||||
[
|
||||
r
|
||||
for r in rows
|
||||
if origin + i * 10 <= r["started_at"] < origin + (i + 1) * 10
|
||||
]
|
||||
for i in range(count)
|
||||
]
|
||||
fig, axes = plt.subplots(
|
||||
2, 1, figsize=(12, 7), sharex=True, constrained_layout=True
|
||||
)
|
||||
positions = [i * 10 + 5 for i in range(count)]
|
||||
bottom = [0] * count
|
||||
for label, color, predicate in [
|
||||
("201: подтверждено", "#238b45", lambda s: s == 201),
|
||||
("Ошибки HTTP", "#d95f0e", lambda s: s not in {201, 0, -1}),
|
||||
("Ошибка TLS / сети", "#756bb1", lambda s: s == 0),
|
||||
("Генератор занят", "#969696", lambda s: s == -1),
|
||||
]:
|
||||
values = [
|
||||
sum(predicate(r["status"]) for r in window) for window in windows
|
||||
]
|
||||
axes[0].bar(
|
||||
positions,
|
||||
values,
|
||||
width=9.5,
|
||||
bottom=bottom,
|
||||
label=label,
|
||||
color=color,
|
||||
)
|
||||
bottom = [a + b for a, b in zip(bottom, values, strict=True)]
|
||||
for q, label in [(0.5, "p50"), (0.95, "p95")]:
|
||||
values = [
|
||||
quantile(
|
||||
[r["duration_seconds"] for r in window if r["status"] == 201],
|
||||
q,
|
||||
)
|
||||
for window in windows
|
||||
]
|
||||
axes[1].plot(
|
||||
positions,
|
||||
[v if v is not None else math.nan for v in values],
|
||||
label=label,
|
||||
)
|
||||
labels = ["1", "2", "3", "4", "5", "6", "7"]
|
||||
for i, phase in enumerate(report["phases"]):
|
||||
left, right = phase["started_at"] - origin, phase["ended_at"] - origin
|
||||
for axis in axes:
|
||||
axis.axvspan(
|
||||
left,
|
||||
right,
|
||||
color="#d9e5ef",
|
||||
alpha=0.22 if i % 2 == 0 else 0.04,
|
||||
)
|
||||
axis.axvline(left, color="#51616c", lw=0.6)
|
||||
axes[0].text(
|
||||
(left + right) / 2,
|
||||
1.02,
|
||||
labels[i],
|
||||
transform=axes[0].get_xaxis_transform(),
|
||||
ha="center",
|
||||
fontsize=8,
|
||||
)
|
||||
axes[0].set_ylabel("Запросы сообщений за 10 с")
|
||||
axes[1].set_ylabel("Задержка успешного запроса, с")
|
||||
axes[1].set_xlabel("Секунды от начала первого этапа")
|
||||
for axis in axes:
|
||||
axis.legend(loc="upper left", fontsize=8)
|
||||
axis.grid(axis="y", alpha=0.2)
|
||||
fig.suptitle("Жизненный цикл сертификатов под нагрузкой HTTPS", y=1.04)
|
||||
fig.text(
|
||||
0.5,
|
||||
-0.04,
|
||||
"1 — Обновление; 2 — Смена рабочего ключа; 3 — Отзыв; 4 — Истечение;\n5 — Блокировка OpenBao; 6 — Замена CA; 7 — После восстановления",
|
||||
ha="center",
|
||||
fontsize=9,
|
||||
)
|
||||
fig.savefig(args.output / "pki-results.png", dpi=170, bbox_inches="tight")
|
||||
plt.close(fig)
|
||||
print("PASS: observed phase summaries and PKI figure")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Scan actual verified application/S3 images using an isolated pinned scanner."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from collections import Counter
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCANNER = "aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb"
|
||||
|
||||
|
||||
def isolated(cache, workspace, *, offline=False):
|
||||
args = [
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--user",
|
||||
f"{os.getuid()}:{os.getgid()}",
|
||||
"--cpus",
|
||||
"0.5",
|
||||
"--memory",
|
||||
"768m",
|
||||
"--read-only",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--security-opt",
|
||||
"no-new-privileges:true",
|
||||
"-v",
|
||||
f"{cache}:/cache",
|
||||
"-v",
|
||||
f"{workspace / 'tmp'}:/tmp",
|
||||
"-v",
|
||||
f"{workspace / 'input'}:/scan:ro",
|
||||
"-v",
|
||||
f"{workspace / 'reports'}:/output",
|
||||
"-e",
|
||||
"TRIVY_CACHE_DIR=/cache",
|
||||
"-e",
|
||||
"GOMEMLIMIT=384MiB",
|
||||
]
|
||||
if offline:
|
||||
args += ["--network", "none"]
|
||||
return args + [SCANNER]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--verification", default="evidence/clean-clone-review.json"
|
||||
)
|
||||
parser.add_argument("--output", default="evidence/image-scan-review.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
assert not output.exists(), "Choose a new receipt path"
|
||||
proof = json.loads((ROOT / args.verification).read_text())
|
||||
assert proof["result"] == "PASS" and proof["checks_completed"]
|
||||
research = proof["security_research"]
|
||||
assert research["complete"]
|
||||
selected = []
|
||||
for label, role in [("application", "worker"), ("object-store", "s3")]:
|
||||
# identity-s3 has the application image; it is not the S3 server.
|
||||
pattern = r"/mtusi-lab7-clean-[0-9a-f]{10}-" + role + r"-\d+"
|
||||
matches = {
|
||||
image
|
||||
for name, image in research["images_before"].items()
|
||||
if re.fullmatch(pattern, name)
|
||||
}
|
||||
assert len(matches) == 1, "Missing or ambiguous verified service image"
|
||||
selected.append((label, matches.pop()))
|
||||
assert len({image for _, image in selected}) == 2
|
||||
assert shutil.disk_usage(ROOT).free >= 3 * 1024**3, (
|
||||
"Scanning needs 3 GiB free for the vulnerability database and image archive"
|
||||
)
|
||||
cache = ROOT / ".work-trivy-cache"
|
||||
workspace = ROOT / ".work-image-scans" / output.stem
|
||||
for directory in [
|
||||
cache,
|
||||
workspace / "tmp",
|
||||
workspace / "input",
|
||||
workspace / "reports",
|
||||
]:
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
receipt = {
|
||||
"date": datetime.now(UTC).isoformat(),
|
||||
"scanner": SCANNER,
|
||||
"verified_runtime_source": proof["source_commit"],
|
||||
"scope": "actual local application and object-store images; other images not covered",
|
||||
"isolation": "no Docker socket or credentials; read-only root; scan network disabled",
|
||||
"complete": False,
|
||||
"images": [],
|
||||
}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
subprocess.run(
|
||||
isolated(cache, workspace)
|
||||
+ ["image", "--download-db-only", "--timeout", "10m"],
|
||||
check=True,
|
||||
)
|
||||
receipt["database"] = json.loads(
|
||||
(cache / "db/metadata.json").read_text()
|
||||
)
|
||||
for label, image in selected:
|
||||
metadata = json.loads(
|
||||
subprocess.check_output(
|
||||
["docker", "image", "inspect", image],
|
||||
text=True,
|
||||
)
|
||||
)[0]
|
||||
revision = (metadata["Config"].get("Labels") or {}).get(
|
||||
"org.opencontainers.image.revision"
|
||||
)
|
||||
if label == "application":
|
||||
assert revision == proof["source_commit"]
|
||||
archive = workspace / "input/image.tar"
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"image",
|
||||
"save",
|
||||
"--output",
|
||||
str(archive),
|
||||
image,
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
name = label + ".json"
|
||||
subprocess.run(
|
||||
isolated(cache, workspace, offline=True)
|
||||
+ [
|
||||
"image",
|
||||
"--skip-db-update",
|
||||
"--scanners",
|
||||
"vuln",
|
||||
"--input",
|
||||
"/scan/image.tar",
|
||||
"--format",
|
||||
"json",
|
||||
"--output",
|
||||
"/output/" + name,
|
||||
"--timeout",
|
||||
"10m",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
raw = (workspace / "reports" / name).read_bytes()
|
||||
vulnerabilities = []
|
||||
for target in json.loads(raw).get("Results", []):
|
||||
for value in target.get("Vulnerabilities", []):
|
||||
vulnerabilities.append(
|
||||
{
|
||||
"target": target["Target"],
|
||||
"type": target.get("Type"),
|
||||
"id": value["VulnerabilityID"],
|
||||
"package": value["PkgName"],
|
||||
"installed": value["InstalledVersion"],
|
||||
"fixed": value.get("FixedVersion"),
|
||||
"severity": value["Severity"],
|
||||
"status": value.get("Status"),
|
||||
"url": value.get("PrimaryURL"),
|
||||
}
|
||||
)
|
||||
counts = dict(
|
||||
Counter(value["severity"] for value in vulnerabilities)
|
||||
)
|
||||
receipt["images"].append(
|
||||
{
|
||||
"name": label,
|
||||
"image": image,
|
||||
"id": metadata["Id"],
|
||||
"revision": revision,
|
||||
"architecture": metadata["Architecture"],
|
||||
"report_sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"counts": counts,
|
||||
"vulnerabilities": vulnerabilities,
|
||||
}
|
||||
)
|
||||
print("SCANNED", label, counts, flush=True)
|
||||
finally:
|
||||
archive.unlink(missing_ok=True)
|
||||
receipt["complete"] = True
|
||||
except BaseException as error:
|
||||
receipt["failure_type"] = type(error).__name__
|
||||
raise
|
||||
finally:
|
||||
output.write_text(
|
||||
json.dumps(receipt, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user