File size: 4,258 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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