cve-kgrag-db / code /src /generators /chunkers.py
DuyTa's picture
Add code/: full CVE-KGRAG project source snapshot
27f6252 verified
Raw
History Blame Contribute Delete
12.9 kB
"""
Structure-aware chunkers for CVE, MITRE ATT&CK, CAPEC, and CWE documents.
Each chunker produces a list of dicts:
{
"id": str — deterministic, stable chunk ID
"kind": str — chunk section name
"text": str — text to embed / index
"payload": dict — Qdrant payload (filterable metadata)
}
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Set
# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────
def _join(*parts: Optional[str], sep: str = " | ") -> str:
return sep.join(p for p in parts if p)
def _list_str(val: Any) -> List[str]:
if isinstance(val, list):
return [str(v) for v in val if v]
if isinstance(val, str) and val:
return [val]
return []
def _base_payload(cve_doc: Dict[str, Any]) -> Dict[str, Any]:
"""Shared metadata carried by every CVE chunk for Qdrant payload filtering."""
cve_id_val = cve_doc.get("id") or cve_doc.get("cve_id", "")
cvss3 = cve_doc.get("cvss_v3") or {}
year = ""
pub = cve_doc.get("published_date", "")
if pub:
year = pub[:4]
return {
"cve_id": cve_id_val,
"severity": cvss3.get("base_severity", ""),
"cvss_score": cvss3.get("base_score"),
"is_in_kev": bool(cve_doc.get("is_in_kev", False)),
"year": year,
"products": _list_str(cve_doc.get("affected_products", [])),
"cwe_refs": _list_str(cve_doc.get("cwe_refs", [])),
"capec_entries": _list_str(cve_doc.get("capec_entries", [])),
"mitre_techniques": _list_str(cve_doc.get("mitre_techniques", [])),
"mitre_tactics": _list_str(cve_doc.get("mitre_tactics", [])),
}
# ─────────────────────────────────────────────────────────────────────────────
# CVEChunker
# ─────────────────────────────────────────────────────────────────────────────
class CVEChunker:
"""
Produces 1-2 self-contained chunks per CVE.
Chunk 1 — ``core``: vulnerability prose + CVSS metrics.
Best for semantic queries about *what* the vuln is
and exact CVE-ID lexical lookup.
Chunk 2 — ``context`` (omitted when empty):
Affected products/vendors + CWE/CAPEC + MITRE ATT&CK
+ KEV status + tags. Best for *who is affected* and
threat-hunting queries.
Both chunks carry the full payload so Qdrant payload filters work uniformly.
"""
def chunk(self, doc: Dict[str, Any]) -> List[Dict[str, Any]]:
cve_id = doc.get("id") or doc.get("cve_id", "unknown")
payload = _base_payload(doc)
chunks: List[Dict[str, Any]] = []
core_text = self._core(doc)
if core_text:
chunks.append({
"id": f"{cve_id}::core",
"kind": "core",
"text": core_text,
"payload": {**payload, "chunk_kind": "core"},
})
ctx_text = self._context(doc)
if ctx_text:
chunks.append({
"id": f"{cve_id}::context",
"kind": "context",
"text": ctx_text,
"payload": {**payload, "chunk_kind": "context"},
})
return chunks
# ── section builders ─────────────────────────────────────────────────────
def _core(self, doc: Dict[str, Any]) -> str:
"""CVE ID + vulnerability prose + full CVSS metrics."""
cve_id = doc.get("id") or doc.get("cve_id", "")
# Extract prose from content (everything before the first blank CVSS line)
content = (doc.get("content") or "").strip()
prose = content.split("\n")[0].strip() if content else (doc.get("description") or "").strip()
parts = [f"CVE ID: {cve_id}"]
if prose:
parts.append(prose)
pub = doc.get("published_date", "")
if pub:
parts.append(f"Published: {pub[:10]}")
cvss3 = doc.get("cvss_v3") or {}
if cvss3.get("base_score"):
parts.append(
f"CVSS v3: {cvss3['base_score']} {cvss3.get('base_severity', '')} "
f"| Vector: {cvss3.get('vector_string', '')}"
)
metric_parts = []
for label, key in [
("AV", "attack_vector"),
("AC", "attack_complexity"),
("PR", "privileges_required"),
("UI", "user_interaction"),
("S", "scope"),
]:
v = cvss3.get(key, "")
if v:
metric_parts.append(f"{label}:{v}")
if metric_parts:
parts.append(" ".join(metric_parts))
impact_parts = []
for label, key in [("C", "confidentiality_impact"), ("I", "integrity_impact"), ("A", "availability_impact")]:
v = cvss3.get(key, "")
if v:
impact_parts.append(f"{label}:{v}")
if impact_parts:
parts.append("Impact: " + " ".join(impact_parts))
cvss2 = doc.get("cvss_v2") or {}
if cvss2.get("base_score"):
parts.append(f"CVSS v2: {cvss2['base_score']} | {cvss2.get('vector_string', '')}")
return " | ".join(parts)
def _context(self, doc: Dict[str, Any]) -> str:
"""Affected products/vendors + CWE/CAPEC + MITRE + KEV — self-contained threat context."""
cve_id = doc.get("id") or doc.get("cve_id", "")
cvss3 = doc.get("cvss_v3") or {}
parts = [f"CVE ID: {cve_id}"]
sev = cvss3.get("base_severity", "")
if sev:
parts.append(f"Severity: {sev}")
products = _list_str(doc.get("affected_products", []))
if products:
parts.append(f"Affected Products: {', '.join(products[:20])}")
vendors = self._extract_vendors(doc)
if vendors:
parts.append(f"Vendors: {', '.join(sorted(vendors)[:15])}")
cwes = _list_str(doc.get("cwe_refs", []))
if cwes:
parts.append(f"CWE Weaknesses: {', '.join(cwes)}")
capecs = _list_str(doc.get("capec_entries", []))
if capecs:
parts.append(f"CAPEC Attack Patterns: {', '.join(capecs[:10])}")
techs = _list_str(doc.get("mitre_techniques", []))
if techs:
parts.append(f"MITRE ATT&CK Techniques: {', '.join(techs[:15])}")
tactics = _list_str(doc.get("mitre_tactics", []))
if tactics:
parts.append(f"MITRE ATT&CK Tactics: {', '.join(tactics[:10])}")
if doc.get("is_in_kev"):
parts.append("KEV: Known Exploited Vulnerability")
edb = doc.get("exploitdb_correlations_count", 0) or 0
if edb:
parts.append(f"ExploitDB References: {edb}")
tags = _list_str(doc.get("tags", []))
if tags:
parts.append(f"Tags: {', '.join(tags)}")
# Only emit if there is meaningful content beyond CVE ID + severity
if len(parts) <= 2:
return ""
return " | ".join(parts)
def _extract_vendors(self, doc: Dict[str, Any]) -> Set[str]:
vendors: Set[str] = set()
for cfg in doc.get("cpe_configurations") or []:
for match in cfg.get("cpe_match") or []:
uri = match.get("cpe23Uri", "")
segs = uri.split(":")
if len(segs) > 4 and segs[3] not in ("*", "-", ""):
vendors.add(segs[3])
return vendors
# ─────────────────────────────────────────────────────────────────────────────
# MITREChunker
# ─────────────────────────────────────────────────────────────────────────────
class MITREChunker:
"""One chunk per MITRE ATT&CK technique (already compact ~300-500 words)."""
def chunk(self, doc: Dict[str, Any]) -> List[Dict[str, Any]]:
tid = doc.get("id", "")
title = doc.get("title", "")
content= doc.get("content", "")
tactics= doc.get("tactics", [])
tac_ids= doc.get("tactic_ids", [])
text = _join(
f"MITRE ATT&CK Technique: {tid}",
f"Name: {title}",
f"Tactics: {', '.join(tactics)}" if tactics else None,
f"Description: {content}" if content else None,
)
return [{
"id": f"mitre::{tid}",
"kind": "technique",
"text": text,
"payload": {
"technique_id": tid,
"title": title,
"tactics": tactics,
"tactic_ids": tac_ids,
"data_type": "mitre",
},
}]
# ─────────────────────────────────────────────────────────────────────────────
# CAPECChunker
# ─────────────────────────────────────────────────────────────────────────────
class CAPECChunker:
"""One chunk per CAPEC attack pattern."""
def chunk(self, doc: Dict[str, Any]) -> List[Dict[str, Any]]:
cid = doc.get("id", "")
title = doc.get("title", "")
content= doc.get("content", "")
capec_id = f"CAPEC-{cid}" if not str(cid).startswith("CAPEC") else cid
text = _join(
f"CAPEC Attack Pattern: {capec_id}",
f"Name: {title}",
f"Description: {content}" if content else None,
)
return [{
"id": f"capec::{capec_id}",
"kind": "pattern",
"text": text,
"payload": {
"capec_id": capec_id,
"title": title,
"data_type": "capec",
},
}]
# ─────────────────────────────────────────────────────────────────────────────
# CWEChunker
# ─────────────────────────────────────────────────────────────────────────────
class CWEChunker:
"""One chunk per CWE weakness entry (parsed from cwe_latest.xml)."""
def chunk(self, doc: Dict[str, Any]) -> List[Dict[str, Any]]:
cwe_id = doc.get("id", "")
name = doc.get("name", "")
desc = doc.get("description", "")
ext = doc.get("extended_description", "")
conseqs = doc.get("consequences", [])
capecs = doc.get("capec_refs", [])
text_parts = [
f"CWE Weakness: {cwe_id}",
f"Name: {name}",
]
if desc:
text_parts.append(f"Description: {desc}")
if ext:
text_parts.append(f"Extended Description: {ext}")
if conseqs:
text_parts.append(f"Impacts: {', '.join(conseqs)}")
if capecs:
text_parts.append(f"Related CAPEC Patterns: {', '.join(capecs)}")
return [{
"id": f"cwe::{cwe_id}",
"kind": "weakness",
"text": " | ".join(text_parts),
"payload": {
"cwe_id": cwe_id,
"name": name,
"abstraction": doc.get("abstraction", ""),
"capec_refs": capecs,
"data_type": "cwe",
},
}]