File size: 15,997 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""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 <br>/<div> 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