"""Сохранить отчёты Trivy по Go-зависимостям и образам фактического стенда.""" import argparse import csv import datetime as dt import json import os from pathlib import Path import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parents[1] def output(*args): return subprocess.check_output(args, cwd="/tmp", text=True).strip() def scan(destination, target, *options): scratch = destination.with_suffix(".partial") subprocess.run(["trivy", target, "--scanners", "vuln", "--format", "json", "--list-all-pkgs", "--output", str(scratch), *options], cwd="/tmp", check=True) data = json.loads(scratch.read_text()) scratch.replace(destination) return data def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--out", type=Path, default=ROOT / "evidence") args = parser.parse_args() for exe in ("docker", "trivy"): if not shutil.which(exe): parser.error(f"Установите {exe} в WSL.") os.environ.setdefault("COMPOSE_FILE", str(ROOT / "compose.yaml")) ids = output("docker", "compose", "ps", "-aq").split() if not ids: parser.error("Сначала запустите стенд.") containers = output("docker", "inspect", "--format", '{{json .Image}} {{json (index .Config.Labels "com.docker.compose.service")}}', *ids) images = {} decoder = json.JSONDecoder() for line in containers.splitlines(): image, end = decoder.raw_decode(line) role = json.loads(line[end:].strip()) images.setdefault(image, set()).add(role) args.out.mkdir(parents=True, exist_ok=True) out = Path(tempfile.mkdtemp(prefix="scan-", dir=args.out.resolve())) print(f"Доказательства: {out}", flush=True) stamp = dt.datetime.now(dt.timezone.utc).isoformat() (out / "versions.txt").write_text(f"{stamp}\n{output('trivy', '--version')}\n") reports = {"Go-зависимости": scan(out / "go.json", "fs", "--pkg-types", "library", str(ROOT / "backend"))} if not any(r.get("Type") == "gomod" for r in reports["Go-зависимости"].get("Results", [])): raise SystemExit("Trivy не обнаружил Go-модули в backend. Проверьте go.mod и версию сканера.") for idx, (image, roles) in enumerate(sorted(images.items()), 1): name = f"image-{idx:02d}" services = ", ".join(sorted(roles)) print(f"{name}: {services} — {image}", flush=True) reports[f"{name}: {services}"] = scan(out / (name + ".json"), "image", "--image-src", "docker", image) (out / "versions.txt").write_text(f"{stamp}\n{output('trivy', '--version')}\n") (out / "images.json").write_text(json.dumps({key: sorted(value) for key, value in images.items()}, indent=2)) with (out / "findings.csv").open("w", newline="", encoding="utf-8-sig") as file: rows = csv.writer(file) rows.writerow(["Область", "Компонент", "ID", "Пакет", "Версия", "Исправлено в", "Уровень"]) for title, report in reports.items(): total = 0 severe = 0 for result in report.get("Results", []): for vuln in result.get("Vulnerabilities") or (): rows.writerow([title, result.get("Target"), vuln["VulnerabilityID"], vuln["PkgName"], vuln["InstalledVersion"], vuln.get("FixedVersion"), vuln["Severity"]]) total += 1 severe += vuln["Severity"] in {"CRITICAL", "HIGH"} print(f"{title}: записей {total}, из них HIGH/CRITICAL {severe}") print(f"Сканирование завершено: {out}") if __name__ == "__main__": main()