Add vuln-scan: Dependency-Check 13.0.0 vs Trivy 0.76.2 vs OSV-Scanner 2.7.1
Same Maven project scanned three ways (pom.xml, SBOM, jars): captured output, false-positive evidence, suppression files with expiry, CI gate, -Pfixed profile. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b7h4ZNF4BDUpJk3Zou
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
f32c088174
commit
7c677a39d2
@@ -0,0 +1,7 @@
|
||||
# Only needed when HTTPS is intercepted by a proxy with its own CA (as in the sandbox used for the post).
|
||||
# Copy that CA bundle next to this file as ca.crt, then:
|
||||
# docker build -f scripts/Dockerfile.trivy -t trivy-local:0.76.2 scripts/
|
||||
# On a normal network use ghcr.io/aquasecurity/trivy:0.76.2 directly (TRIVY_IMAGE in env.sh).
|
||||
FROM ghcr.io/aquasecurity/trivy:0.76.2
|
||||
COPY ca.crt /tmp/ca.crt
|
||||
RUN cat /tmp/ca.crt >> /etc/ssl/certs/ca-certificates.crt
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compares the findings of the three tools using normalise.py.
|
||||
|
||||
compare.py osv.json trivy.json dc.json
|
||||
|
||||
Prints (1) findings per component per tool, (2) which advisory ids only one or two tools report,
|
||||
(3) advisories all three report but with different severity buckets.
|
||||
Severity buckets use the CVSS v3 ranges: >=9.0 CRITICAL, >=7.0 HIGH, >=4.0 MEDIUM, else LOW.
|
||||
"""
|
||||
import collections, subprocess, sys, os
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
def load(tool, path):
|
||||
out = subprocess.run([sys.executable, os.path.join(HERE, "normalise.py"), tool, path],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
return [l.split("\t") for l in out.splitlines()]
|
||||
|
||||
def bucket(sev):
|
||||
if ":" in sev: # dependency-check: "LABEL:score" -> trust the tool's own label
|
||||
return sev.split(":")[0].upper()
|
||||
s = sev
|
||||
try:
|
||||
x = float(s)
|
||||
return "CRITICAL" if x >= 9 else "HIGH" if x >= 7 else "MEDIUM" if x >= 4 else "LOW"
|
||||
except ValueError:
|
||||
return sev.split(":")[0].upper() or "NONE"
|
||||
|
||||
def main():
|
||||
osv, trivy, dc = (load(t, p) for t, p in zip(("osv", "trivy", "dc"), sys.argv[1:4]))
|
||||
names = ("osv-scanner", "trivy", "dependency-check")
|
||||
data = dict(zip(names, (osv, trivy, dc)))
|
||||
|
||||
comps = sorted({r[1] for rows in data.values() for r in rows})
|
||||
print("findings per component (advisory ids, deduplicated)")
|
||||
print(f' {"component":55} ' + " ".join(f"{n:>17}" for n in names))
|
||||
for c in comps:
|
||||
cells = [len({r[2] for r in rows if r[1] == c}) for rows in data.values()]
|
||||
print(f" {c:55} " + " ".join(f"{x:>17}" for x in cells))
|
||||
print(f' {"TOTAL (component, id) pairs":55} ' + " ".join(f"{len({(r[1], r[2]) for r in rows}):>17}" for rows in data.values()))
|
||||
|
||||
pairs = {n: {(r[1], r[2]) for r in rows} for n, rows in data.items()}
|
||||
allp = set().union(*pairs.values())
|
||||
print("\nreported by every tool:", len(set.intersection(*pairs.values())))
|
||||
print("\nreported by only some tools (O = osv-scanner, T = trivy, D = dependency-check)")
|
||||
for p in sorted(allp - set.intersection(*pairs.values())):
|
||||
who = "".join(l if p in pairs[n] else "-" for l, n in zip("OTD", names))
|
||||
print(f" {who} {p[1]:16} {p[0]}")
|
||||
|
||||
print("\nsame advisory, different severity bucket")
|
||||
sev = {n: {(r[1], r[2]): bucket(r[3]) for r in rows} for n, rows in data.items()}
|
||||
shown = 0
|
||||
for p in sorted(set.intersection(*pairs.values())):
|
||||
b = [sev[n][p] for n in names]
|
||||
if len(set(b)) > 1:
|
||||
shown += 1
|
||||
print(f" {p[1]:16} {p[0].split(':')[1]:18} osv={b[0]:9} trivy={b[1]:9} dc={b[2]}")
|
||||
if not shown:
|
||||
print(" none")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
# Tool locations used by run-all.sh. Override with environment variables.
|
||||
MODULE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
OUT="$MODULE/output"
|
||||
export JAVA_HOME="${JAVA_HOME:-/tmp/tools/jdk-25.0.5.1+2}"
|
||||
export PATH="$JAVA_HOME/bin:$PATH"
|
||||
OSV="${OSV:-/tmp/gopath/bin/osv-scanner}"
|
||||
TRIVY_IMAGE="${TRIVY_IMAGE:-trivy-local:0.76.2}"
|
||||
DC_VERSION="${DC_VERSION:-13.0.0}" # org.owasp:dependency-check-maven
|
||||
DC_DATA="${DC_DATA:-/tmp/dcdata}" # persisted Dependency-Check H2 database
|
||||
TRIVY_CACHE="${TRIVY_CACHE:-/tmp/trivy-cache}"
|
||||
# Strip sandbox noise from anything that is committed.
|
||||
clean() { grep -v -E '^Picked up|^WARNING: |sun.misc.Unsafe' | sed -e "s#$MODULE#<module>#g" -e "s#$HOME#~#g"; }
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A severity gate for osv-scanner, which has no built-in threshold flag.
|
||||
|
||||
gate.py osv.json <minimum-cvss> exits 1 when any finding has a CVSS score >= the minimum
|
||||
"""
|
||||
import os, subprocess, sys
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
out = subprocess.run([sys.executable, os.path.join(HERE, "normalise.py"), "osv", sys.argv[1]],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
limit = float(sys.argv[2])
|
||||
bad = []
|
||||
for line in out.splitlines():
|
||||
_, comp, vid, score = line.split("\t")
|
||||
if score and float(score) >= limit:
|
||||
bad.append((score, vid, comp))
|
||||
for score, vid, comp in sorted(bad, reverse=True)[:5]:
|
||||
print(f" {score:>5} {vid} {comp}")
|
||||
print(f"{len(bad)} finding(s) with CVSS >= {limit}")
|
||||
sys.exit(1 if bad else 0)
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reads the JSON report of osv-scanner, Trivy or Dependency-Check and prints one normalised
|
||||
record per finding: <tool> <group:artifact:version> <id> <severity-or-score>
|
||||
|
||||
Normalisation rules (kept deliberately simple so the comparison is easy to audit):
|
||||
* the id is the CVE alias when the report has one, otherwise the advisory id (GHSA-...)
|
||||
* the component is group:artifact:version in Maven coordinates
|
||||
Usage: normalise.py osv|trivy|dc report.json
|
||||
"""
|
||||
import json, re, sys
|
||||
|
||||
def osv(d):
|
||||
for res in d["results"]:
|
||||
for p in res["packages"]:
|
||||
pkg = p["package"]; comp = f'{pkg["name"]}:{pkg["version"]}'
|
||||
scores = {}
|
||||
for g in p.get("groups", []):
|
||||
for i in g["ids"]:
|
||||
scores[i] = g.get("max_severity", "")
|
||||
for v in p["vulnerabilities"]:
|
||||
cves = [a for a in v.get("aliases", []) if a.startswith("CVE-")]
|
||||
yield comp, (cves[0] if cves else v["id"]), scores.get(v["id"], "")
|
||||
|
||||
def trivy(d):
|
||||
for res in d.get("Results", []):
|
||||
for v in res.get("Vulnerabilities", []) or []:
|
||||
yield f'{v["PkgName"]}:{v["InstalledVersion"]}', v["VulnerabilityID"], v.get("Severity", "")
|
||||
|
||||
def dc(d):
|
||||
for dep in d.get("dependencies", []):
|
||||
pk = next((p["id"] for p in dep.get("packages", []) if p["id"].startswith("pkg:maven/")), None)
|
||||
if pk:
|
||||
m = re.match(r"pkg:maven/([^/]+)/([^@]+)@(.+)", pk)
|
||||
comp = f"{m.group(1)}:{m.group(2)}:{m.group(3)}"
|
||||
else:
|
||||
comp = dep["fileName"]
|
||||
for v in dep.get("vulnerabilities", []) or []:
|
||||
sev = v.get("severity", "")
|
||||
cv = v.get("cvssv3", {}).get("baseScore") or v.get("cvssv2", {}).get("score") or ""
|
||||
yield comp, v["name"], f"{sev}:{cv}" if cv != "" else sev
|
||||
|
||||
if __name__ == "__main__":
|
||||
tool, path = sys.argv[1], sys.argv[2]
|
||||
data = json.load(open(path))
|
||||
for comp, vid, sev in {"osv": osv, "trivy": trivy, "dc": dc}[tool](data):
|
||||
print(tool, comp, vid, sev, sep="\t")
|
||||
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/. See scripts/env.sh for tool locations and README.md for setup.
|
||||
# Needs: JDK 25, Maven 3.9, Go 1.24 (to install osv-scanner), Docker, outbound HTTPS to Maven Central,
|
||||
# api.osv.dev, ghcr.io / mirror.gcr.io (Trivy DB), nvd.nist.gov (Dependency-Check feed), cisa.gov.
|
||||
# Every output file is overwritten, none is deleted first.
|
||||
set -u
|
||||
. "$(dirname "$0")/env.sh"
|
||||
mkdir -p "$OUT" /tmp/raw "$TRIVY_CACHE"
|
||||
cd "$MODULE"
|
||||
UA='Mozilla/5.0'
|
||||
mvnq() { mvn -B "$@" 2>&1 | clean; }
|
||||
trivy() { docker run --rm -v "$MODULE":/src:ro -v "$TRIVY_CACHE":/root/.cache/trivy "$TRIVY_IMAGE" "$@"; }
|
||||
dc() { mvn -B org.owasp:dependency-check-maven:$DC_VERSION:check -DdataDirectory="$DC_DATA" -DautoUpdate=false \
|
||||
-DretireJsAnalyzerEnabled=false "$@" 2>&1; }
|
||||
count() { python3 scripts/normalise.py "$1" "$2" | wc -l; }
|
||||
metadata() { curl -s -A "$UA" "https://repo1.maven.org/maven2/$1/maven-metadata.xml" | grep -E '<(latest|release|lastUpdated)>'; }
|
||||
|
||||
# ---------------------------------------------------------------- 01 versions
|
||||
{
|
||||
echo '$ mvn -v'; mvnq -v | head -3
|
||||
echo; echo '$ osv-scanner --version'; $OSV --version 2>&1 | head -2
|
||||
echo; echo '$ trivy --version'; trivy --version
|
||||
echo; echo '$ curl .../org/owasp/dependency-check-maven/maven-metadata.xml | grep -E "<(latest|release|lastUpdated)>"'
|
||||
metadata org/owasp/dependency-check-maven
|
||||
echo; echo '$ curl https://proxy.golang.org/github.com/google/osv-scanner/v2/@latest'
|
||||
curl -s -A "$UA" https://proxy.golang.org/github.com/google/osv-scanner/v2/@latest | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["Version"], d["Time"])'
|
||||
echo; echo '$ curl https://proxy.golang.org/github.com/aquasecurity/trivy/@latest'
|
||||
curl -s -A "$UA" https://proxy.golang.org/github.com/aquasecurity/trivy/@latest | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["Version"], d["Time"])'
|
||||
echo; echo '$ mvn help:describe -Dplugin=org.owasp:dependency-check-maven:'$DC_VERSION' (goal names only)'
|
||||
mvnq help:describe -Dplugin=org.owasp:dependency-check-maven:$DC_VERSION | grep -E '^dependency-check:|^ dependency-check:' | head -20
|
||||
} > "$OUT/01-versions.txt" 2>&1
|
||||
|
||||
# ---------------------------------------------------------------- 02 project
|
||||
mvnq -q package cyclonedx:makeAggregateBom >/dev/null
|
||||
mvnq -q dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/lib >/dev/null
|
||||
{
|
||||
echo '$ mvn dependency:tree'; mvnq dependency:tree | sed -n '/dependency:.*tree/,$p' | grep -E '^\[INFO\] ([+|\\]|com\.ankurm)'
|
||||
echo; echo '$ ls target/lib (what ships: runtime scope only)'; ls target/lib
|
||||
echo; echo '$ grep -rl org.yaml src/main/java || echo "no source file imports org.yaml"'
|
||||
grep -rl 'org.yaml' src/main/java || echo "no source file imports org.yaml"
|
||||
echo; echo '$ java -cp "target/classes:target/lib/*" com.ankurm.vulnscan.OrderApp'
|
||||
java -cp "target/classes:target/lib/*" com.ankurm.vulnscan.OrderApp 2>&1 | grep -v '^Picked up'
|
||||
} > "$OUT/02-project.txt"
|
||||
|
||||
# ---------------------------------------------------------------- 03 osv-scanner
|
||||
{
|
||||
echo '$ osv-scanner scan source -L pom.xml'
|
||||
$OSV scan source -L pom.xml 2>&1 | clean; echo "exit code: ${PIPESTATUS[0]}"
|
||||
echo; echo '$ osv-scanner scan source -L pom.xml --no-resolve (direct dependencies only)'
|
||||
$OSV scan source -L pom.xml --no-resolve 2>&1 | clean | grep -E 'Scanned|^Total|No issues'
|
||||
} > "$OUT/03-osv-scanner.txt"
|
||||
$OSV scan source -L pom.xml --format json --output-file /tmp/raw/osv-pom.json >/dev/null 2>&1
|
||||
|
||||
# ---------------------------------------------------------------- 04 trivy
|
||||
{
|
||||
echo '$ trivy fs --scanners vuln pom.xml (table output, summary lines only)'
|
||||
trivy fs --scanners vuln --skip-version-check /src/pom.xml 2>&1 | grep -E 'pom.xml \(pom\)|^Total:'
|
||||
echo; echo '$ trivy fs ... -f json | one line per finding: component, id, severity'
|
||||
trivy fs --scanners vuln --skip-version-check -q -f json /src/pom.xml > /tmp/raw/trivy-pom.json
|
||||
python3 scripts/normalise.py trivy /tmp/raw/trivy-pom.json | cut -f2- | sort | sed 's/\t/ /g'
|
||||
} > "$OUT/04-trivy.txt"
|
||||
|
||||
# ---------------------------------------------------------------- 05 dependency-check
|
||||
if [ ! -f "$DC_DATA/odc.mv.db" ]; then
|
||||
mvn -B org.owasp:dependency-check-maven:$DC_VERSION:update-only -DdataDirectory="$DC_DATA" -DretireJsAnalyzerEnabled=false \
|
||||
'-DnvdDatafeedUrl=https://nvd.nist.gov/feeds/json/cve/2.0/nvdcve-2.0-{0}.json.gz' 2>&1 | clean \
|
||||
| grep -v 'Download Started' > "$OUT/05a-dc-database-build.txt"
|
||||
fi
|
||||
{
|
||||
echo '$ mvn org.owasp:dependency-check-maven:'$DC_VERSION':check -DautoUpdate=false -Dformats=JSON (log, trimmed)'
|
||||
S=$(date +%s)
|
||||
dc -Dformats=JSON -DfailBuildOnCVSS=11 | clean | grep -E 'Analysis Complete|Writing JSON|Total time|OSS Index|BUILD|Finished (Jar|CPE|NVD|Known)' | cut -c1-200
|
||||
echo "wall clock seconds: $(( $(date +%s) - S ))"
|
||||
cp target/dependency-check-report.json /tmp/raw/dc.json
|
||||
echo; echo '$ one line per finding: component, id, label:cvss'
|
||||
python3 scripts/normalise.py dc /tmp/raw/dc.json | cut -f2- | sort | sed 's/\t/ /g'
|
||||
} > "$OUT/05-dependency-check.txt"
|
||||
{
|
||||
echo '$ mvn org.owasp:dependency-check-maven:'$DC_VERSION':update-only (no -DnvdDatafeedUrl, no NVD API key)'
|
||||
D=$(mktemp -d)
|
||||
mvn -B -X org.owasp:dependency-check-maven:$DC_VERSION:update-only -DdataDirectory="$D" -DretireJsAnalyzerEnabled=false 2>&1 \
|
||||
| grep -E 'requesting URI|Status Code|Reason:|Key : message|Invalid API Key|BUILD (SUCCESS|FAILURE)' | cut -c1-220
|
||||
} > "$OUT/05b-dc-keyless-nvd-update.txt"
|
||||
|
||||
# ---------------------------------------------------------------- 06 compare
|
||||
python3 scripts/compare.py /tmp/raw/osv-pom.json /tmp/raw/trivy-pom.json /tmp/raw/dc.json > "$OUT/06-compare.txt"
|
||||
|
||||
# ---------------------------------------------------------------- 07 false positives
|
||||
{
|
||||
echo '== CVE-2026-34479: which artifact does the advisory describe?'
|
||||
echo '$ curl -s https://api.osv.dev/v1/vulns/CVE-2026-34479 | jq -r .summary'
|
||||
curl -s https://api.osv.dev/v1/vulns/CVE-2026-34479 | python3 -c 'import json,sys; print(json.load(sys.stdin)["summary"])'
|
||||
echo '$ unzip -l target/lib/log4j-core-2.14.1.jar | grep -c Log4j1XmlLayout'
|
||||
unzip -l target/lib/log4j-core-2.14.1.jar | grep -c Log4j1XmlLayout
|
||||
echo '$ unzip -l target/lib/log4j-api-2.14.1.jar | grep -c Log4j1XmlLayout'
|
||||
unzip -l target/lib/log4j-api-2.14.1.jar | grep -c Log4j1XmlLayout
|
||||
echo '$ ls target/lib | grep -c "log4j-1.2-api"'
|
||||
ls target/lib | grep -c "log4j-1.2-api"
|
||||
echo; echo '== where each tool attached CVE-2026-34479'
|
||||
for t in osv:osv-pom trivy:trivy-pom dc:dc; do python3 scripts/normalise.py ${t%%:*} /tmp/raw/${t##*:}.json | grep CVE-2026-34479 | cut -f1,2 | sed 's/\t/ /'; done
|
||||
echo; echo '== CVE-2023-35116 (reported only by dependency-check): the NVD description'
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d = json.load(open('/tmp/raw/dc.json'))
|
||||
for dep in d['dependencies']:
|
||||
for v in dep.get('vulnerabilities', []):
|
||||
if v['name'] == 'CVE-2023-35116':
|
||||
print(dep['fileName'], v['name'], v['severity'])
|
||||
print(v['description'])
|
||||
PY
|
||||
echo; echo '== CVE-2026-49844: OSV attaches it to log4j-api only; dependency-check also attaches it to log4j-core'
|
||||
python3 scripts/normalise.py dc /tmp/raw/dc.json | grep CVE-2026-49844 | cut -f2,3 | sed 's/\t/ /'
|
||||
curl -s https://api.osv.dev/v1/vulns/GHSA-qv9r-c865-cp47 | python3 -c 'import json,sys; d=json.load(sys.stdin); print("GHSA-qv9r-c865-cp47 affects:", sorted({a["package"]["name"] for a in d["affected"]}))'
|
||||
echo; echo '== why dependency-check misses 9 jackson advisories (3 jackson-core, 6 jackson-databind): NVD status of each id'
|
||||
for id in CVE-2025-52999 CVE-2026-68494 CVE-2026-89425 CVE-2026-19032 CVE-2026-59889 CVE-2026-77310 CVE-2026-83557 CVE-2026-91776 CVE-2026-91777; do
|
||||
curl -s -m 40 -A "$UA" "https://services.nvd.nist.gov/rest/json/cves/2.0?cveId=$id" | python3 -c '
|
||||
import json,sys
|
||||
c=json.load(sys.stdin)["vulnerabilities"][0]["cve"]
|
||||
print(c["id"], "status:", c["vulnStatus"], " has CPE configurations:", "configurations" in c)'
|
||||
sleep 7
|
||||
done
|
||||
} > "$OUT/07-false-positives.txt" 2>&1
|
||||
|
||||
# ---------------------------------------------------------------- 08 suppression
|
||||
{
|
||||
O=$(count osv /tmp/raw/osv-pom.json); echo "osv-scanner: $O findings with no config"
|
||||
$OSV scan source -L pom.xml --config config/osv-scanner.toml --format json --output-file /tmp/raw/o1.json >/dev/null 2>&1
|
||||
echo "osv-scanner: $(count osv /tmp/raw/o1.json) with config/osv-scanner.toml (ignoreUntil 2027-03-01)"
|
||||
$OSV scan source -L pom.xml --config config/osv-scanner-expired.toml --format json --output-file /tmp/raw/o2.json >/dev/null 2>&1
|
||||
echo "osv-scanner: $(count osv /tmp/raw/o2.json) with config/osv-scanner-expired.toml (ignoreUntil 2026-01-01, already past)"
|
||||
echo
|
||||
echo "trivy: $(count trivy /tmp/raw/trivy-pom.json) findings with no ignore file"
|
||||
for f in trivyignore trivyignore-expired; do
|
||||
trivy fs --scanners vuln --skip-version-check -q -f json --ignorefile /src/config/$f.yaml /src/pom.xml > /tmp/raw/t-$f.json
|
||||
echo "trivy: $(count trivy /tmp/raw/t-$f.json) with config/$f.yaml"
|
||||
done
|
||||
echo
|
||||
echo "dependency-check: $(count dc /tmp/raw/dc.json) findings with no suppression file"
|
||||
for f in dc-suppressions dc-suppressions-expired; do
|
||||
dc -Dformats=JSON -DsuppressionFiles=config/$f.xml -DfailBuildOnCVSS=11 >/dev/null
|
||||
cp target/dependency-check-report.json /tmp/raw/dc-$f.json
|
||||
echo "dependency-check: $(count dc /tmp/raw/dc-$f.json) with config/$f.xml"
|
||||
done
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d = json.load(open('/tmp/raw/dc-dc-suppressions.json'))
|
||||
print("dependency-check suppressed (kept in the report, not counted):", sorted({(v['name']) for dep in d['dependencies'] for v in dep.get('suppressedVulnerabilities', [])}))
|
||||
PY
|
||||
cp /tmp/raw/dc.json target/dependency-check-report.json
|
||||
} > "$OUT/08-suppression.txt" 2>&1
|
||||
|
||||
# ---------------------------------------------------------------- 09 SBOM
|
||||
{
|
||||
echo '$ mvn cyclonedx:makeAggregateBom -> target/bom.json'
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d = json.load(open('target/bom.json'))
|
||||
print("bomFormat", d["bomFormat"], "specVersion", d["specVersion"])
|
||||
print("components:", len(d["components"]))
|
||||
for c in d["components"]:
|
||||
print(" ", c["purl"])
|
||||
PY
|
||||
echo; echo '$ trivy sbom target/bom.json'
|
||||
trivy sbom --skip-version-check -q -f json /src/target/bom.json > /tmp/raw/trivy-sbom.json
|
||||
echo "findings: $(count trivy /tmp/raw/trivy-sbom.json) (same scan from the manifest: $(count trivy /tmp/raw/trivy-pom.json))"
|
||||
echo; echo '$ osv-scanner scan source -L target/bom.json'
|
||||
$OSV scan source -L target/bom.json --format json --output-file /tmp/raw/osv-sbom.json 2>&1 | clean | grep -E 'Scanned'
|
||||
echo "findings: $(count osv /tmp/raw/osv-sbom.json) (same scan from pom.xml: $(count osv /tmp/raw/osv-pom.json))"
|
||||
echo; echo 'difference between osv-scanner on pom.xml (<) and on the SBOM (>):'
|
||||
diff <(python3 scripts/normalise.py osv /tmp/raw/osv-pom.json | cut -f2,3 | sort) <(python3 scripts/normalise.py osv /tmp/raw/osv-sbom.json | cut -f2,3 | sort) | sed 's/\t/ /'
|
||||
echo; echo '$ the same SBOM with one component edited by hand (log4j-core 2.14.1 -> 2.26.1 in version and purl)'
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d = json.load(open('target/bom.json'))
|
||||
for c in d["components"]:
|
||||
if c["name"] == "log4j-core":
|
||||
c["version"] = "2.26.1"; c["purl"] = c["purl"].replace("2.14.1", "2.26.1")
|
||||
json.dump(d, open('/tmp/raw/bom-edited.json', 'w'))
|
||||
PY
|
||||
mkdir -p /tmp/raw/edited && cp /tmp/raw/bom-edited.json /tmp/raw/edited/bom.json
|
||||
docker run --rm -v /tmp/raw/edited:/e:ro -v "$TRIVY_CACHE":/root/.cache/trivy "$TRIVY_IMAGE" sbom --skip-version-check -q -f json /e/bom.json > /tmp/raw/trivy-sbom-edited.json
|
||||
echo "trivy findings on the edited SBOM: $(count trivy /tmp/raw/trivy-sbom-edited.json) (log4j-core findings: $(python3 scripts/normalise.py trivy /tmp/raw/trivy-sbom-edited.json | grep -c 'log4j-core'))"
|
||||
} > "$OUT/09-sbom.txt" 2>&1
|
||||
|
||||
# ---------------------------------------------------------------- 10 artifacts
|
||||
{
|
||||
echo '$ trivy rootfs target/lib (the real jars)'
|
||||
trivy rootfs --scanners vuln --skip-version-check -q -f json /src/target/lib > /tmp/raw/trivy-lib.json
|
||||
echo "findings: $(count trivy /tmp/raw/trivy-lib.json)"
|
||||
echo; echo '$ osv-scanner scan source -r --no-ignore target/lib (default plugins)'
|
||||
$OSV scan source -r --no-ignore target/lib 2>&1 | clean | tail -3
|
||||
echo; echo '$ osv-scanner scan source -r --no-ignore --x-plugins java/archive target/lib'
|
||||
$OSV scan source -r --no-ignore --x-plugins java/archive --format json --output-file /tmp/raw/osv-lib.json target/lib 2>&1 | clean | grep -E 'End status' | tail -1
|
||||
echo "findings: $(count osv /tmp/raw/osv-lib.json)"
|
||||
echo; echo '$ dependency-check (the Maven plugin always analyses the resolved jars; it has no manifest-only mode)'
|
||||
echo "findings: $(count dc /tmp/raw/dc.json). How it recognised jackson-databind-2.13.4.jar:"
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d = json.load(open('/tmp/raw/dc.json'))
|
||||
for dep in d['dependencies']:
|
||||
if dep['fileName'].startswith('jackson-databind'):
|
||||
for ident in dep.get('vulnerabilityIds', []):
|
||||
print(" ", ident['id'], "confidence", ident['confidence'])
|
||||
for p in dep.get('packages', []):
|
||||
print(" ", p['id'], "confidence", p['confidence'])
|
||||
PY
|
||||
echo; echo '$ osv-scanner scan source --no-ignore --x-plugins java/archive target/orders-1.0.0.jar (the thin application jar)'
|
||||
$OSV scan source --no-ignore --x-plugins java/archive target/orders-1.0.0.jar 2>&1 | clean | tail -2
|
||||
} > "$OUT/10-artifacts.txt" 2>&1
|
||||
|
||||
# ---------------------------------------------------------------- 11 gating
|
||||
{
|
||||
echo '== exit codes on the vulnerable project'
|
||||
$OSV scan source -L pom.xml >/dev/null 2>&1; echo "osv-scanner (no flag): exit $?"
|
||||
python3 scripts/gate.py /tmp/raw/osv-pom.json 9.0 | tail -1; echo "osv-scanner + scripts/gate.py 9.0: exit ${PIPESTATUS[0]}"
|
||||
trivy fs --scanners vuln --skip-version-check -q --exit-code 1 --severity CRITICAL /src/pom.xml >/dev/null 2>&1; echo "trivy --exit-code 1 --severity CRITICAL: exit $?"
|
||||
trivy fs --scanners vuln --skip-version-check -q /src/pom.xml >/dev/null 2>&1; echo "trivy (no --exit-code): exit $?"
|
||||
dc -Dformats=JSON -DfailBuildOnCVSS=9 >/tmp/raw/g1.log; echo "dependency-check -DfailBuildOnCVSS=9: exit $?"; grep -E 'Failed to execute|CVSS score' /tmp/raw/g1.log | cut -c1-230 | head -3
|
||||
dc -Dformats=JSON -DfailBuildOnCVSS=11 >/tmp/raw/g2.log; echo "dependency-check -DfailBuildOnCVSS=11: exit $?"
|
||||
echo; echo '== the same project with -Pfixed (all flagged dependencies moved to current releases)'
|
||||
mvnq -q -Pfixed package cyclonedx:makeAggregateBom >/dev/null
|
||||
mvnq -q -Pfixed dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/lib-fixed >/dev/null
|
||||
echo "runtime jars: $(ls target/lib-fixed | tr '\n' ' ')"
|
||||
$OSV scan source -L target/bom.json --format json --output-file /tmp/raw/osv-fixed.json >/dev/null 2>&1; echo "osv-scanner on the SBOM: exit $?; findings: $(count osv /tmp/raw/osv-fixed.json)"
|
||||
trivy sbom --skip-version-check -q -f json --exit-code 1 /src/target/bom.json > /tmp/raw/trivy-fixed.json 2>/dev/null; echo "trivy sbom --exit-code 1: exit $?; findings: $(count trivy /tmp/raw/trivy-fixed.json)"
|
||||
dc -Pfixed -Dformats=JSON -DfailBuildOnAnyVulnerability=true >/tmp/raw/g3.log; echo "dependency-check -Pfixed -DfailBuildOnAnyVulnerability=true: exit $?"
|
||||
cp target/dependency-check-report.json /tmp/raw/dc-fixed.json; echo "dependency-check findings: $(count dc /tmp/raw/dc-fixed.json)"
|
||||
echo; echo '== scope: a vulnerable test-scope dependency (commons-collections 3.2.1, pom.xml at its default versions)'
|
||||
echo "osv-scanner on pom.xml:"; $OSV scan source -L pom.xml 2>&1 | clean | grep -E 'commons-collections' | cut -c1-150
|
||||
trivy fs --scanners vuln --skip-version-check -q -f json /src/pom.xml > /tmp/raw/trivy-scope.json
|
||||
echo "trivy fs pom.xml: $(python3 scripts/normalise.py trivy /tmp/raw/trivy-scope.json | grep -c commons-collections) commons-collections findings"
|
||||
echo "dependency-check (jars): $(python3 scripts/normalise.py dc /tmp/raw/dc.json | grep -c commons-collections) commons-collections findings"
|
||||
} > "$OUT/11-gating-and-fix.txt" 2>&1
|
||||
mvnq -q package cyclonedx:makeAggregateBom >/dev/null
|
||||
|
||||
# ---------------------------------------------------------------- 12 footprint
|
||||
{
|
||||
echo '== what each tool keeps on disk'
|
||||
echo "dependency-check H2 database: $(du -sh "$DC_DATA" | cut -f1)"
|
||||
echo "trivy cache: $(du -sh "$TRIVY_CACHE" | cut -f1) (db $(du -sh "$TRIVY_CACHE/db" | cut -f1), java-db $(du -sh "$TRIVY_CACHE/java-db" | cut -f1))"
|
||||
echo "osv-scanner: nothing, it queries api.osv.dev (unless --offline-vulnerabilities)"
|
||||
echo; echo '== wall clock seconds, warm caches, this 2-vCPU sandbox'
|
||||
t() { local s; s=$(date +%s.%N); "$@" >/dev/null 2>&1; printf '%s %.1f\n' "$LABEL" "$(echo "$(date +%s.%N) - $s" | bc)"; }
|
||||
LABEL="osv-scanner scan source -L pom.xml: " t $OSV scan source -L pom.xml
|
||||
LABEL="trivy fs pom.xml (docker run): " t docker run --rm -v "$MODULE":/src:ro -v "$TRIVY_CACHE":/root/.cache/trivy "$TRIVY_IMAGE" fs --scanners vuln --skip-version-check /src/pom.xml
|
||||
LABEL="trivy sbom bom.json (docker run): " t docker run --rm -v "$MODULE":/src:ro -v "$TRIVY_CACHE":/root/.cache/trivy "$TRIVY_IMAGE" sbom --skip-version-check /src/target/bom.json
|
||||
LABEL="dependency-check:check (DB present): " t mvn -B org.owasp:dependency-check-maven:$DC_VERSION:check -DdataDirectory="$DC_DATA" -DautoUpdate=false -DretireJsAnalyzerEnabled=false -Dformats=JSON -DfailBuildOnCVSS=11
|
||||
echo; echo '== osv-scanner offline mode: download the Maven database once, then scan from it (the network was not cut for this run)'
|
||||
OFFLINE=$(mktemp -d)
|
||||
XDG_CACHE_HOME=$OFFLINE $OSV scan source -L pom.xml --offline-vulnerabilities --download-offline-databases 2>&1 | clean | grep -E 'Downloaded|Total|No issues|Error' | head -4
|
||||
echo "cache size: $(du -sh $OFFLINE | cut -f1)"
|
||||
XDG_CACHE_HOME=$OFFLINE $OSV scan source -L pom.xml --offline-vulnerabilities --format json --output-file /tmp/raw/osv-offline.json >/dev/null 2>&1
|
||||
echo "offline findings: $(count osv /tmp/raw/osv-offline.json) (online: $(count osv /tmp/raw/osv-pom.json))"
|
||||
} > "$OUT/12-footprint.txt" 2>&1
|
||||
echo done
|
||||
Reference in New Issue
Block a user