File size: 11,861 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 | """
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 # partial_ratio threshold; matches "sql injection" → CWE-89
_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:
# CWE-ID (uppercase, e.g. "CWE-79") → {capecs, mitre_techniques, mitre_description}
self.cwe_map: dict[str, dict] = {}
# TA0001 → [T1190, T1133, ...]
self.tactic_to_techs: dict[str, list[str]] = {}
# T1059 → [TA0002, ...]
self.tech_to_tactics: dict[str, list[str]] = {}
# "collection" → "TA0009"
self.tactic_name_to_id: dict[str, str] = {}
# CWE-79 → "Improper Neutralization of Input During Web Page Generation"
self.cwe_names: dict[str, str] = {}
# lower-name → CWE-ID (for fuzzy / substring matching)
self._name_to_cwe: dict[str, str] = {}
self._fuzzy_available = False
# ── Loaders ──────────────────────────────────────────────────────────────
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())
# Keys may be "CWE-79" or "79" — normalise to "CWE-XX"
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 # noqa: F401
self._fuzzy_available = True
except ImportError:
logger.warning("rapidfuzz not available — falling back to substring CWE matching")
# ── Public lookups (O(1)) ────────────────────────────────────────────────
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(), "")
# ── Fuzzy CWE-name matching ───────────────────────────────────────────────
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
]
# Fallback: substring match
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
# ── Entity extraction from free text ────────────────────────────────────
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]
# Fuzzy match against sliding window of 2-5 words so partial_ratio works
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] = {} # cwe_id → best hit
for size in range(2, 6): # 2-word to 5-word windows
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
# Sort by score desc, return top-k
return sorted(seen.values(), key=lambda h: h["score"], reverse=True)[:k]
# ── Prompt rendering ─────────────────────────────────────────────────────
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()
# Explicit CWE IDs from regex
for cwe in hints.get("cwes", [])[:max_cwes]:
self._append_cwe_line(cwe, lines, seen_cwes, max_techs_per_cwe)
# Fuzzy name hits (if not already covered above)
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)
# Technique → tactic mapping
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 management ──────────────────────────────────────────────────────
_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
|