File size: 12,895 Bytes
27f6252 | 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | """
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",
},
}]
|