forked from mtusi2026/mtusi2026lab7
70 lines
2.9 KiB
Python
70 lines
2.9 KiB
Python
"""Сканирует lock-файл и локальные образы, не передавая сокет Docker сканеру."""
|
|
|
|
from datetime import UTC, datetime
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
from tempfile import TemporaryDirectory
|
|
|
|
from scripts.deployment import ROOT, ComposeProject
|
|
|
|
SCANNER = "ghcr.io/aquasecurity/trivy:0.76.2"
|
|
|
|
|
|
def scan() -> dict:
|
|
project = ComposeProject()
|
|
images = sorted({service["image"] for service in project.config["services"].values()
|
|
if "build" in service})
|
|
with TemporaryDirectory(prefix="lab7-scan-") as directory:
|
|
workspace = Path(directory)
|
|
packages = workspace / "packages"
|
|
packages.mkdir()
|
|
shutil.copyfile(ROOT / "requirements.txt", packages / "requirements.txt")
|
|
cache = workspace / "cache"
|
|
cache.mkdir()
|
|
|
|
def trivy(mount, args):
|
|
result = subprocess.run(
|
|
["docker", "run", "--rm", "--cap-drop=ALL",
|
|
"--user", f"{os.getuid()}:{os.getgid()}",
|
|
"--security-opt=no-new-privileges", "-v", f"{cache}:/cache",
|
|
"-v", mount, SCANNER, *args, "--cache-dir", "/cache",
|
|
"--quiet", "--scanners", "vuln", "--severity", "HIGH,CRITICAL",
|
|
"--format", "json", "--timeout", "6m"],
|
|
cwd=ROOT, check=True, stdout=subprocess.PIPE,
|
|
)
|
|
report = json.loads(result.stdout)
|
|
return {
|
|
"targets": [item["Target"] for item in report.get("Results", [])],
|
|
"findings": [
|
|
{name: issue.get(name) for name in (
|
|
"VulnerabilityID", "PkgName", "InstalledVersion", "FixedVersion",
|
|
"Severity", "PrimaryURL", "Status",
|
|
)}
|
|
for item in report.get("Results", [])
|
|
for issue in item.get("Vulnerabilities", [])
|
|
],
|
|
}
|
|
|
|
result = {"scanner": SCANNER, "date_utc": datetime.now(UTC).isoformat(), "dependency": trivy(
|
|
f"{packages}:/scan:ro", ["fs", "/scan"],
|
|
), "images": {}}
|
|
archive = workspace / "image.tar"
|
|
for name in images:
|
|
subprocess.run(["docker", "image", "save", "-o", archive, name],
|
|
cwd=ROOT, check=True)
|
|
findings = trivy(f"{archive}:/image.tar:ro", ["image", "--input", "/image.tar"])
|
|
result["images"][name] = {
|
|
"image_id": project.docker("image", "inspect", "--format", "{{.Id}}", name),
|
|
**findings,
|
|
}
|
|
return result
|
|
|
|
|
|
if __name__ == "__main__":
|
|
destination = ROOT / "evidence/security-scan.json"
|
|
destination.write_text(json.dumps(scan(), ensure_ascii=False, indent=2) + "\n")
|
|
print("Результаты Trivy сохранены в evidence/security-scan.json")
|