cve-kgrag-db / code /src /generators /cwe_parser.py
DuyTa's picture
Add code/: full CVE-KGRAG project source snapshot
27f6252 verified
Raw
History Blame Contribute Delete
3.05 kB
"""
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])