ccrb / scripts /ingest /normalize_kev_nvd.py
prshrs's picture
Upload CCRB v0.2-dev cybersecurity retrieval benchmark
8510f62 verified
Raw History Blame Contribute Delete
4.26 kB
"""Normalize CISA KEV and NVD JSON 2.0 feeds into CCRB CVE documents and graph edges."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
def _clean_ws(text: str | None) -> str:
if not text:
return ""
return re.sub(r"\s+", " ", text).strip()
def parse_cisa_kev(kev_path: Path) -> tuple[list[dict[str, Any]], list[dict[str, str]], set[str]]:
"""Parse CISA KEV JSON feed into CVE documents, CVE->CWE edges, and KEV CVE ID set."""
payload = json.loads(kev_path.read_text(encoding="utf-8"))
docs: list[dict[str, Any]] = []
edges: list[dict[str, str]] = []
kev_cves: set[str] = set()
for item in payload.get("vulnerabilities", []):
cve_id = str(item.get("cveID", "")).strip()
if not cve_id:
continue
kev_cves.add(cve_id)
vendor = _clean_ws(item.get("vendorProject"))
product = _clean_ws(item.get("product"))
vuln_name = _clean_ws(item.get("vulnerabilityName"))
short_desc = _clean_ws(item.get("shortDescription"))
req_action = _clean_ws(item.get("requiredAction"))
date_added = str(item.get("dateAdded", "")).strip()
cwes = [str(c).strip() for c in item.get("cwes", []) if str(c).strip()]
for cwe in cwes:
edges.append({"src": cve_id, "rel": "has_cwe", "dst": cwe})
parts = [short_desc]
if vendor or product:
parts.append(f"Affected product: {vendor} {product}".strip())
if req_action:
parts.append(f"Required remediation: {req_action}")
if cwes:
parts.append(f"Mapped weaknesses: {', '.join(cwes)}")
docs.append(
{
"document_id": f"cve_doc_{cve_id}",
"title": f"{cve_id}: {vuln_name or f'{vendor} {product} vulnerability'}",
"text": "\n\n".join(p for p in parts if p),
"source": "CISA KEV",
"track": "cve",
"source_id": cve_id,
"license": "Public-Domain-US-Gov",
"published_date": date_added,
"kev": True,
"url": f"https://nvd.nist.gov/vuln/detail/{cve_id}",
}
)
return docs, edges, kev_cves
def parse_nvd_page(
nvd_path: Path,
*,
kev_cves: set[str] | None = None,
) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
"""Parse a single NVD JSON 2.0 response file into CVE documents and CVE->CWE edges."""
payload = json.loads(nvd_path.read_text(encoding="utf-8"))
docs: list[dict[str, Any]] = []
edges: list[dict[str, str]] = []
kev_set = kev_cves or set()
for wrapper in payload.get("vulnerabilities", []):
cve = wrapper.get("cve", {})
cve_id = str(cve.get("id", "")).strip()
if not cve_id:
continue
if cve.get("vulnStatus") == "Rejected":
continue
en_descs = [
_clean_ws(d.get("value"))
for d in cve.get("descriptions", [])
if d.get("lang") == "en" and d.get("value")
]
if not en_descs:
continue
cwes: list[str] = []
for weakness in cve.get("weaknesses", []):
for desc in weakness.get("description", []):
val = str(desc.get("value", "")).strip()
if val.startswith("CWE-"):
cwes.append(val)
edges.append({"src": cve_id, "rel": "has_cwe", "dst": val})
pub_date = str(cve.get("published", ""))[:10]
text_parts = [en_descs[0]]
if cwes:
text_parts.append("Associated weaknesses: " + ", ".join(sorted(set(cwes))))
docs.append(
{
"document_id": f"cve_doc_{cve_id}",
"title": f"{cve_id}: {en_descs[0][:110]}",
"text": "\n\n".join(text_parts),
"source": "NVD",
"track": "cve",
"source_id": cve_id,
"license": "Public-Domain-US-Gov",
"published_date": pub_date,
"kev": cve_id in kev_set,
"url": f"https://nvd.nist.gov/vuln/detail/{cve_id}",
}
)
return docs, edges