Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions .github/custom_tools/trivy/compare_summaries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Copyright (C) 2024-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

import argparse
import csv
import os


KEY_FIELDS = ("image", "cve", "name")
IMPORTANT_SEVERITIES = {"HIGH", "CRITICAL"}
PYTHON_VULN_CLASS = "lang-pkgs"
PYTHON_VULN_TYPE = "python-pkg"


def load_rows(csv_path: str):
rows = []
with open(csv_path, newline="") as fh:
reader = csv.DictReader(fh)
for row in reader:
rows.append(row)
return rows


def build_keyed_rows(rows):
keyed = {}
for row in rows:
key = tuple(row.get(field, "") for field in KEY_FIELDS)
keyed[key] = row
return keyed






def fmt_row(row: dict) -> str:
return (
f"| {row.get('image', '')} | {row.get('severity', '')} | "
f"{row.get('cve', '')} | {row.get('name', '')} | "
f"{row.get('version', '')} |"
)


def build_markdown(mitigated_rows, baseline_count, current_count):
mitigated_count = len(mitigated_rows)
lines = [
"## Trivy CVE delta",
"",
f"- Baseline (`latest`) findings: **{baseline_count}**",
f"- Current PR findings: **{current_count}**",
f"- Mitigated HIGH/CRITICAL Python-library findings: **{mitigated_count}**",
"",
]

if mitigated_count == 0:
lines.append("No mitigated HIGH/CRITICAL CVEs were detected for Python libraries.")
lines.append("")
return "\n".join(lines)

lines.extend([
"### Mitigated HIGH/CRITICAL Python-library findings",
"",
"| Image | Severity | CVE | Package | Old version |",
"| --- | --- | --- | --- | --- |",
])

for row in mitigated_rows:
lines.append(fmt_row(row))

lines.append("")
return "\n".join(lines)


def write_github_outputs(baseline_count, current_count, mitigated_count):
github_output = os.getenv("GITHUB_OUTPUT")
if not github_output:
return

with open(github_output, "a", encoding="utf-8") as fh:
fh.write(f"baseline_count={baseline_count}\n")
fh.write(f"current_count={current_count}\n")
fh.write(f"mitigated_count={mitigated_count}\n")


def is_python_library_vuln(row: dict) -> bool:
vuln_class = (row.get("vuln_class") or "").strip().lower()
vuln_type = (row.get("vuln_type") or "").strip().lower()
return vuln_class == PYTHON_VULN_CLASS and vuln_type == PYTHON_VULN_TYPE


def main():
parser = argparse.ArgumentParser(description="Compare Trivy summary CSV files")
parser.add_argument("baseline_csv", help="Baseline summary CSV (e.g. latest images)")
parser.add_argument("current_csv", help="Current summary CSV (e.g. PR images)")
parser.add_argument("output_markdown", help="Output markdown report")
args = parser.parse_args()

baseline_rows = load_rows(args.baseline_csv)
current_rows = load_rows(args.current_csv)

baseline_keyed = build_keyed_rows(baseline_rows)
current_keyed = build_keyed_rows(current_rows)

mitigated_keys = sorted(set(baseline_keyed) - set(current_keyed))
mitigated_rows = [baseline_keyed[key] for key in mitigated_keys]
mitigated_rows = [
row for row in mitigated_rows
if (row.get("severity") or "").upper() in IMPORTANT_SEVERITIES and is_python_library_vuln(row)
]

markdown = build_markdown(
mitigated_rows=mitigated_rows,
baseline_count=len(baseline_rows),
current_count=len(current_rows),
)

with open(args.output_markdown, "w", encoding="utf-8") as fh:
fh.write(markdown)

write_github_outputs(
baseline_count=len(baseline_rows),
current_count=len(current_rows),
mitigated_count=len(mitigated_rows),
)


if __name__ == "__main__":
main()

89 changes: 89 additions & 0 deletions .github/custom_tools/trivy/data_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Copyright (C) 2024-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

import os
from datetime import datetime, timezone
from enum import IntEnum


def errors_path(postprocessed_path: str) -> str:
"""Sidecar file next to the postprocessed results, holding the
vulnerabilities that could not be processed. Written by
json_postprocess.py, reported on by the summary builder."""
base, ext = os.path.splitext(postprocessed_path)
return f"{base}-errors{ext or '.json'}"


class Severity(IntEnum):
CRITICAL = 4
HIGH = 3
MEDIUM = 2
LOW = 1
UNKNOWN = 0


class AffectedDependency:
"""To avoid duplicates of vulnerabilities coming from different
places of same package, __hash__ and __eq__ are implemented,
so that objects are suitable to use in sets."""

def __init__(
self,
vuln_class: str,
vuln_type: str,
name: str,
version: str,
severity: Severity,
published_date: str,
fix: str,
cve: str,
cve_url: str,
title: str
):
self.vuln_class = vuln_class
self.vuln_type = vuln_type
self.name = name
self.version = version
if isinstance(severity, int):
severity = Severity(severity)
self.severity = severity
self.published_date = published_date
self.fix = fix
self.cve = cve
self.cve_url = cve_url
self.title = title

