mvd001/cyberset / scripts /parse_nvd.py
mvd001's picture
download
raw
4.81 kB
"""NVD JSON 2.0 yearly + modified feeds -> _intermediate/nvd_<feed>.parquet and nvd_fix_<feed>.parquet (streaming, ijson)."""
import sys, os, glob, gzip, ijson, multiprocessing as mp
import pyarrow as pa, pyarrow.parquet as pq
sys.path.insert(0, os.path.dirname(__file__))
from hubcommon import INTER, RAW, parse_commit_url, norm_repo
CVSS_T = pa.struct([("vector", pa.string()), ("base_score", pa.float64()), ("source", pa.string())])
CPE_T = pa.struct([("criteria", pa.string()), ("version_start_including", pa.string()), ("version_start_excluding", pa.string()),
("version_end_including", pa.string()), ("version_end_excluding", pa.string())])
SCHEMA = pa.schema([
("cve_id", pa.string()), ("feed", pa.string()), ("published", pa.string()), ("last_modified", pa.string()),
("vuln_status", pa.string()), ("source_identifier", pa.string()), ("description", pa.string()),
("cwe_ids", pa.list_(pa.string())), ("cvss_v2", CVSS_T), ("cvss_v3", CVSS_T), ("cvss_v4", CVSS_T),
("cpe_matches", pa.list_(CPE_T)), ("n_references", pa.int32()), ("patch_ref_urls", pa.list_(pa.string())),
("cisa_kev_added", pa.string()),
])
FIX_SCHEMA = pa.schema([("cve_id", pa.string()), ("last_modified", pa.string()), ("repo_url", pa.string()), ("sha", pa.string()),
("source", pa.string()), ("evidence", pa.string()), ("score", pa.float64()), ("ref_url", pa.string())])
def pick(metrics, key):
lst = metrics.get(key) or []
if not lst: return None
lst = sorted(lst, key=lambda m: 0 if m.get("type") == "Primary" else 1)
d = lst[0].get("cvssData", {})
return {"vector": d.get("vectorString"), "base_score": d.get("baseScore"), "source": lst[0].get("source")}
def work(path):
feed = os.path.basename(path).replace("nvdcve-2.0-", "").replace(".json.gz", "")
rows, fixes = [], []
with gzip.open(path, "rb") as f:
for item in ijson.items(f, "vulnerabilities.item", use_float=True):
c = item["cve"]; cid = c["id"]
desc = next((d["value"] for d in c.get("descriptions", []) if d.get("lang") == "en"), None)
cw = []
for w in c.get("weaknesses", []) or []:
for d in w.get("description", []):
v = d.get("value", "")
if v.startswith("CWE-") and v not in cw: cw.append(v)
m = c.get("metrics", {}) or {}
v3 = pick(m, "cvssMetricV31") or pick(m, "cvssMetricV30")
cpes, seen = [], set()
for cfg in c.get("configurations", []) or []:
for node in cfg.get("nodes", []) or []:
for cm in node.get("cpeMatch", []) or []:
if not cm.get("vulnerable"): continue
k = (cm.get("criteria"), cm.get("versionStartIncluding"), cm.get("versionStartExcluding"),
cm.get("versionEndIncluding"), cm.get("versionEndExcluding"))
if k in seen: continue
seen.add(k)
cpes.append(dict(zip(["criteria", "version_start_including", "version_start_excluding",
"version_end_including", "version_end_excluding"], k)))
refs = c.get("references", []) or []
patch_urls = []
for r in refs:
tags = r.get("tags") or []
if "Patch" in tags:
u = r.get("url")
if u not in patch_urls: patch_urls.append(u)
for u in patch_urls:
pc = parse_commit_url(u)
if pc:
fixes.append(dict(cve_id=cid, last_modified=c.get("lastModified"), repo_url=norm_repo(pc[0]), sha=pc[1],
source="nvd", evidence="nvd_ref_tag:Patch", score=0.9, ref_url=u))
rows.append(dict(cve_id=cid, feed=feed, published=c.get("published"), last_modified=c.get("lastModified"),
vuln_status=c.get("vulnStatus"), source_identifier=c.get("sourceIdentifier"), description=desc, cwe_ids=cw,
cvss_v2=pick(m, "cvssMetricV2"), cvss_v3=v3, cvss_v4=pick(m, "cvssMetricV40"), cpe_matches=cpes,
n_references=len(refs), patch_ref_urls=patch_urls, cisa_kev_added=c.get("cisaExploitAdd")))
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), f"{INTER}/nvd_{feed}.parquet", compression="zstd")
pq.write_table(pa.Table.from_pylist(fixes, schema=FIX_SCHEMA), f"{INTER}/nvdfix_{feed}.parquet", compression="zstd")
return feed, len(rows), len(fixes)
if __name__ == "__main__":
files = sorted(glob.glob(f"{RAW}/nvd/*/nvdcve-2.0-*.json.gz"), key=os.path.getsize, reverse=True)
with mp.Pool(4) as p:
for r in p.imap_unordered(work, files): print(*r, flush=True)

Xet Storage Details

Size:
4.81 kB
·
Xet hash:
90a2dfe1cba28dcbeed34b6d505a93eea146aa1830627b51cedee4b7e5c744ce

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.