File size: 3,051 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
"""
Parse data/CTI/raw/cwe_latest.xml into per-CWE Python dicts ready for chunking.
"""

import xml.etree.ElementTree as ET
from pathlib import Path
from typing import List, Dict, Any
import sys

project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))
from config import Config

_NS = "{http://cwe.mitre.org/cwe-7}"


def _text(el, tag: str) -> str:
    child = el.find(_NS + tag)
    if child is None:
        return ""
    parts = []
    if child.text:
        parts.append(child.text.strip())
    # Some extended-description fields have nested <p> or <xhtml:p>
    for sub in child:
        t = (sub.text or "").strip() + (sub.tail or "").strip()
        if t:
            parts.append(t)
    return " ".join(parts).strip()


def _list_text(el, container_tag: str, item_tag: str, attrib: str = "Nature") -> List[str]:
    container = el.find(_NS + container_tag)
    if container is None:
        return []
    return [
        item.get(attrib, "")
        for item in container.findall(_NS + item_tag)
        if item.get(attrib)
    ]


def parse_cwe_xml(xml_path: Path | None = None) -> List[Dict[str, Any]]:
    """Return a list of CWE dicts from the MITRE CWE XML catalogue."""
    if xml_path is None:
        config = Config()
        xml_path = config.cti_data_dir / "cwe_latest.xml"

    tree = ET.parse(xml_path)
    root = tree.getroot()

    entries: List[Dict[str, Any]] = []
    for weakness in root.findall(".//" + _NS + "Weakness"):
        cwe_id   = "CWE-" + weakness.get("ID", "")
        name     = weakness.get("Name", "")
        abstract = weakness.get("Abstraction", "")
        status   = weakness.get("Status", "")

        description = _text(weakness, "Description")
        extended    = _text(weakness, "Extended_Description")

        # Common_Consequences → list of Impact strings
        consequences: List[str] = []
        cc = weakness.find(_NS + "Common_Consequences")
        if cc is not None:
            for cons in cc.findall(_NS + "Consequence"):
                for imp in cons.findall(_NS + "Impact"):
                    if imp.text:
                        consequences.append(imp.text.strip())

        # Related_Attack_Patterns → CAPEC IDs
        capec_refs: List[str] = []
        rap = weakness.find(_NS + "Related_Attack_Patterns")
        if rap is not None:
            for ref in rap.findall(_NS + "Related_Attack_Pattern"):
                cid = ref.get("CAPEC_ID")
                if cid:
                    capec_refs.append(f"CAPEC-{cid}")

        entries.append({
            "id":           cwe_id,
            "name":         name,
            "abstraction":  abstract,
            "status":       status,
            "description":  description,
            "extended_description": extended,
            "consequences": consequences,
            "capec_refs":   capec_refs,
        })

    return entries


if __name__ == "__main__":
    entries = parse_cwe_xml()
    print(f"Parsed {len(entries)} CWE entries")
    print("Sample:", entries[0])