| """ |
| In-process cheat sheet: CWE ↔ CAPEC ↔ MITRE ATT&CK taxonomy. |
| |
| Loaded once at startup from the existing on-disk JSON files. All public lookups |
| are O(1) dict access. Fuzzy CWE-name matching uses rapidfuzz (WRatio scorer); |
| falls back to substring match if rapidfuzz is unavailable. |
| |
| Sources: |
| data/CTI/raw/cwe_capec_mitre_mapping.json — CWE → {capecs, mitre_techniques} |
| data/CTI/docs/attack_mappings.json — tactic ↔ technique taxonomy |
| data/knowledge_base/rag_exports/cwe_chunks.json — CWE human-readable names |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import logging |
| import re |
| from pathlib import Path |
| from typing import Optional |
|
|
| logger = logging.getLogger(__name__) |
|
|
| _RE_CVE = re.compile(r"\bCVE-\d{4}-\d{4,}\b", re.I) |
| _RE_CWE = re.compile(r"\bCWE[-\s]?(\d+)\b", re.I) |
| _RE_CAPEC = re.compile(r"\bCAPEC[-\s]?(\d+)\b", re.I) |
| _RE_TECH = re.compile(r"\bT(\d{4}(?:\.\d{3})?)\b") |
| _RE_TAC = re.compile(r"\bTA(\d{4})\b") |
|
|
| _FUZZY_SCORE_CUTOFF = 90 |
| _FUZZY_TOP_K = 3 |
|
|
|
|
| class CheatSheet: |
| """ |
| In-memory CWE/CAPEC/MITRE taxonomy with rapidfuzz fuzzy CWE-name matching. |
| |
| Never instantiate directly — use init_cheat_sheet() / get_cheat_sheet(). |
| """ |
|
|
| def __init__(self) -> None: |
| |
| self.cwe_map: dict[str, dict] = {} |
| |
| self.tactic_to_techs: dict[str, list[str]] = {} |
| |
| self.tech_to_tactics: dict[str, list[str]] = {} |
| |
| self.tactic_name_to_id: dict[str, str] = {} |
| |
| self.cwe_names: dict[str, str] = {} |
| |
| self._name_to_cwe: dict[str, str] = {} |
| self._fuzzy_available = False |
|
|
| |
|
|
| def load(self, project_root: Path) -> "CheatSheet": |
| self._load_cwe_map(project_root / "data/CTI/raw/cwe_capec_mitre_mapping.json") |
| self._load_attack_mappings(project_root / "data/CTI/docs/attack_mappings.json") |
| self._load_cwe_names(project_root / "data/knowledge_base/rag_exports/cwe_chunks.json") |
| self._try_import_rapidfuzz() |
| logger.info( |
| "CheatSheet loaded: %d CWEs, %d tactics, %d techniques, %d CWE names, fuzzy=%s", |
| len(self.cwe_map), len(self.tactic_to_techs), len(self.tech_to_tactics), |
| len(self.cwe_names), self._fuzzy_available, |
| ) |
| return self |
|
|
| def _load_cwe_map(self, path: Path) -> None: |
| if not path.exists(): |
| logger.warning("cwe_capec_mitre_mapping.json not found at %s", path) |
| return |
| raw: dict = json.loads(path.read_text()) |
| |
| for k, v in raw.items(): |
| cid = k if k.upper().startswith("CWE-") else f"CWE-{k}" |
| self.cwe_map[cid.upper()] = v |
|
|
| def _load_attack_mappings(self, path: Path) -> None: |
| if not path.exists(): |
| logger.warning("attack_mappings.json not found at %s", path) |
| return |
| data = json.loads(path.read_text()) |
| self.tactic_to_techs = {k.upper(): v for k, v in data.get("tactic_to_techniques", {}).items()} |
| self.tech_to_tactics = {k.upper(): v for k, v in data.get("technique_to_tactics", {}).items()} |
| self.tactic_name_to_id = {k.lower(): v.upper() |
| for k, v in data.get("tactic_name_to_id", {}).items()} |
|
|
| def _load_cwe_names(self, path: Path) -> None: |
| if not path.exists(): |
| logger.warning("cwe_chunks.json not found at %s", path) |
| return |
| chunks: list = json.loads(path.read_text()) |
| for c in chunks: |
| p = c.get("payload", {}) |
| cid = p.get("cwe_id", "") |
| name = p.get("name", "") |
| if cid and name: |
| self.cwe_names[cid.upper()] = name |
| self._name_to_cwe[name.lower()] = cid.upper() |
|
|
| def _try_import_rapidfuzz(self) -> None: |
| try: |
| import rapidfuzz |
| self._fuzzy_available = True |
| except ImportError: |
| logger.warning("rapidfuzz not available — falling back to substring CWE matching") |
|
|
| |
|
|
| def lookup_techniques_for_cwe(self, cwe_id: str) -> list[str]: |
| return self.cwe_map.get(cwe_id.upper(), {}).get("mitre_techniques", []) |
|
|
| def lookup_capecs_for_cwe(self, cwe_id: str) -> list[str]: |
| return self.cwe_map.get(cwe_id.upper(), {}).get("capecs", []) |
|
|
| def lookup_techniques_for_tactic(self, tactic_id: str) -> list[str]: |
| return self.tactic_to_techs.get(tactic_id.upper(), []) |
|
|
| def lookup_tactics_for_technique(self, tech_id: str) -> list[str]: |
| return self.tech_to_tactics.get(tech_id.upper(), []) |
|
|
| def cwe_name(self, cwe_id: str) -> str: |
| return self.cwe_names.get(cwe_id.upper(), "") |
|
|
| |
|
|
| def fuzzy_match_cwe( |
| self, |
| query: str, |
| k: int = _FUZZY_TOP_K, |
| score_cutoff: int = _FUZZY_SCORE_CUTOFF, |
| ) -> list[dict]: |
| """ |
| Match CWE names against arbitrary query text using rapidfuzz WRatio. |
| |
| Returns [{"cwe_id": "CWE-79", "name": "...", "score": 92.3}, ...] |
| sorted by score desc. Falls back to substring match when rapidfuzz |
| is unavailable. |
| """ |
| if not self._name_to_cwe: |
| return [] |
|
|
| query_lower = query.lower() |
|
|
| if self._fuzzy_available: |
| from rapidfuzz import process as fz_process, fuzz |
|
|
| matches = fz_process.extract( |
| query_lower, |
| self._name_to_cwe.keys(), |
| scorer=fuzz.partial_ratio, |
| limit=k, |
| score_cutoff=score_cutoff, |
| ) |
| return [ |
| {"cwe_id": self._name_to_cwe[m[0]], "name": m[0], "score": m[1]} |
| for m in matches |
| ] |
|
|
| |
| results = [] |
| for name, cid in self._name_to_cwe.items(): |
| if len(name) >= 5 and name in query_lower: |
| results.append({"cwe_id": cid, "name": name, "score": 75.0}) |
| if len(results) >= k: |
| break |
| return results |
|
|
| |
|
|
| def entity_to_hints(self, text: str, max_items: int = 6) -> dict: |
| """ |
| NER-lite + fuzzy matching over arbitrary user query text. |
| |
| Returns dict with keys: cves, cwes, capecs, techniques, tactics, name_hits. |
| name_hits is a list of {"cwe_id", "name", "score"} from fuzzy CWE matching. |
| """ |
| if not text: |
| return {"cves": [], "cwes": [], "capecs": [], "techniques": [], "tactics": [], "name_hits": []} |
|
|
| cves = list(dict.fromkeys(_RE_CVE.findall(text)))[:max_items] |
| cwes = [f"CWE-{n}" for n in dict.fromkeys(_RE_CWE.findall(text))][:max_items] |
| capecs = [f"CAPEC-{n}" for n in dict.fromkeys(_RE_CAPEC.findall(text))][:max_items] |
| techniques = [f"T{n}" for n in dict.fromkeys(_RE_TECH.findall(text))][:max_items] |
| tactics = [f"TA{n}" for n in dict.fromkeys(_RE_TAC.findall(text))][:max_items] |
|
|
| |
| name_hits = self._fuzzy_match_windows(text, k=max_items) |
|
|
| return { |
| "cves": cves, |
| "cwes": cwes, |
| "capecs": capecs, |
| "techniques": techniques, |
| "tactics": tactics, |
| "name_hits": name_hits, |
| } |
|
|
| def _fuzzy_match_windows(self, text: str, k: int = 3) -> list[dict]: |
| """ |
| Slide a 2-5-word window over text and fuzzy-match each window against |
| CWE names. Deduplicates by cwe_id, keeps highest score per CWE. |
| """ |
| words = re.sub(r"[^\w\s]", " ", text.lower()).split() |
| seen: dict[str, dict] = {} |
| for size in range(2, 6): |
| for i in range(len(words) - size + 1): |
| window = " ".join(words[i : i + size]) |
| for hit in self.fuzzy_match_cwe(window, k=k): |
| cid = hit["cwe_id"] |
| if cid not in seen or hit["score"] > seen[cid]["score"]: |
| seen[cid] = hit |
| |
| return sorted(seen.values(), key=lambda h: h["score"], reverse=True)[:k] |
|
|
| |
|
|
| def render_hint_block(self, hints: dict, max_cwes: int = 3, max_techs_per_cwe: int = 4) -> str: |
| """ |
| Compact hint block for injection into rewriter / translate-symptom prompts. |
| |
| Hard-capped to avoid prompt bloat (<400 chars target). |
| """ |
| lines: list[str] = [] |
| seen_cwes: set[str] = set() |
|
|
| |
| for cwe in hints.get("cwes", [])[:max_cwes]: |
| self._append_cwe_line(cwe, lines, seen_cwes, max_techs_per_cwe) |
|
|
| |
| for hit in hints.get("name_hits", []): |
| if len(seen_cwes) >= max_cwes: |
| break |
| self._append_cwe_line(hit["cwe_id"], lines, seen_cwes, max_techs_per_cwe) |
|
|
| |
| for tech in hints.get("techniques", [])[:4]: |
| tacs = self.lookup_tactics_for_technique(tech)[:2] |
| if tacs: |
| lines.append(f" {tech}: tactics={tacs}") |
|
|
| if not lines: |
| return "" |
| return "KG taxonomy hints:\n" + "\n".join(lines) |
|
|
| def _append_cwe_line( |
| self, |
| cwe: str, |
| lines: list[str], |
| seen: set[str], |
| max_techs: int, |
| ) -> None: |
| if cwe in seen: |
| return |
| seen.add(cwe) |
| nm = self.cwe_names.get(cwe, "") |
| techs = self.lookup_techniques_for_cwe(cwe)[:max_techs] |
| capecs = self.lookup_capecs_for_cwe(cwe)[:3] |
| parts = [] |
| if techs: |
| parts.append(f"techniques={techs}") |
| if capecs: |
| parts.append(f"capecs={capecs}") |
| if parts: |
| label = f"{cwe}({nm})" if nm else cwe |
| lines.append(f" {label}: {', '.join(parts)}") |
|
|
|
|
| |
|
|
| _singleton: Optional[CheatSheet] = None |
|
|
|
|
| def init_cheat_sheet(project_root: Path) -> CheatSheet: |
| """Load and cache the global CheatSheet singleton.""" |
| global _singleton |
| _singleton = CheatSheet().load(Path(project_root)) |
| return _singleton |
|
|
|
|
| def get_cheat_sheet() -> Optional[CheatSheet]: |
| """Return the loaded CheatSheet, or None if init_cheat_sheet was never called.""" |
| return _singleton |
|
|