"""Normalize MITRE CWE XML, CAPEC XML, and ATT&CK STIX 2.1 into CCRB documents and graph edges."""
from __future__ import annotations
import json
import re
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
def _local(tag: str) -> str:
return tag.rsplit("}", 1)[-1] if "}" in tag else tag
def _clean_ws(text: str | None) -> str:
if not text:
return ""
return re.sub(r"\s+", " ", text).strip()
def _elem_text(elem: ET.Element | None) -> str:
if elem is None:
return ""
return _clean_ws("".join(elem.itertext()))
def _code_elem_text(elem: ET.Element) -> str:
"""Extract code snippet text while turning XHTML
/
boundaries into newlines."""
parts: list[str] = []
def _walk(node: ET.Element) -> None:
tag = _local(node.tag).lower()
if tag in {"br", "div", "p", "li"} and parts:
parts.append("\n")
if node.text:
parts.append(node.text)
for child in node:
_walk(child)
if child.tail:
parts.append(child.tail)
_walk(elem)
lines = [line.rstrip() for line in "".join(parts).splitlines()]
# Collapse excessive blank lines while preserving code indentation
out: list[str] = []
blank_run = 0
for line in lines:
if not line.strip():
blank_run += 1
if blank_run <= 1:
out.append("")
else:
blank_run = 0
out.append(line)
return "\n".join(out).strip()
def parse_cwe_xml(
xml_or_zip: Path,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], list[dict[str, str]]]:
"""Parse CWE XML (or .zip containing XML) into CWE docs, remediation docs, code examples, and edges."""
if xml_or_zip.suffix.lower() == ".zip":
with zipfile.ZipFile(xml_or_zip, "r") as zf:
xml_names = [n for n in zf.namelist() if n.lower().endswith(".xml")]
if not xml_names:
raise ValueError(f"No .xml file found inside {xml_or_zip}")
with zf.open(xml_names[0]) as handle:
root = ET.parse(handle).getroot()
else:
root = ET.parse(xml_or_zip).getroot()
cwe_docs: list[dict[str, Any]] = []
remediation_docs: list[dict[str, Any]] = []
code_docs: list[dict[str, Any]] = []
edges: list[dict[str, str]] = []
for elem in root.iter():
if _local(elem.tag) != "Weakness":
continue
status = elem.attrib.get("Status", "")
if status == "Deprecated" or status == "Obsolete":
continue
cwe_num = elem.attrib.get("ID", "").strip()
name = elem.attrib.get("Name", "").strip()
if not cwe_num or not name:
continue
cwe_id = f"CWE-{cwe_num}"
desc_parts: list[str] = []
consequence_parts: list[str] = []
mitigation_idx = 0
example_idx = 0
for child in elem:
tag = _local(child.tag)
if tag in {"Description", "Extended_Description"}:
txt = _elem_text(child)
if txt:
desc_parts.append(txt)
elif tag == "Common_Consequences":
for conseq in child:
txt = _elem_text(conseq)
if txt:
consequence_parts.append(txt)
elif tag == "Related_Weaknesses":
for rel in child:
nature = rel.attrib.get("Nature", "")
target_num = rel.attrib.get("CWE_ID", "").strip()
if target_num and nature:
edges.append(
{
"src": cwe_id,
"rel": f"cwe_{nature.lower()}",
"dst": f"CWE-{target_num}",
}
)
elif tag == "Related_Attack_Patterns":
for capec_ref in child:
capec_num = capec_ref.attrib.get("CAPEC_ID", "").strip()
if capec_num:
edges.append(
{
"src": cwe_id,
"rel": "related_capec",
"dst": f"CAPEC-{capec_num}",
}
)
elif tag == "Potential_Mitigations":
for mit in child:
mit_text = _elem_text(mit)
if len(mit_text) < 25:
continue
mitigation_idx += 1
rem_id = f"rem_cwe_{cwe_num}_{mitigation_idx:02d}"
remediation_docs.append(
{
"document_id": rem_id,
"title": f"Mitigation for {cwe_id}: {name}",
"text": mit_text,
"source": "MITRE CWE",
"track": "remediation",
"source_id": f"{cwe_id}-MIT-{mitigation_idx}",
"license": "MITRE-CWE-TOU",
"url": f"https://cwe.mitre.org/data/definitions/{cwe_num}.html",
}
)
edges.append({"src": cwe_id, "rel": "mitigated_by", "dst": rem_id})
elif tag == "Demonstrative_Examples":
for ex in child:
intro = ""
good_blocks: list[str] = []
bad_blocks: list[str] = []
langs: list[str] = []
for sub in ex:
sub_tag = _local(sub.tag)
if sub_tag == "Intro_Text":
intro = _elem_text(sub)
elif sub_tag == "Example_Code":
lang = sub.attrib.get("Language", "").strip()
nature = sub.attrib.get("Nature", "").strip().lower()
raw_code = _code_elem_text(sub)
if not raw_code:
continue
if lang:
langs.append(lang)
if nature == "bad":
bad_blocks.append(f"[{lang or 'Code'}]\n{raw_code}")
else:
tag_label = nature.title() if nature else "Reference"
good_blocks.append(f"[{tag_label} | {lang or 'Code'}]\n{raw_code}")
if good_blocks or bad_blocks:
example_idx += 1
code_doc_id = None
if good_blocks:
code_doc_id = f"code_cwe_{cwe_num}_{example_idx:02d}"
combined = (f"{intro}\n\n" if intro else "") + "\n\n".join(good_blocks)
code_docs.append(
{
"document_id": code_doc_id,
"title": f"{cwe_id} Secure Reference Code: {name}",
"text": combined,
"source": "MITRE CWE Examples",
"track": "code",
"source_id": f"{cwe_id}-GOOD-{example_idx}",
"license": "MITRE-CWE-TOU",
"language_tags": sorted(set(langs)),
"url": f"https://cwe.mitre.org/data/definitions/{cwe_num}.html",
}
)
edges.append({"src": cwe_id, "rel": "has_good_code", "dst": code_doc_id})
if bad_blocks:
bad_id = f"bad_cwe_{cwe_num}_{example_idx:02d}"
code_docs.append(
{
"document_id": bad_id,
"title": f"{cwe_id} Vulnerable Pattern: {name}",
"text": "\n\n".join(bad_blocks),
"source": "MITRE CWE Examples",
"track": "code_query_seed",
"source_id": f"{cwe_id}-BAD-{example_idx}",
"license": "MITRE-CWE-TOU",
"language_tags": sorted(set(langs)),
"cwe_id": cwe_id,
}
)
edges.append({"src": cwe_id, "rel": "has_bad_code", "dst": bad_id})
if code_doc_id is not None:
edges.append({"src": bad_id, "rel": "paired_good_code", "dst": code_doc_id})
full_text_parts = desc_parts[:]
if consequence_parts:
full_text_parts.append("Common Consequences: " + " | ".join(consequence_parts[:4]))
cwe_docs.append(
{
"document_id": f"cwe_doc_{cwe_num}",
"title": f"{cwe_id}: {name}",
"text": "\n\n".join(full_text_parts) or name,
"source": "MITRE CWE",
"track": "cwe",
"source_id": cwe_id,
"license": "MITRE-CWE-TOU",
"url": f"https://cwe.mitre.org/data/definitions/{cwe_num}.html",
}
)
return cwe_docs, remediation_docs, code_docs, edges
def parse_capec_xml(xml_path: Path) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
"""Parse CAPEC XML into supplementary CWE/ATT&CK distractor docs and CWE/ATT&CK edges."""
root = ET.parse(xml_path).getroot()
capec_docs: list[dict[str, Any]] = []
edges: list[dict[str, str]] = []
for elem in root.iter():
if _local(elem.tag) != "Attack_Pattern":
continue
if elem.attrib.get("Status") in {"Deprecated", "Obsolete"}:
continue
capec_num = elem.attrib.get("ID", "").strip()
name = elem.attrib.get("Name", "").strip()
if not capec_num or not name:
continue
capec_id = f"CAPEC-{capec_num}"
desc_parts: list[str] = []
for child in elem:
tag = _local(child.tag)
if tag in {"Description", "Extended_Description"}:
txt = _elem_text(child)
if txt:
desc_parts.append(txt)
elif tag == "Related_Weaknesses":
for rel in child:
cwe_num = rel.attrib.get("CWE_ID", "").strip()
if cwe_num:
edges.append({"src": capec_id, "rel": "exploits_cwe", "dst": f"CWE-{cwe_num}"})
elif tag == "Taxonomy_Mappings":
for mapping in child:
if mapping.attrib.get("Taxonomy_Name") == "ATTACK":
entry_id = ""
for sub in mapping:
if _local(sub.tag) == "Entry_ID":
entry_id = _elem_text(sub)
if entry_id:
tech_id = entry_id if entry_id.startswith("T") else f"T{entry_id}"
edges.append({"src": capec_id, "rel": "maps_attack", "dst": tech_id})
capec_docs.append(
{
"document_id": f"capec_doc_{capec_num}",
"title": f"{capec_id}: {name}",
"text": "\n\n".join(desc_parts) or name,
"source": "MITRE CAPEC",
"track": "attack",
"source_id": capec_id,
"license": "MITRE-CAPEC-TOU",
"url": f"https://capec.mitre.org/data/definitions/{capec_num}.html",
}
)
return capec_docs, edges
def parse_attack_stix(
stix_paths: list[Path],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, str]]]:
"""Parse MITRE ATT&CK STIX 2.1 bundles into ATT&CK docs, mitigation docs, and graph edges."""
attack_docs: list[dict[str, Any]] = []
remediation_docs: list[dict[str, Any]] = []
edges: list[dict[str, str]] = []
stix_to_ext_id: dict[str, str] = {}
seen_attack_ids: set[str] = set()
seen_rem_ids: set[str] = set()
raw_relationships: list[dict[str, Any]] = []
for stix_path in stix_paths:
bundle = json.loads(stix_path.read_text(encoding="utf-8"))
for obj in bundle.get("objects", []):
if obj.get("revoked") or obj.get("x_mitre_deprecated"):
continue
obj_type = obj.get("type")
ext_id = ""
ext_url = ""
for ref in obj.get("external_references", []):
if ref.get("source_name") == "mitre-attack" and ref.get("external_id"):
ext_id = str(ref["external_id"]).strip()
ext_url = str(ref.get("url", ""))
break
if obj_type == "attack-pattern" and ext_id:
stix_to_ext_id[obj["id"]] = ext_id
if ext_id in seen_attack_ids:
continue
seen_attack_ids.add(ext_id)
tactics = [
p.get("phase_name", "")
for p in obj.get("kill_chain_phases", [])
if p.get("phase_name")
]
platforms = obj.get("x_mitre_platforms", [])
detection = _clean_ws(obj.get("x_mitre_detection", ""))
body_parts = [_clean_ws(obj.get("description", ""))]
if tactics:
body_parts.append("Tactics: " + ", ".join(tactics))
if platforms:
body_parts.append("Platforms: " + ", ".join(platforms))
if detection:
body_parts.append("Detection: " + detection)
attack_docs.append(
{
"document_id": f"attack_doc_{ext_id.replace('.', '_')}",
"title": f"{ext_id}: {obj.get('name', ext_id)}",
"text": "\n\n".join(p for p in body_parts if p),
"source": "MITRE ATT&CK",
"track": "attack",
"source_id": ext_id,
"license": "Apache-2.0",
"url": ext_url,
}
)
elif obj_type == "course-of-action" and ext_id:
doc_id = f"rem_attack_{ext_id}"
stix_to_ext_id[obj["id"]] = doc_id
if ext_id in seen_rem_ids:
continue
seen_rem_ids.add(ext_id)
remediation_docs.append(
{
"document_id": doc_id,
"title": f"{ext_id}: {obj.get('name', ext_id)}",
"text": _clean_ws(obj.get("description", "")) or str(obj.get("name", "")),
"source": "MITRE ATT&CK Mitigations",
"track": "remediation",
"source_id": ext_id,
"license": "Apache-2.0",
"url": ext_url,
}
)
elif obj_type == "relationship":
raw_relationships.append(obj)
for rel_obj in raw_relationships:
rel_type = rel_obj.get("relationship_type")
src_ext = stix_to_ext_id.get(rel_obj.get("source_ref", ""))
dst_ext = stix_to_ext_id.get(rel_obj.get("target_ref", ""))
if not src_ext or not dst_ext:
continue
if rel_type in {"mitigates", "subtechnique-of"}:
edges.append({"src": src_ext, "rel": rel_type.replace("-", "_"), "dst": dst_ext})
return attack_docs, remediation_docs, edges