File size: 4,495 Bytes
c4c44be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | #!/usr/bin/env python3
"""Find CVEs that have identified diff URLs in NVD but no usable .diff file.
Walks every nvdcve-2.0-YYYY.json under dataset/nvd/data, collects the same
diff-bearing reference URLs that download.py would try to fetch, then
verifies that the expected file (data/<year>/<bucket>xxx/CVE-YYYY-NNNN.diff)
exists and contains real diff content.
Statuses:
missing no file on disk
empty file exists but is 0-byte
invalid file exists but contains no `diff --git ` and no
git-format-patch header (likely HTML / 404 / JSON error)
ok file is a real diff (not reported)
Outputs (under <cve_diff>/.logs/, next to failures.tsv):
missing.log one line per (CVE, original URL): ts, status, cve, url
missing.tsv cve, status, expected_path, original_url, diff_url
Complements failures.tsv: failures.tsv lists per-URL fetch failures,
missing.tsv surfaces CVEs whose final .diff file is absent or invalid as
a whole — including cases the downloader silently skipped.
Usage:
python missing.py
"""
from __future__ import annotations
import datetime as dt
import json
import pathlib
import sys
SCRIPT_DIR = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(SCRIPT_DIR))
import download # noqa: E402 reuse filter_url / to_diff_url / target_for
NVD_DIR = download.DATA_DIR
LOG_DIR = download.LOG_DIR
def extract_pairs():
"""Yield (cve_id, [url, ...]) for every CVE whose NVD references contain
at least one URL that download.py would treat as a diff source."""
for path in sorted(NVD_DIR.glob("nvdcve-2.0-*.json")):
print(f"[scan] {path.name}", file=sys.stderr)
try:
with open(path, "rb") as fh:
data = json.load(fh)
except (OSError, json.JSONDecodeError) as e:
print(f"[warn] failed to parse {path.name}: {e}", file=sys.stderr)
continue
for item in data.get("vulnerabilities", []):
cve = item.get("cve") or {}
cve_id = cve.get("id")
if not cve_id:
continue
urls = []
seen = set()
for ref in cve.get("references") or []:
url = ref.get("url")
if url and url not in seen and download.filter_url(url):
urls.append(url)
seen.add(url)
if urls:
yield cve_id, urls
def classify(target: pathlib.Path) -> str:
if not target.is_file():
return "missing"
try:
body = target.read_bytes()
except OSError:
return "missing"
if not body:
return "empty"
if not download.looks_like_diff(body):
return "invalid"
return "ok"
def main() -> int:
if not NVD_DIR.is_dir():
print(f"error: {NVD_DIR} is not a directory", file=sys.stderr)
return 2
LOG_DIR.mkdir(parents=True, exist_ok=True)
log_path = LOG_DIR / "missing.log"
tsv_path = LOG_DIR / "missing.tsv"
n_total = 0
counts = {"ok": 0, "missing": 0, "empty": 0, "invalid": 0}
with open(log_path, "w", encoding="utf-8") as log, \
open(tsv_path, "w", encoding="utf-8") as tsv:
tsv.write("cve\tstatus\texpected_path\toriginal_url\tdiff_url\n")
for cve_id, urls in extract_pairs():
n_total += 1
target = download.target_for(cve_id)
status = classify(target)
counts[status] += 1
if status == "ok":
continue
try:
rel_target = target.relative_to(SCRIPT_DIR)
except ValueError:
rel_target = target
ts = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for url in urls:
diff_url = download.to_diff_url(url) or ""
log.write(f"{ts}\t{status}\t{cve_id}\t{url}\n")
tsv.write(
f"{cve_id}\t{status}\t{rel_target}\t{url}\t{diff_url}\n"
)
bad = counts["missing"] + counts["empty"] + counts["invalid"]
print(f"[done] {n_total} CVE(s) with diff URLs", file=sys.stderr)
print(
f" ok={counts['ok']} missing={counts['missing']} "
f"empty={counts['empty']} invalid={counts['invalid']}",
file=sys.stderr,
)
print(f" log={log_path}", file=sys.stderr)
print(f" tsv={tsv_path}", file=sys.stderr)
return 1 if bad else 0
if __name__ == "__main__":
sys.exit(main())
|