def __eq__(self, other):
if not isinstance(other, AffectedDependency):
return False
return self.name == other.name and self.cve == other.cve

def __hash__(self):
return hash((self.name, self.cve))

@property
def age(self) -> int:
if self.published_date is None:
return 0
# Handle case with and without microseconds
try:
published = datetime.strptime(self.published_date, "%Y-%m-%dT%H:%M:%S.%fZ")
except ValueError:
published = datetime.strptime(self.published_date, "%Y-%m-%dT%H:%M:%SZ")
now = datetime.now(timezone.utc)
age_days = (now - published.replace(tzinfo=timezone.utc)).days
return age_days

def to_dict(self):
return {
"vuln_class": self.vuln_class,
"vuln_type": self.vuln_type,
"name": self.name,
"version": self.version,
"severity": self.severity,
"published_date": self.published_date,
"fix": self.fix,
"cve": self.cve,
"cve_url": self.cve_url,
"title": self.title
}
79 changes: 79 additions & 0 deletions .github/custom_tools/trivy/json_postprocess.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Copyright (C) 2024-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""
This script processes Trivy JSON to form that will be used
for per-image results and summary.
"""

import json
import argparse

from data_models import AffectedDependency, Severity, errors_path

parser = argparse.ArgumentParser(description="Process Trivy JSON results.")
parser.add_argument("input_file", help="Input Trivy JSON filename")
parser.add_argument("output_file", help="Output processed JSON filename")
args = parser.parse_args()

with open(args.input_file, 'r') as f:
data = json.load(f)


def vuln_url(vuln: dict) -> str:
"""Trivy omits PrimaryURL for advisories without an NVD entry,
e.g. Go-only ones like GO-2026-5932. Fall back to a reference
pointing at the advisory itself, then to its data source."""
if vuln.get("PrimaryURL"):
return vuln["PrimaryURL"]
for ref in vuln.get("References", []):
if vuln["VulnerabilityID"] in ref:
return ref
return vuln.get("DataSource", {}).get("URL", "")


deps = []
errors = []

for r in data["Results"]:
if "Vulnerabilities" not in r:
continue

for vuln in r["Vulnerabilities"]:
try:
fix = None
if vuln["Status"] == "fixed":
fix = vuln["FixedVersion"]
dep = AffectedDependency(
r["Class"],
r["Type"],
vuln["PkgName"],
vuln["InstalledVersion"],
Severity[vuln["Severity"]],
vuln.get("PublishedDate"),
fix,
vuln["VulnerabilityID"],
vuln_url(vuln),
vuln.get("Title", f"Title not found. Description: {vuln.get('Description', 'Also not found.')}")
)
deps.append(dep)
except KeyError as e:
print(
f"ERROR: missing key {e} in vulnerability "
f"{json.dumps(vuln, indent=4)}",
)
errors.append({"missing_key": e.args[0], "vulnerability": vuln})

# Remove duplicates
deps = set(deps)
deps = list(deps)
deps_dicted = [d.to_dict() for d in deps]

with open(args.output_file, 'w') as f:
f.write(json.dumps(deps_dicted, indent=4))

# The summary builder picks this up to report that some vulnerabilities
# are missing from its tables.
if errors:
with open(errors_path(args.output_file), 'w') as f:
f.write(json.dumps(errors, indent=4))
14 changes: 14 additions & 0 deletions .github/custom_tools/trivy/sdl-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
timeout: 40m
exit-code: 2
list-all-pkgs: true
format: template
template: '@.github/custom_tools/trivy/sdl-template.tpl'
output: sdl-scan-results.csv
scan:
scanners:
- vuln
severity:
- HIGH
- CRITICAL
skip-dirs:
- /compliance/
29 changes: 29 additions & 0 deletions .github/custom_tools/trivy/sdl-template.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{{ range . }}
Trivy Vulnerability Scan Results ({{- .Target -}})
VulnerabilityID,Severity,CVSS Score,Title,Library,Vulnerable Version,Fixed Version,Information URL,Triage Information
{{ range .Vulnerabilities }}
{{- .VulnerabilityID }},
{{- .Severity }},
{{- range $key, $value := .CVSS }}
{{- if (eq $key "nvd") }}
{{- .V3Score -}}
{{- end }}
{{- end }},
{{- quote .Title }},
{{- quote .PkgName }},
{{- quote .InstalledVersion }},
{{- quote .FixedVersion }},
{{- .PrimaryURL }}
{{ else -}}
No vulnerabilities found at this time.
{{ end }}
Trivy Dependency Scan Results ({{ .Target }})
ID,Name,Version,Notes
{{ range .Packages -}}
{{- quote .ID }},
{{- quote .Name }},
{{- quote .Version }}
{{ else -}}
No dependencies found at this time.
{{ end }}
{{ end }}
Loading
Loading