#!/usr/bin/env python3 """ Neo4j Graph Service — replaces NetworkX graph builder. Responsibilities ---------------- 1. bulk_load() — load all KG JSON files into Neo4j in batched transactions. 2. similar_cves() — find CVEs related by shared CWE / product / vendor. 3. subgraph_for_cves() — expand a set of CVE IDs by N hops for RAG context. 4. (optional) centrality_scores() — PageRank via GDS for ranked context. Run as CLI to do the bulk load: python -m src.constructors.neo4j_graph_service --bulk-load python -m src.constructors.neo4j_graph_service --similar CVE-2021-44228 python -m src.constructors.neo4j_graph_service --stats """ from __future__ import annotations import argparse import json import logging import sys from pathlib import Path from typing import Any, Dict, List, Optional, Tuple from neo4j import GraphDatabase, Session project_root = Path(__file__).parent.parent.parent sys.path.insert(0, str(project_root)) from config import Config from src.generators.rag_config import NEO4J_URI, NEO4J_USER, NEO4J_PASSWORD logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") logger = logging.getLogger(__name__) _BATCH = 10_000 # rows per Neo4j transaction class Neo4jGraphService: """ Bulk-load KG JSON → Neo4j and expose graph query helpers. Connects on construction; call .close() when done. """ def __init__( self, uri: str = NEO4J_URI, user: str = NEO4J_USER, pwd: str = NEO4J_PASSWORD, ) -> None: self.driver = GraphDatabase.driver(uri, auth=(user, pwd)) self.config = Config() self.kg_dir = self.config.knowledge_base_dir / "knowledge_graph" def close(self) -> None: self.driver.close() def __enter__(self) -> "Neo4jGraphService": return self def __exit__(self, *_: Any) -> None: self.close() # ── schema ──────────────────────────────────────────────────────────────── def create_constraints(self) -> None: """Unique constraints guarantee idempotent MERGE.""" constraints = [ ("CVE", "id"), ("Product", "name"), ("Vendor", "name"), ("CWE", "id"), ("CAPEC", "id"), ("Technique", "id"), ("Tactic", "id"), ] with self.driver.session() as s: for label, prop in constraints: try: s.run( f"CREATE CONSTRAINT IF NOT EXISTS " f"FOR (n:{label}) REQUIRE n.{prop} IS UNIQUE" ) except Exception as e: logger.warning(f"Constraint {label}.{prop}: {e}") logger.info("Constraints ensured.") # ── bulk loader ─────────────────────────────────────────────────────────── def bulk_load(self) -> None: """Load all JSON KG files into Neo4j. Idempotent (uses MERGE).""" logger.info("Starting Neo4j bulk load …") self.create_constraints() self._load_cve_nodes() self._load_product_nodes() self._load_vendor_nodes() self._load_cwe_nodes() self._load_capec_nodes() self._load_technique_nodes() self._load_tactic_nodes() self._load_rels("cve_cwe_relationships.json", self._upsert_cve_cwe) self._load_rels("cve_product_relationships.json", self._upsert_cve_product) self._load_rels("cve_capec_relationships.json", self._upsert_cve_capec) self._load_rels("cve_mitre_technique_relationships.json",self._upsert_cve_technique) self._load_rels("cve_mitre_tactic_relationships.json", self._upsert_cve_tactic) self._load_rels("product_vendor_relationships.json", self._upsert_product_vendor) logger.info("Bulk load complete.") self._log_counts() # ── node loaders ────────────────────────────────────────────────────────── def _load_cve_nodes(self) -> None: data = self._read_json("cves_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} CVE nodes …") cypher = """ UNWIND $rows AS r MERGE (c:CVE {id: r.id}) SET c.title = r.title, c.description = r.description, c.source = r.source, c.published_date = r.published_date, c.last_modified = r.last_modified_date, c.cvss_v3_score = r.cvss_v3_score, c.cvss_v3_severity = r.cvss_v3_severity, c.cvss_v3_vector = r.cvss_v3_vector, c.attack_vector = r.attack_vector, c.attack_complexity = r.attack_complexity, c.privileges_required = r.privileges_required, c.user_interaction = r.user_interaction, c.scope = r.scope, c.conf_impact = r.conf_impact, c.integ_impact = r.integ_impact, c.avail_impact = r.avail_impact, c.cvss_v2_score = r.cvss_v2_score, c.cvss_v2_vector = r.cvss_v2_vector, c.is_in_kev = r.is_in_kev, c.exploitdb_count = r.exploitdb_count, c.tags = r.tags """ def _norm(r: Dict[str, Any]) -> Dict[str, Any]: cvss3 = r.get("cvss_v3") or {} cvss2 = r.get("cvss_v2") or {} # Use prose description (first line of content if available) raw_desc = r.get("content", r.get("description", "")) or "" prose = raw_desc.split("\n")[0].strip() # Build a real title from the first sentence of the description title = prose[:120] if prose else r.get("id", "") return { "id": r.get("id", ""), "title": title, "description": prose, "source": r.get("source", ""), "published_date": r.get("published_date", ""), "last_modified_date":r.get("last_modified_date", ""), "cvss_v3_score": cvss3.get("base_score"), "cvss_v3_severity": cvss3.get("base_severity", ""), "cvss_v3_vector": cvss3.get("vector_string", ""), "attack_vector": cvss3.get("attack_vector", ""), "attack_complexity": cvss3.get("attack_complexity", ""), "privileges_required": cvss3.get("privileges_required", ""), "user_interaction": cvss3.get("user_interaction", ""), "scope": cvss3.get("scope", ""), "conf_impact": cvss3.get("confidentiality_impact", ""), "integ_impact": cvss3.get("integrity_impact", ""), "avail_impact": cvss3.get("availability_impact", ""), "cvss_v2_score": cvss2.get("base_score"), "cvss_v2_vector": cvss2.get("vector_string", ""), "is_in_kev": bool(r.get("is_in_kev", False)), "exploitdb_count": r.get("exploitdb_correlations_count", 0) or 0, "tags": r.get("tags") or [], } self._batch_write(cypher, [_norm(r) for r in rows]) def _load_product_nodes(self) -> None: data = self._read_json("products_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} Product nodes …") cypher = """ UNWIND $rows AS r MERGE (p:Product {name: r.name}) SET p.vendor = r.vendor, p.display_name = r.display_name, p.category = r.category, p.criticality_score = r.criticality_score """ self._batch_write(cypher, rows) def _load_vendor_nodes(self) -> None: data = self._read_json("vendors_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} Vendor nodes …") cypher = """ UNWIND $rows AS r MERGE (v:Vendor {name: r.name}) """ # vendors_nodes may store as {vendor_name: {name:..., ...}} norm_rows = [] for r in rows: norm_rows.append({"name": r.get("name", r.get("vendor", ""))}) self._batch_write(cypher, norm_rows) def _load_cwe_nodes(self) -> None: data = self._read_json("cwes_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} CWE nodes …") # Enrich with real names + descriptions from cwe_chunks.json if available cwe_enrichment: Dict[str, Dict[str, str]] = {} cwe_chunks_path = ( self.config.knowledge_base_dir / "rag_exports" / "cwe_chunks.json" ) if cwe_chunks_path.exists(): try: with open(cwe_chunks_path, encoding="utf-8") as f: cwe_chunks = json.load(f) for c in cwe_chunks: p = c.get("payload", {}) cid = p.get("cwe_id", "") if cid: cwe_enrichment[cid] = { "name": p.get("name", ""), "description": c.get("text", "")[:500], } logger.info(f" CWE enrichment loaded: {len(cwe_enrichment)} entries") except Exception as e: logger.warning(f" Could not load CWE enrichment: {e}") cypher = """ UNWIND $rows AS r MERGE (w:CWE {id: r.id}) SET w.name = r.name, w.description = r.description, w.vuln_count = r.vulnerability_count """ def _norm(r: Dict[str, Any]) -> Dict[str, Any]: cid = r.get("id", "") enriched = cwe_enrichment.get(cid, {}) raw_name = r.get("name", "") # Strip verbose prefix "Common Weakness Enumeration CWE-XXX" → real name clean_name = ( enriched.get("name") or raw_name.replace("Common Weakness Enumeration ", "").strip() or cid ) return { "id": cid, "name": clean_name, "description": enriched.get("description", ""), "vulnerability_count": r.get("vulnerability_count", 0), } self._batch_write(cypher, [_norm(r) for r in rows]) def _load_capec_nodes(self) -> None: data = self._read_json("capecs_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} CAPEC nodes …") cypher = """ UNWIND $rows AS r MERGE (a:CAPEC {id: r.id}) SET a.name = r.name """ self._batch_write(cypher, rows) def _load_technique_nodes(self) -> None: data = self._read_json("mitre_techniques_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} Technique nodes …") # Load real names + descriptions from CTI technique JSON files cti_dir = self.config.cti_docs_dir / "attack_techniques" technique_enrichment: Dict[str, Dict[str, str]] = {} if cti_dir.exists(): for jf in cti_dir.glob("*.json"): try: with open(jf, encoding="utf-8") as f: doc = json.load(f) tid = doc.get("id", "") if tid: technique_enrichment[tid] = { "name": doc.get("title", ""), "description": (doc.get("content") or "")[:400], "tactics": ", ".join(doc.get("tactics", [])), } except Exception: pass logger.info(f" Technique enrichment loaded: {len(technique_enrichment)} entries") cypher = """ UNWIND $rows AS r MERGE (t:Technique {id: r.id}) SET t.name = r.name, t.description = r.description, t.tactics = r.tactics, t.vuln_count = r.vulnerability_count """ def _norm(r: Dict[str, Any]) -> Dict[str, Any]: tid = r.get("id", "") enriched = technique_enrichment.get(tid, {}) raw_name = r.get("name", r.get("title", "")) clean_name = ( enriched.get("name") or raw_name.replace("MITRE ATT&CK Technique ", "").strip() or tid ) return { "id": tid, "name": clean_name, "description": enriched.get("description", ""), "tactics": enriched.get("tactics", ""), "vulnerability_count": r.get("vulnerability_count", 0), } self._batch_write(cypher, [_norm(r) for r in rows]) def _load_tactic_nodes(self) -> None: data = self._read_json("mitre_tactics_nodes.json") rows = list(data.values()) if isinstance(data, dict) else data logger.info(f"Loading {len(rows):,} Tactic nodes …") cypher = """ UNWIND $rows AS r MERGE (t:Tactic {id: r.id}) SET t.name = r.name, t.vuln_count = r.vulnerability_count """ def _norm(r: Dict[str, Any]) -> Dict[str, Any]: raw_name = r.get("name", r.get("title", "")) # Strip verbose prefix "MITRE ATT&CK Tactic TXXX" → real name clean_name = raw_name.replace("MITRE ATT&CK Tactic ", "").strip() or r.get("id", "") return { "id": r.get("id", ""), "name": clean_name, "vulnerability_count": r.get("vulnerability_count", 0), } self._batch_write(cypher, [_norm(r) for r in rows]) # ── relationship loaders ────────────────────────────────────────────────── def _load_rels(self, filename: str, handler) -> None: path = self.kg_dir / filename if not path.exists(): logger.warning(f"Relationship file not found: {filename}") return with open(path, encoding="utf-8") as f: rows = json.load(f) logger.info(f"Loading {len(rows):,} {filename} …") handler(rows) def _upsert_cve_cwe(self, rows: List[Dict[str, Any]]) -> None: cypher = """ UNWIND $rows AS r MATCH (c:CVE {id: r.cve_id}), (w:CWE {id: r.cwe_id}) MERGE (c)-[:HAS_WEAKNESS]->(w) """ self._batch_write(cypher, rows) def _upsert_cve_product(self, rows: List[Dict[str, Any]]) -> None: cypher = """ UNWIND $rows AS r MATCH (c:CVE {id: r.cve_id}), (p:Product {name: r.product_name}) MERGE (c)-[:AFFECTS]->(p) """ self._batch_write(cypher, rows) def _upsert_cve_capec(self, rows: List[Dict[str, Any]]) -> None: cypher = """ UNWIND $rows AS r MATCH (c:CVE {id: r.cve_id}), (a:CAPEC {id: r.capec_id}) MERGE (c)-[:USES_PATTERN]->(a) """ norm = [{"cve_id": r.get("cve_id", ""), "capec_id": r.get("capec_id", "")} for r in rows] self._batch_write(cypher, norm) def _upsert_cve_technique(self, rows: List[Dict[str, Any]]) -> None: cypher = """ UNWIND $rows AS r MATCH (c:CVE {id: r.cve_id}), (t:Technique {id: r.technique_id}) MERGE (c)-[:IMPLEMENTS_TECHNIQUE]->(t) """ norm = [{"cve_id": r.get("cve_id", ""), "technique_id": r.get("technique_id", "")} for r in rows] self._batch_write(cypher, norm) def _upsert_cve_tactic(self, rows: List[Dict[str, Any]]) -> None: cypher = """ UNWIND $rows AS r MATCH (c:CVE {id: r.cve_id}), (t:Tactic {id: r.tactic_id}) MERGE (c)-[:MAPPED_TO_TACTIC]->(t) """ norm = [{"cve_id": r.get("cve_id", ""), "tactic_id": r.get("tactic_id", "")} for r in rows] self._batch_write(cypher, norm) def _upsert_product_vendor(self, rows: List[Dict[str, Any]]) -> None: cypher = """ UNWIND $rows AS r MATCH (p:Product {name: r.product_name}), (v:Vendor {name: r.vendor_name}) MERGE (p)-[:MANUFACTURED_BY]->(v) """ norm = [{"product_name": r.get("product_name", r.get("product", "")), "vendor_name": r.get("vendor_name", r.get("vendor", ""))} for r in rows] self._batch_write(cypher, norm) # ── query API ───────────────────────────────────────────────────────────── def similar_cves(self, cve_id: str, k: int = 10) -> List[Dict[str, Any]]: """ Find CVEs related to cve_id by shared CWE, product, or tactic. Returns list of {cve_id, shared_type, score}. """ cypher = """ MATCH (src:CVE {id: $cve_id}) CALL { WITH src MATCH (src)-[:HAS_WEAKNESS]->(w:CWE)<-[:HAS_WEAKNESS]-(other:CVE) WHERE other.id <> $cve_id RETURN other.id AS cve_id, 'cwe' AS shared_type, count(w) AS cnt UNION WITH src MATCH (src)-[:AFFECTS]->(p:Product)<-[:AFFECTS]-(other:CVE) WHERE other.id <> $cve_id RETURN other.id AS cve_id, 'product' AS shared_type, count(p) AS cnt UNION WITH src MATCH (src)-[:MAPPED_TO_TACTIC]->(t:Tactic)<-[:MAPPED_TO_TACTIC]-(other:CVE) WHERE other.id <> $cve_id RETURN other.id AS cve_id, 'tactic' AS shared_type, count(t) AS cnt } RETURN cve_id, shared_type, sum(cnt) AS score ORDER BY score DESC LIMIT $k """ with self.driver.session() as s: result = s.run(cypher, cve_id=cve_id, k=k) return [{"cve_id": r["cve_id"], "shared_type": r["shared_type"], "score": r["score"]} for r in result] def subgraph_for_cves(self, cve_ids: List[str], hops: int = 1) -> Dict[str, Any]: """Backward-compat wrapper — seed subgraph from CVE IDs.""" return self.subgraph_from_nodes( [{"label": "CVE", "id": cid} for cid in cve_ids], hops=hops ) # ── label-agnostic KG API ───────────────────────────────────────────────── _LABEL_KEY: Dict[str, str] = { "CVE": "id", "CWE": "id", "CAPEC": "id", "Technique": "id", "Tactic": "id", "Product": "name", "Vendor": "name", } _LABEL_TO_CVE_REL: Dict[str, Optional[str]] = { "CWE": "HAS_WEAKNESS", "CAPEC": "USES_PATTERN", "Technique": "IMPLEMENTS_TECHNIQUE", "Tactic": "MAPPED_TO_TACTIC", "Product": "AFFECTS", "Vendor": None, # handled via Product hop } def lookup_by_label(self, label: str, query: str, k: int = 5) -> List[Dict[str, Any]]: """ Fuzzy + exact match a node by label. Returns [{id, name, props}]. Label must be in _LABEL_KEY whitelist. """ if label not in self._LABEL_KEY: logger.warning("lookup_by_label: unknown label %r", label) return [] key = self._LABEL_KEY[label] cypher = f""" MATCH (n:{label}) WHERE toLower(n.{key}) = toLower($q) OR toLower(n.{key}) CONTAINS toLower($q) RETURN coalesce(n.id, n.name) AS id, coalesce(n.name, n.id) AS name, properties(n) AS props LIMIT $k """ with self.driver.session() as s: result = s.run(cypher, q=query, k=k) return [{"id": r["id"], "name": r["name"], "props": dict(r["props"])} for r in result] def cves_for_node(self, label: str, node_id: str, k: int = 10) -> List[Dict[str, Any]]: """ Given a non-CVE seed (Product, CWE, Technique, Tactic, CAPEC, Vendor), return connected CVEs ordered by CVSS score desc. """ if label not in self._LABEL_TO_CVE_REL: return [] key = self._LABEL_KEY.get(label, "id") rel = self._LABEL_TO_CVE_REL[label] if label == "Vendor": cypher = f""" MATCH (v:Vendor)-[:MANUFACTURED_BY]-(p:Product)-[:AFFECTS]-(c:CVE) WHERE v.name = $nid RETURN DISTINCT c.id AS id, c.cvss_v3_score AS cvss, c.description AS desc ORDER BY cvss DESC LIMIT $k """ elif rel: cypher = f""" MATCH (n:{label})-[:{rel}]-(c:CVE) WHERE n.{key} = $nid RETURN c.id AS id, c.cvss_v3_score AS cvss, c.description AS desc ORDER BY cvss DESC LIMIT $k """ else: return [] with self.driver.session() as s: return [ {"id": r["id"], "cvss": r["cvss"], "description": r["desc"]} for r in s.run(cypher, nid=node_id, k=k) ] def subgraph_from_nodes(self, seeds: List[Dict[str, str]], hops: int = 1) -> Dict[str, Any]: """ General subgraph expansion from heterogeneous seeds [{label, id}, ...]. Replaces the CVE-only subgraph_for_cves. Expands each seed label separately and merges results. Label must be in _LABEL_KEY whitelist. """ hops = max(1, int(hops)) by_label: Dict[str, List[str]] = {} for s in seeds: lbl = s.get("label", "") if lbl in self._LABEL_KEY: by_label.setdefault(lbl, []).append(s["id"]) all_nodes: List[Dict] = [] all_edges: List[Dict] = [] with self.driver.session() as session: for label, ids in by_label.items(): key = self._LABEL_KEY[label] cypher = f""" MATCH path = (seed:{label})-[*1..{hops}]-(n) WHERE seed.{key} IN $ids UNWIND nodes(path) AS node UNWIND relationships(path) AS rel RETURN DISTINCT labels(node)[0] AS node_label, coalesce(node.id, node.name) AS node_id, node.name AS node_name, type(rel) AS rel_type, coalesce(startNode(rel).id, startNode(rel).name) AS rel_start, coalesce(endNode(rel).id, endNode(rel).name) AS rel_end LIMIT 500 """ for r in session.run(cypher, ids=ids): all_nodes.append({ "label": r["node_label"], "id": r["node_id"], "name": r["node_name"], }) all_edges.append({ "type": r["rel_type"], "start": r["rel_start"], "end": r["rel_end"], }) # Dedup seen_n: set = set() seen_e: set = set() nodes = [n for n in all_nodes if (n["label"], n["id"]) not in seen_n and not seen_n.add((n["label"], n["id"]))] # type: ignore[func-returns-value] edges = [e for e in all_edges if (e["type"], e["start"], e["end"]) not in seen_e and not seen_e.add((e["type"], e["start"], e["end"]))] # type: ignore[func-returns-value] return {"nodes": nodes, "edges": edges} # ── stats ───────────────────────────────────────────────────────────────── def get_stats(self) -> Dict[str, int]: labels = ["CVE", "Product", "Vendor", "CWE", "CAPEC", "Technique", "Tactic"] stats: Dict[str, int] = {} with self.driver.session() as s: for label in labels: result = s.run(f"MATCH (n:{label}) RETURN count(n) AS cnt") stats[label] = result.single()["cnt"] return stats def _log_counts(self) -> None: stats = self.get_stats() for label, cnt in stats.items(): logger.info(f" {label}: {cnt:,}") # ── internal ────────────────────────────────────────────────────────────── def _read_json(self, filename: str) -> Any: path = self.kg_dir / filename if not path.exists(): logger.warning(f"File not found: {path}") return {} logger.info(f" Reading {filename} ({path.stat().st_size / 1e6:.0f} MB) …") with open(path, encoding="utf-8") as f: return json.load(f) def _batch_write(self, cypher: str, rows: List[Dict[str, Any]]) -> None: total = len(rows) with self.driver.session() as s: for start in range(0, total, _BATCH): batch = rows[start : start + _BATCH] s.run(cypher, rows=batch) if (start + _BATCH) % (10 * _BATCH) == 0: logger.info(f" … {start + _BATCH:,} / {total:,}") # ───────────────────────────────────────────────────────────────────────────── # CLI # ───────────────────────────────────────────────────────────────────────────── if __name__ == "__main__": parser = argparse.ArgumentParser(description="Neo4j Graph Service") parser.add_argument("--bulk-load", action="store_true", help="Load KG JSON → Neo4j") parser.add_argument("--similar", type=str, help="Find CVEs similar to given CVE-ID") parser.add_argument("--k", type=int, default=10) parser.add_argument("--stats", action="store_true") args = parser.parse_args() with Neo4jGraphService() as svc: if args.bulk_load: svc.bulk_load() elif args.similar: results = svc.similar_cves(args.similar, k=args.k) print(f"\nCVEs similar to {args.similar}:") for r in results: print(f" {r['cve_id']:25s} ({r['shared_type']:10s}) score={r['score']}") elif args.stats: stats = svc.get_stats() print("\nNeo4j node counts:") for label, cnt in stats.items(): print(f" {label:12s}: {cnt:,}") else: parser.print_help()