Skeleton contracts / contracts (pull_request) Blocked by required conditions
112 lines
5.2 KiB
Python
112 lines
5.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Inventory comparable pip-audit and Trivy reports without counting duplicate paths."""
|
|
import argparse
|
|
from collections import Counter, defaultdict
|
|
import json
|
|
from pathlib import Path
|
|
|
|
|
|
def surface(package):
|
|
if package in {"pillow", "starlette", "fastapi", "opentelemetry-api"}:
|
|
return {
|
|
"pillow": "JPEG/PNG exposed; other codecs restricted",
|
|
"starlette": "ASGI/HTTP used; check the affected API",
|
|
"fastapi": "ASGI/HTTP used; check the affected API",
|
|
"opentelemetry-api": "trace context consumed from broker",
|
|
}[package]
|
|
if package in {"openssl", "libssl3", "libssl3t64", "libcrypto3", "gnutls", "libgnutls30"}:
|
|
return "TLS library present; verify process, platform and affected feature"
|
|
if package == "stdlib" or "/" in package:
|
|
return "Embedded Go dependency; module presence alone does not show reachable code"
|
|
return "Image package present; process and affected feature not established"
|
|
|
|
|
|
def advisory_id(aliases):
|
|
return min(aliases, key=lambda value: (not value.startswith("CVE-"), not value.startswith("GHSA-"), value))
|
|
|
|
|
|
def load(directory):
|
|
audit = json.loads((directory / "python.json").read_text())
|
|
images = (directory / "images.txt").read_text().splitlines()
|
|
rows = []
|
|
aliases = {}
|
|
python_entries = 0
|
|
image_counts = Counter()
|
|
for dependency in audit["dependencies"]:
|
|
for item in dependency.get("vulns", []):
|
|
python_entries += 1
|
|
group = {item["id"], *item.get("aliases", [])}
|
|
for key in group.copy():
|
|
group.update(aliases.get(key, ()))
|
|
for key in group:
|
|
aliases[key] = group
|
|
rows.append(("Python runtime", dependency["name"], dependency["version"], item["id"],
|
|
"not supplied", ", ".join(item["fix_versions"]), "pip-audit"))
|
|
for image in images:
|
|
stem = image.translate(str.maketrans("/:@", "___"))
|
|
report = json.loads((directory / f"{stem}.json").read_text())
|
|
if not report.get("Metadata", {}).get("ImageID"):
|
|
raise ValueError(f"Incomplete Trivy report for {image}")
|
|
for result in report.get("Results", []):
|
|
for item in result.get("Vulnerabilities", []):
|
|
image_counts[item["Severity"]] += 1
|
|
rows.append((image, item["PkgName"], item["InstalledVersion"], item["VulnerabilityID"],
|
|
item["Severity"], item.get("FixedVersion", ""), result["Target"]))
|
|
grouped = defaultdict(set)
|
|
for image, package, version, identifier, severity, fix, target in rows:
|
|
group = aliases.get(identifier, {identifier})
|
|
normalized = advisory_id(group)
|
|
grouped[image, package, version, normalized, severity, fix].add(target)
|
|
return grouped, python_entries, image_counts, aliases
|
|
|
|
|
|
def family(image):
|
|
repository = image.split("@", 1)[0].rsplit(":", 1)[0]
|
|
if repository.startswith("mtusi2026lab7-"):
|
|
return "local-" + repository.rsplit("-", 1)[-1]
|
|
return repository
|
|
|
|
|
|
def print_table(rows):
|
|
print("| Image | Package | Installed | ID | Severity | Vendor fix | Targets | Applicability review |")
|
|
print("| --- | --- | --- | --- | --- | --- | --- | --- |")
|
|
for (image, package, version, identifier, severity, fix), targets in sorted(rows.items()):
|
|
fields = (image, package, version, identifier, severity, fix or "not reported",
|
|
", ".join(sorted(targets)), surface(package))
|
|
print("| " + " | ".join(value.replace("|", "\\|").replace("\n", " ") for value in fields) + " |")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("directory", type=Path)
|
|
parser.add_argument("--baseline", type=Path)
|
|
args = parser.parse_args()
|
|
grouped, python_entries, image_counts, aliases = load(args.directory)
|
|
identities = {row[3] for row in grouped if row[0] != "Python runtime"}
|
|
py_identities = {row[3] for row in grouped if row[0] == "Python runtime"}
|
|
print("# Inventory")
|
|
print()
|
|
print(f"Python input rows: {python_entries}, distinct advisory IDs after aliases: {len(py_identities)}.")
|
|
print(f"Image input rows: {sum(image_counts.values())} ({dict(sorted(image_counts.items()))}), "
|
|
f"distinct advisory IDs: {len(identities)}, CVE IDs: {sum(x.startswith('CVE-') for x in identities)}.")
|
|
if args.baseline:
|
|
old, _, _, old_aliases = load(args.baseline)
|
|
|
|
def coordinate(row):
|
|
image, package, _, identifier, _, _ = row
|
|
related = {identifier, *aliases.get(identifier, ()), *old_aliases.get(identifier, ())}
|
|
return family(image), package, advisory_id(related)
|
|
|
|
old_coordinates = {coordinate(row) for row in old}
|
|
new_coordinates = {coordinate(row) for row in grouped}
|
|
print("\n## Baseline findings absent from the new image or runtime\n")
|
|
print_table({row: targets for row, targets in old.items() if coordinate(row) not in new_coordinates})
|
|
print("\n## Newly reported placements\n")
|
|
print_table({row: targets for row, targets in grouped.items() if coordinate(row) not in old_coordinates})
|
|
print("\n## Grouped findings\n")
|
|
print_table(grouped)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|