-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathnvd_store.py
More file actions
80 lines (63 loc) · 2.25 KB
/
Copy pathnvd_store.py
File metadata and controls
80 lines (63 loc) · 2.25 KB
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
"""Cumulative storage for raw NVD JSON.
NVD's API returns a flat list of vulnerability objects. For incremental
updates we need to keep a single on-disk corpus that earlier CVEs are still
in, merging each week's delta in by CVE ID.
This module owns the merge logic so `build_tables.py` can keep reading a
single authoritative `nvd_cves.json` without knowing it was built across
multiple runs.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
log = logging.getLogger(__name__)
def _cve_id(item):
return item.get("cve", {}).get("id")
def merge_nvd_json(cumulative_path, delta_path):
"""Merge delta NVD JSON into the cumulative file, keyed by CVE ID.
Delta entries overwrite cumulative ones (so late-edit fields like CVSS
re-scoring or newly added references land correctly).
Args:
cumulative_path: existing cumulative JSON (created if missing).
delta_path: JSON produced by a delta download run.
Returns:
(inserted_ids, updated_ids) — lists of CVE IDs for changelog use.
"""
cumulative_path = Path(cumulative_path)
delta_path = Path(delta_path)
if cumulative_path.exists() and cumulative_path.stat().st_size > 0:
with open(cumulative_path) as f:
cumulative = json.load(f)
else:
cumulative = []
index = {}
for i, item in enumerate(cumulative):
cid = _cve_id(item)
if cid:
index[cid] = i
with open(delta_path) as f:
delta = json.load(f)
inserted = []
updated = []
for item in delta:
cid = _cve_id(item)
if not cid:
continue
if cid in index:
cumulative[index[cid]] = item
updated.append(cid)
else:
index[cid] = len(cumulative)
cumulative.append(item)
inserted.append(cid)
# Atomic write.
cumulative_path.parent.mkdir(parents=True, exist_ok=True)
tmp = cumulative_path.with_suffix(cumulative_path.suffix + ".tmp")
with open(tmp, "w") as f:
json.dump(cumulative, f)
tmp.replace(cumulative_path)
log.info(
"NVD JSON merge: inserted=%d updated=%d total=%d",
len(inserted), len(updated), len(cumulative),
)
return inserted, updated