#!/usr/bin/env python3 """ Incremental update from FKIE NVD JSON feeds. Pulls CVE-Recent.json.xz (last 8 days) or CVE-Modified.json.xz from fkie-cad/nvd-json-data-feeds and patches our derived artifacts in place: data/knowledge_base/enhanced_documents_cve_.json ← per-CVE upsert data/knowledge_base/knowledge_graph/cves_nodes.json ← regen affected data/knowledge_base/knowledge_graph/cve_*_relationships.json ← regen affected data/knowledge_base/rag_exports/cve_chunks.json ← regen affected data/knowledge_base/bm25/vocab.json ← full rebuild (cheap) Cron-friendly: stores last-seen FKIE meta hash in .last_sync.json and is a no-op when upstream hasn't changed. Re-runnable, idempotent. CWE→CAPEC→TTP mapping uses the deterministic CWEtoCAPECtoTTPMapper, so incremental mapping is essentially free (no LLM calls). Usage: # Default: incremental, last 8 days python scripts/update_from_fkie.py # Catch-up across a longer gap (uses CVE-Modified, ~30 day window) python scripts/update_from_fkie.py --feed modified # Specific year(s) — for backfill / spot fixes python scripts/update_from_fkie.py --feed year --years 2025 2026 # Dry run: download + diff but don't write python scripts/update_from_fkie.py --dry-run """ from __future__ import annotations import argparse import json import logging import lzma import shutil import sys import tempfile import urllib.request from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Set, Tuple PROJECT_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(PROJECT_ROOT)) from src.generators.chunkers import CVEChunker # noqa: E402 from src.mapper.cve_cwe_mapper import CVEtoCWEtoTTPMapper # noqa: E402 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger("update_from_fkie") # ── Paths ───────────────────────────────────────────────────────────────────── KB_DIR = PROJECT_ROOT / "data" / "knowledge_base" KG_DIR = KB_DIR / "knowledge_graph" RAG_DIR = KB_DIR / "rag_exports" BM25_DIR = KB_DIR / "bm25" STATE_FILE = KB_DIR / ".last_sync.json" CWE_MAP_PATH = PROJECT_ROOT / "data" / "CTI" / "raw" / "cwe_capec_mitre_mapping.json" # ── FKIE feed ───────────────────────────────────────────────────────────────── FKIE_BASE = "https://github.com/fkie-cad/nvd-json-data-feeds/releases/latest/download" FEED_URLS = { "recent": f"{FKIE_BASE}/CVE-Recent.json.xz", "modified": f"{FKIE_BASE}/CVE-Modified.json.xz", } META_URLS = { "recent": f"{FKIE_BASE}/CVE-Recent.meta", "modified": f"{FKIE_BASE}/CVE-Modified.meta", } # ── State ───────────────────────────────────────────────────────────────────── @dataclass class SyncState: last_meta: Dict[str, str] # feed name -> meta file content last_run: Optional[str] @classmethod def load(cls) -> "SyncState": if STATE_FILE.exists(): d = json.loads(STATE_FILE.read_text()) return cls(last_meta=d.get("last_meta", {}), last_run=d.get("last_run")) return cls(last_meta={}, last_run=None) def save(self) -> None: STATE_FILE.write_text(json.dumps({ "last_meta": self.last_meta, "last_run": datetime.now(timezone.utc).isoformat(), }, indent=2)) # ── HTTP ────────────────────────────────────────────────────────────────────── def _fetch(url: str, dst: Path) -> None: log.info(f"fetching {url}") req = urllib.request.Request(url, headers={"User-Agent": "cve-kgrag-update/1.0"}) with urllib.request.urlopen(req, timeout=60) as r, dst.open("wb") as f: shutil.copyfileobj(r, f) def _fetch_text(url: str) -> str: req = urllib.request.Request(url, headers={"User-Agent": "cve-kgrag-update/1.0"}) with urllib.request.urlopen(req, timeout=30) as r: return r.read().decode("utf-8", errors="replace") def _check_upstream_changed(feed: str, state: SyncState) -> Tuple[bool, str]: """Return (changed, latest_meta_text).""" try: meta = _fetch_text(META_URLS[feed]) except Exception as e: log.warning(f"could not fetch .meta: {e}; assuming changed") return True, "" prev = state.last_meta.get(feed, "") return meta != prev, meta def _load_fkie_payload(feed: str, year_override: Optional[int] = None) -> List[Dict[str, Any]]: """Download and decompress a FKIE feed → list of CVE objects.""" if feed == "year": assert year_override is not None url = f"{FKIE_BASE}/CVE-{year_override}.json.xz" else: url = FEED_URLS[feed] with tempfile.TemporaryDirectory() as td: xz_path = Path(td) / "feed.json.xz" _fetch(url, xz_path) with lzma.open(xz_path, "rb") as f: payload = json.load(f) # FKIE structure: {"cve_items": [...], "CVE_Items": [...], or top-level list} if isinstance(payload, list): return payload for k in ("cve_items", "CVE_Items", "vulnerabilities"): if k in payload: v = payload[k] return v if isinstance(v, list) else list(v.values()) raise ValueError(f"unrecognised FKIE payload schema: keys={list(payload)[:5]}") # ── FKIE → our enhanced_doc shape ───────────────────────────────────────────── def _last_modified(fkie_cve: Dict[str, Any]) -> str: """Best-effort extract lastModified ISO timestamp from FKIE record.""" for k in ("lastModified", "last_modified_date", "lastModifiedDate"): if k in fkie_cve and fkie_cve[k]: return fkie_cve[k] cve = fkie_cve.get("cve") or {} for k in ("lastModified", "lastModifiedDate"): if k in cve and cve[k]: return cve[k] return "" def _cve_id(fkie_cve: Dict[str, Any]) -> str: cve = fkie_cve.get("cve") or fkie_cve return cve.get("id") or cve.get("CVE_data_meta", {}).get("ID") or fkie_cve.get("id", "") def _description(fkie_cve: Dict[str, Any]) -> str: cve = fkie_cve.get("cve") or fkie_cve descs = cve.get("descriptions") or cve.get("description", {}).get("description_data") or [] for d in descs: if d.get("lang") in ("en", None): return d.get("value", "") return descs[0].get("value", "") if descs else "" def _cwe_ids(fkie_cve: Dict[str, Any]) -> List[str]: cve = fkie_cve.get("cve") or fkie_cve out: List[str] = [] for w in cve.get("weaknesses", []): for d in w.get("description", []): v = d.get("value", "") if v.upper().startswith("CWE-"): out.append(v.upper()) if not out: for ptype in cve.get("problemtype", {}).get("problemtype_data", []): for d in ptype.get("description", []): v = d.get("value", "") if v.upper().startswith("CWE-"): out.append(v.upper()) return sorted(set(out)) def _cvss(fkie_cve: Dict[str, Any], version: str) -> Dict[str, Any]: cve = fkie_cve.get("cve") or fkie_cve metrics = cve.get("metrics", {}) keys = { "v3": ("cvssMetricV31", "cvssMetricV30"), "v2": ("cvssMetricV2",), }[version] for k in keys: for m in metrics.get(k, []): d = m.get("cvssData", {}) if not d: continue return { "version": d.get("version", ""), "base_score": d.get("baseScore"), "base_severity": d.get("baseSeverity") or m.get("baseSeverity") or "", "vector_string": d.get("vectorString", ""), } return {} def _affected_products(fkie_cve: Dict[str, Any]) -> List[str]: """Extract simple product names from CPEs (vendor:product style).""" cve = fkie_cve.get("cve") or fkie_cve products: Set[str] = set() for cfg in cve.get("configurations", []): for node in cfg.get("nodes", []): for cm in node.get("cpeMatch", []): cpe = cm.get("criteria") or cm.get("cpe23Uri", "") parts = cpe.split(":") if len(parts) >= 5 and parts[4]: products.add(parts[4]) return sorted(products) def _references(fkie_cve: Dict[str, Any]) -> List[str]: cve = fkie_cve.get("cve") or fkie_cve refs = cve.get("references", []) out = [] for r in refs: url = r.get("url") or r.get("URL", "") if url: out.append(url) return out def fkie_to_enhanced_doc(fkie_cve: Dict[str, Any], mapper: CVEtoCWEtoTTPMapper) -> Optional[Dict[str, Any]]: """Convert one FKIE CVE record into the enhanced_documents schema.""" cve_id = _cve_id(fkie_cve) if not cve_id: return None description = _description(fkie_cve) if not description: return None cve = fkie_cve.get("cve") or fkie_cve cvss_v3 = _cvss(fkie_cve, "v3") cvss_v2 = _cvss(fkie_cve, "v2") cwe_ids = _cwe_ids(fkie_cve) products = _affected_products(fkie_cve) references = _references(fkie_cve) # CWE → CAPEC → MITRE technique/tactic (deterministic, no LLM) cve_for_mapper = {"id": cve_id, "cwe_refs": cwe_ids, "cwe_ids": cwe_ids} ttp_ids, mapping_details = mapper.map_cve_to_ttps(cve_for_mapper) capec_entries: List[str] = [] for m in mapping_details.get("mappings", []): capec_entries.extend(m.get("capecs", [])) capec_entries = sorted(set(capec_entries)) mitre_techniques = sorted({t for t in ttp_ids if t.startswith("T")}) mitre_tactics = sorted({t for t in ttp_ids if t.startswith("TA")}) # Build the embedding content content_parts: List[str] = [description] if cvss_v3.get("base_score") is not None: content_parts.append(f"CVSS v{cvss_v3.get('version','3.x')} Score: {cvss_v3['base_score']} ({cvss_v3.get('base_severity','Unknown')})") if cvss_v3.get("vector_string"): content_parts.append(f"CVSS v{cvss_v3.get('version','3.x')} Vector: {cvss_v3['vector_string']}") if cvss_v2.get("base_score") is not None: content_parts.append(f"CVSS v2.0 Score: {cvss_v2['base_score']} ({cvss_v2.get('base_severity','Unknown')})") if products: content_parts.append(f"Affected Products: {', '.join(products[:5])}") if cwe_ids: content_parts.append(f"Related CWEs: {', '.join(cwe_ids)}") if capec_entries: content_parts.append(f"Related CAPECs: {', '.join(capec_entries[:3])}") if mitre_techniques: content_parts.append(f"MITRE ATT&CK Techniques: {', '.join(mitre_techniques[:3])}") if mitre_tactics: content_parts.append(f"MITRE ATT&CK Tactics: {', '.join(mitre_tactics[:3])}") if references: content_parts.append(f"References: {', '.join(references[:3])}") return { "id": cve_id, "title": f"CVE {cve_id}", "content": "\n".join(content_parts), "source": "FKIE/NVD", "document_type": "CVE", "cve_refs": [cve_id], "cwe_refs": cwe_ids, "capec_entries": capec_entries, "mitre_techniques": mitre_techniques, "mitre_tactics": mitre_tactics, "cvss_v3": cvss_v3, "cvss_v2": cvss_v2, "affected_products": products, "cpe_configurations": cve.get("configurations", []), "published_date": cve.get("published") or cve.get("publishedDate", ""), "last_modified_date": _last_modified(fkie_cve), "is_in_kev": bool(cve.get("cisaExploitAdd")), "references": references, "tags": sorted({t for t in (cwe_ids + capec_entries + mitre_techniques) if t}), } # ── File operations ─────────────────────────────────────────────────────────── def _year_of(cve_id: str) -> str: parts = cve_id.split("-") return parts[1] if len(parts) >= 3 and parts[1].isdigit() else "other" def _atomic_write_json(path: Path, data: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") with tmp.open("w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) tmp.replace(path) def _load_year_file(year: str) -> List[Dict[str, Any]]: p = KB_DIR / f"enhanced_documents_cve_{year}.json" if not p.exists(): return [] with p.open("r", encoding="utf-8") as f: return json.load(f) def upsert_enhanced_docs(new_docs: List[Dict[str, Any]], dry_run: bool) -> Tuple[Dict[str, Dict[str, int]], Set[str]]: """Group by year, merge by CVE id, only write when lastModified is newer. Returns (per-year stats, set of CVE ids that were actually added or updated). """ by_year: Dict[str, List[Dict[str, Any]]] = {} for d in new_docs: by_year.setdefault(_year_of(d["id"]), []).append(d) stats: Dict[str, Dict[str, int]] = {} touched: Set[str] = set() for year, batch in by_year.items(): existing = _load_year_file(year) index = {d["id"]: i for i, d in enumerate(existing)} added = updated = skipped = 0 for new in batch: i = index.get(new["id"]) if i is None: existing.append(new) added += 1 touched.add(new["id"]) continue old_mod = existing[i].get("last_modified_date", "") new_mod = new.get("last_modified_date", "") if new_mod and new_mod <= old_mod: skipped += 1 continue existing[i] = new updated += 1 touched.add(new["id"]) stats[year] = {"added": added, "updated": updated, "skipped": skipped} if dry_run: log.info(f" [dry-run] {year}: +{added} ~{updated} ={skipped}") else: _atomic_write_json(KB_DIR / f"enhanced_documents_cve_{year}.json", existing) log.info(f" {year}: +{added} ~{updated} ={skipped}") return stats, touched def regenerate_chunks_for(cve_ids: Set[str], dry_run: bool) -> None: """Patch rag_exports/cve_chunks.json — drop old chunks for these CVEs, re-chunk fresh docs.""" if not cve_ids: return path = RAG_DIR / "cve_chunks.json" chunks: List[Dict[str, Any]] = [] if path.exists(): with path.open("r", encoding="utf-8") as f: chunks = json.load(f) kept = [c for c in chunks if c.get("payload", {}).get("cve_id") not in cve_ids] # Re-chunk from the freshly-written enhanced docs chunker = CVEChunker() years_needed = {_year_of(c) for c in cve_ids} new_chunks: List[Dict[str, Any]] = [] for year in years_needed: for doc in _load_year_file(year): if doc["id"] in cve_ids: new_chunks.extend(chunker.chunk(doc)) out = kept + new_chunks log.info(f" cve_chunks.json: kept {len(kept):,}, +{len(new_chunks):,} new (was {len(chunks):,})") if not dry_run: _atomic_write_json(path, out) def regenerate_kg_rows_for(cve_ids: Set[str], dry_run: bool) -> None: """Patch knowledge_graph/*.json — drop CVE rows + relationships involving these CVEs, re-emit.""" if not cve_ids: return # Load fresh enhanced docs for these CVEs docs_by_id: Dict[str, Dict[str, Any]] = {} for year in {_year_of(c) for c in cve_ids}: for d in _load_year_file(year): if d["id"] in cve_ids: docs_by_id[d["id"]] = d # cves_nodes.json — replace rows nodes_path = KG_DIR / "cves_nodes.json" if nodes_path.exists(): with nodes_path.open("r", encoding="utf-8") as f: nodes = json.load(f) rows = list(nodes.values()) if isinstance(nodes, dict) else nodes kept = [r for r in rows if (r.get("id") or r.get("cve_id")) not in cve_ids] for cve_id, doc in docs_by_id.items(): kept.append({ "id": cve_id, "node_type": "CVE", "description": (doc.get("content") or "").split("\n", 1)[0], "cvss_v3": doc.get("cvss_v3", {}), "cvss_v2": doc.get("cvss_v2", {}), "severity": doc.get("cvss_v3", {}).get("base_severity", "UNKNOWN"), "published": doc.get("published_date", ""), "last_modified": doc.get("last_modified_date", ""), "in_kev": bool(doc.get("is_in_kev", False)), }) log.info(f" cves_nodes.json: kept {len(kept) - len(docs_by_id):,}, +{len(docs_by_id):,} replaced") if not dry_run: _atomic_write_json(nodes_path, kept) # Relationships — for each affected CVE, regenerate edges from its enhanced doc rel_specs = [ ("cve_cwe_relationships.json", "cwe_refs", "cwe_id"), ("cve_capec_relationships.json", "capec_entries", "capec_id"), ("cve_mitre_technique_relationships.json", "mitre_techniques", "technique_id"), ("cve_mitre_tactic_relationships.json", "mitre_tactics", "tactic_id"), ] for fname, source_field, target_key in rel_specs: path = KG_DIR / fname if not path.exists(): continue with path.open("r", encoding="utf-8") as f: rels = json.load(f) kept = [r for r in rels if r.get("cve_id") not in cve_ids] added = 0 for cve_id, doc in docs_by_id.items(): for target in doc.get(source_field, []): kept.append({"cve_id": cve_id, target_key: target}) added += 1 log.info(f" {fname}: +{added}") if not dry_run: _atomic_write_json(path, kept) # cve_product_relationships.json — keyed by product name prod_path = KG_DIR / "cve_product_relationships.json" if prod_path.exists(): with prod_path.open("r", encoding="utf-8") as f: rels = json.load(f) kept = [r for r in rels if r.get("cve_id") not in cve_ids] added = 0 for cve_id, doc in docs_by_id.items(): for product in doc.get("affected_products", []): kept.append({"cve_id": cve_id, "product": product}) added += 1 log.info(f" cve_product_relationships.json: +{added}") if not dry_run: _atomic_write_json(prod_path, kept) # ── Main ────────────────────────────────────────────────────────────────────── def main() -> int: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--feed", choices=["recent", "modified", "year"], default="recent", help="recent=last 8d, modified=~30d, year=full per-year file (needs --years)") p.add_argument("--years", type=int, nargs="+", help="When --feed year: which years to refresh") p.add_argument("--dry-run", action="store_true", help="Compute the diff but write nothing") p.add_argument("--force", action="store_true", help="Run even if FKIE .meta says nothing changed") args = p.parse_args() if args.feed == "year" and not args.years: p.error("--feed year requires --years YYYY [YYYY ...]") if not CWE_MAP_PATH.exists(): log.error(f"CWE→CAPEC→TTP mapping not found at {CWE_MAP_PATH}; bootstrap pipeline first") return 2 mapper = CVEtoCWEtoTTPMapper(CWE_MAP_PATH) state = SyncState.load() if args.feed != "year": changed, meta = _check_upstream_changed(args.feed, state) if not changed and not args.force: log.info(f"FKIE feed '{args.feed}' unchanged since last run — nothing to do") return 0 state.last_meta[args.feed] = meta # Pull payload(s) raw: List[Dict[str, Any]] = [] if args.feed == "year": for y in args.years: raw.extend(_load_fkie_payload("year", year_override=y)) else: raw = _load_fkie_payload(args.feed) log.info(f"feed contains {len(raw):,} CVE records") # Convert and upsert log.info("converting → enhanced docs …") new_docs: List[Dict[str, Any]] = [] for rec in raw: d = fkie_to_enhanced_doc(rec, mapper) if d: new_docs.append(d) log.info(f"built {len(new_docs):,} enhanced docs") stats, touched = upsert_enhanced_docs(new_docs, dry_run=args.dry_run) log.info(f"regenerating chunks + KG rows for {len(touched):,} CVEs …") regenerate_chunks_for(touched, dry_run=args.dry_run) regenerate_kg_rows_for(touched, dry_run=args.dry_run) if args.dry_run: log.info("dry-run complete; state file not updated") else: state.save() log.info(f"state saved → {STATE_FILE}") log.info("note: bm25/vocab.json is not rebuilt incrementally — run `python scripts/build_bm25_vocab.py` " "(or upstream tooling) on a weekly cadence if you want fresh IDF.") return 0 if __name__ == "__main__": sys.exit(main())