| """CWE, CAPEC, ATT&CK -> processed/{weakness_kb,capec_kb,attack_kb,taxonomy_map}.parquet""" | |
| import sys, os, zipfile, json, re | |
| from collections import defaultdict, deque | |
| from lxml import etree | |
| import pyarrow as pa, pyarrow.parquet as pq | |
| sys.path.insert(0, os.path.dirname(__file__)) | |
| from hubcommon import ROOT, one | |
| PROC = f"{ROOT}/processed" | |
| def text(el): | |
| return re.sub(r"\s+", " ", "".join(el.itertext())).strip() if el is not None else None | |
| def uniq(xs): | |
| out = [] | |
| for x in xs: | |
| if x not in out: out.append(x) | |
| return out | |
| # ---------------- CWE ---------------- | |
| cwe_zip = one("cwe/*/cwec_latest.xml.zip") | |
| zf = zipfile.ZipFile(cwe_zip); xml_name = zf.namelist()[0] | |
| root = etree.fromstring(zf.read(xml_name)) | |
| NS = {"c": root.nsmap[None]} | |
| CWE_VERSION = root.get("Version") | |
| cwe = {} | |
| for w in root.iterfind(".//c:Weaknesses/c:Weakness", NS): | |
| cid = "CWE-" + w.get("ID") | |
| p1000, pany = [], [] | |
| for rw in w.iterfind("c:Related_Weaknesses/c:Related_Weakness", NS): | |
| if rw.get("Nature") == "ChildOf": | |
| t = "CWE-" + rw.get("CWE_ID"); pany.append(t) | |
| if rw.get("View_ID") == "1000": p1000.append(t) | |
| cwe[cid] = dict(cwe_id=cid, name=w.get("Name"), kind="weakness", abstraction=w.get("Abstraction"), status=w.get("Status"), | |
| description=text(w.find("c:Description", NS)), parents=uniq(p1000), parents_any_view=uniq(pany), | |
| capec_ids=uniq("CAPEC-" + r.get("CAPEC_ID") for r in w.iterfind("c:Related_Attack_Patterns/c:Related_Attack_Pattern", NS)), | |
| members=[]) | |
| for c in root.iterfind(".//c:Categories/c:Category", NS): | |
| cid = "CWE-" + c.get("ID") | |
| mem = uniq("CWE-" + m.get("CWE_ID") for m in c.iterfind("c:Relationships/c:Has_Member", NS)) | |
| cwe[cid] = dict(cwe_id=cid, name=c.get("Name"), kind="category", abstraction=None, status=c.get("Status"), | |
| description=text(c.find("c:Summary", NS)), parents=[], parents_any_view=[], capec_ids=[], members=mem) | |
| for v in root.iterfind(".//c:Views/c:View", NS): | |
| cid = "CWE-" + v.get("ID") | |
| cwe[cid] = dict(cwe_id=cid, name=v.get("Name"), kind="view", abstraction=None, status=v.get("Status"), | |
| description=text(v.find("c:Objective", NS)), parents=[], parents_any_view=[], capec_ids=[], | |
| members=uniq("CWE-" + m.get("CWE_ID") for m in v.iterfind("c:Members/c:Has_Member", NS))) | |
| member_of = defaultdict(list) | |
| for k, r in cwe.items(): | |
| if r["kind"] == "category": | |
| for m in r["members"]: member_of[m].append(k) | |
| # ---------------- CAPEC ---------------- | |
| capec_path = one("capec/*/capec_latest.xml") | |
| croot = etree.parse(capec_path).getroot() | |
| CNS = {"c": croot.nsmap[None]} | |
| CAPEC_VERSION = croot.get("Version") | |
| capec = {} | |
| for a in croot.iterfind(".//c:Attack_Patterns/c:Attack_Pattern", CNS): | |
| pid = "CAPEC-" + a.get("ID") | |
| att = [] | |
| for tm in a.iterfind("c:Taxonomy_Mappings/c:Taxonomy_Mapping", CNS): | |
| if tm.get("Taxonomy_Name") == "ATTACK": | |
| e = (tm.findtext("c:Entry_ID", namespaces=CNS) or "").strip() | |
| if e: att.append(e if e.startswith("T") else "T" + e) | |
| capec[pid] = dict(capec_id=pid, name=a.get("Name"), abstraction=a.get("Abstraction"), status=a.get("Status"), | |
| description=text(a.find("c:Description", CNS)), likelihood=a.findtext("c:Likelihood_Of_Attack", namespaces=CNS), | |
| severity=a.findtext("c:Typical_Severity", namespaces=CNS), | |
| parents=uniq("CAPEC-" + r.get("CAPEC_ID") for r in a.iterfind("c:Related_Attack_Patterns/c:Related_Attack_Pattern", CNS) if r.get("Nature") == "ChildOf"), | |
| cwe_ids=uniq("CWE-" + r.get("CWE_ID") for r in a.iterfind("c:Related_Weaknesses/c:Related_Weakness", CNS)), | |
| attack_techniques_direct=uniq(att)) | |
| # CWE<->CAPEC union of both directions | |
| for pid, p in capec.items(): | |
| for c in p["cwe_ids"]: | |
| if c in cwe and pid not in cwe[c]["capec_ids"]: cwe[c]["capec_ids"].append(pid) | |
| for c, r in cwe.items(): | |
| for pid in r["capec_ids"]: | |
| if pid in capec and c not in capec[pid]["cwe_ids"]: capec[pid]["cwe_ids"].append(c) | |
| # ---------------- ATT&CK ---------------- | |
| att_path = one("attack/*/enterprise-attack.json") | |
| bundle = json.load(open(att_path)) | |
| objs = {o["id"]: o for o in bundle["objects"]} | |
| ATTACK_VERSION = next((o.get("x_mitre_version") for o in bundle["objects"] if o["type"] == "x-mitre-collection"), None) | |
| def ext_id(o): | |
| return next((r.get("external_id") for r in o.get("external_references", []) if r.get("source_name") == "mitre-attack"), None) | |
| # data components per technique via detects(detection-strategy -> technique) -> analytics -> log source refs | |
| dc_by_tech = defaultdict(list) | |
| for o in bundle["objects"]: | |
| if o["type"] == "relationship" and o.get("relationship_type") == "detects": | |
| ds = objs.get(o["source_ref"]); tech = o["target_ref"] | |
| if not ds or ds.get("type") != "x-mitre-detection-strategy": continue | |
| for an in ds.get("x_mitre_analytic_refs", []) or []: | |
| for ls in (objs.get(an) or {}).get("x_mitre_log_source_references", []) or []: | |
| dc = objs.get(ls.get("x_mitre_data_component_ref")) | |
| if dc and dc["name"] not in dc_by_tech[tech]: dc_by_tech[tech].append(dc["name"]) | |
| attack = {} | |
| for o in bundle["objects"]: | |
| if o["type"] != "attack-pattern": continue | |
| tid = ext_id(o) | |
| if not tid: continue | |
| attack[tid] = dict(technique_id=tid, name=o.get("name"), | |
| tactic=[k["phase_name"] for k in o.get("kill_chain_phases", []) if k.get("kill_chain_name") == "mitre-attack"], | |
| is_subtechnique=bool(o.get("x_mitre_is_subtechnique")), parent_technique=tid.split(".")[0] if "." in tid else None, | |
| platforms=o.get("x_mitre_platforms") or [], | |
| capec_ids=uniq(r["external_id"] for r in o.get("external_references", []) if r.get("source_name") == "capec" and r.get("external_id")), | |
| data_sources=sorted(dc_by_tech.get(o["id"], []) or (o.get("x_mitre_data_sources") or [])), | |
| deprecated=bool(o.get("x_mitre_deprecated")), revoked=bool(o.get("revoked")), | |
| description=o.get("description"), url=next((r.get("url") for r in o.get("external_references", []) if r.get("source_name") == "mitre-attack"), None), | |
| modified=o.get("modified"), stix_id=o["id"]) | |
| # resolve revoked technique ids (CAPEC 3.9 maps to some ids ATT&CK has since revoked) via revoked-by relationships | |
| revoked_by = {} | |
| for o in bundle["objects"]: | |
| if o["type"] == "relationship" and o.get("relationship_type") == "revoked-by": | |
| s_, t_ = objs.get(o["source_ref"]), objs.get(o["target_ref"]) | |
| if s_ and t_ and s_.get("type") == "attack-pattern" and ext_id(s_) and ext_id(t_): revoked_by[ext_id(s_)] = ext_id(t_) | |
| def resolve(t, depth=0): | |
| if t in revoked_by and depth < 5: return resolve(revoked_by[t], depth + 1) | |
| return t | |
| capec_attack_dropped, capec_attack_remapped = [], [] | |
| for pid, p in capec.items(): | |
| out = [] | |
| for t in p["attack_techniques_direct"]: | |
| r = resolve(t) | |
| if r != t: capec_attack_remapped.append(f"{pid}:{t}->{r}") | |
| if r not in attack or attack[r]["revoked"] or attack[r]["deprecated"]: | |
| capec_attack_dropped.append(f"{pid}:{t}"); continue | |
| if r not in out: out.append(r) | |
| p["attack_techniques_direct"] = out | |
| # ATT&CK<->CAPEC union of both directions | |
| for pid, p in capec.items(): | |
| for t in p["attack_techniques_direct"]: | |
| if t in attack and pid not in attack[t]["capec_ids"]: attack[t]["capec_ids"].append(pid) | |
| for t, a in attack.items(): | |
| if a["revoked"] or a["deprecated"]: continue | |
| for pid in a["capec_ids"]: | |
| if pid in capec and t not in capec[pid]["attack_techniques_direct"]: capec[pid]["attack_techniques_direct"].append(t) | |
| # ---------------- closures ---------------- | |
| def nearest_with(start, parents_of, has): | |
| """BFS up the hierarchy; return (ids, basis) from the nearest ancestor level that has a mapping.""" | |
| seen, frontier, depth = {start}, [start], 0 | |
| while frontier: | |
| found = [] | |
| for n in frontier: | |
| v = has(n) | |
| if v: found += [x for x in v if x not in found] | |
| if found: return found, ("direct" if depth == 0 else f"inherited_depth{depth}") | |
| nxt = [] | |
| for n in frontier: | |
| for p in parents_of(n): | |
| if p not in seen: seen.add(p); nxt.append(p) | |
| frontier, depth = nxt, depth + 1 | |
| return [], None | |
| for pid, p in capec.items(): | |
| p["attack_techniques"], p["attack_basis"] = nearest_with(pid, lambda n: capec.get(n, {}).get("parents", []), | |
| lambda n: capec.get(n, {}).get("attack_techniques_direct")) | |
| children = defaultdict(list) | |
| for k, r in cwe.items(): | |
| for pnt in r["parents"]: children[pnt].append(k) | |
| def ancestors(cid): | |
| out, q = [], deque(cwe.get(cid, {}).get("parents", [])) | |
| while q: | |
| x = q.popleft() | |
| if x in out: continue | |
| out.append(x); q.extend(cwe.get(x, {}).get("parents", [])) | |
| return out | |
| wk_rows, tax_rows = [], [] | |
| for k, r in sorted(cwe.items(), key=lambda kv: int(kv[0][4:])): | |
| caps, basis = nearest_with(k, lambda n: cwe.get(n, {}).get("parents", []), lambda n: cwe.get(n, {}).get("capec_ids")) | |
| techs = uniq(t for c in caps for t in capec.get(c, {}).get("attack_techniques", [])) | |
| techs_direct = uniq(t for c in r["capec_ids"] for t in capec.get(c, {}).get("attack_techniques_direct", [])) | |
| wk_rows.append(dict(cwe_id=k, name=r["name"], kind=r["kind"], abstraction=r["abstraction"], status=r["status"], | |
| description=r["description"], parents=r["parents"], parents_any_view=r["parents_any_view"], | |
| children=children.get(k, []) if r["kind"] == "weakness" else r["members"], | |
| ancestors=ancestors(k), member_of_categories=member_of.get(k, []), capec_ids=r["capec_ids"])) | |
| if r["kind"] == "view": continue | |
| tax_rows.append(dict(family=k, family_type="cwe", description=r["name"], cwe_ids=[k], capec_ids=caps, | |
| attack_techniques=techs, capec_ids_direct=r["capec_ids"], attack_techniques_direct=techs_direct, | |
| mapping_basis=basis, cve_ids=[], label_aliases=[])) | |
| # ---------------- attack families (hand-curated seed set; validated below) ---------------- | |
| FAMILIES = [ | |
| ("sql_injection", "SQL injection against web applications", ["CWE-89"], ["CAPEC-66", "CAPEC-7", "CAPEC-108", "CAPEC-110"], ["T1190"], [], | |
| ["Web Attack – Sql Injection", "Web Attack - Sql Injection", "SQL Injection", "sql_injection", "SQLi"]), | |
| ("xss", "Cross-site scripting", ["CWE-79", "CWE-80"], ["CAPEC-63", "CAPEC-588", "CAPEC-591", "CAPEC-592"], ["T1189", "T1059.007"], [], | |
| ["Web Attack – XSS", "Web Attack - XSS", "Brute Force -XSS", "XSS", "xss"]), | |
| ("command_injection", "OS command / code injection", ["CWE-77", "CWE-78", "CWE-94"], ["CAPEC-88", "CAPEC-248", "CAPEC-242"], ["T1190", "T1059"], [], | |
| ["Command Injection", "Code Injection"]), | |
| ("injection", "Injection attacks of unspecified kind (SQL + code injection; ToN-IoT / NF-UQ 'Injection')", ["CWE-74"], ["CAPEC-66", "CAPEC-248"], ["T1190"], [], | |
| ["Injection", "injection"]), | |
| ("path_traversal", "Directory / path traversal", ["CWE-22"], ["CAPEC-126", "CAPEC-139"], ["T1190", "T1083"], [], ["Path Traversal", "Directory Traversal"]), | |
| ("brute_force", "Credential brute forcing / password guessing (FTP, SSH, web login)", ["CWE-307", "CWE-521", "CWE-1391"], | |
| ["CAPEC-49", "CAPEC-112", "CAPEC-16", "CAPEC-565", "CAPEC-600"], ["T1110", "T1110.001", "T1110.003", "T1110.004"], [], | |
| ["FTP-Patator", "SSH-Patator", "Web Attack – Brute Force", "Web Attack - Brute Force", "Brute Force -Web", "FTP-BruteForce", "SSH-Bruteforce", "password", "Password", "BruteForce", "Brute Force"]), | |
| ("dos", "Denial of service from one/few sources (HTTP floods, slow-rate, resource exhaustion)", ["CWE-400", "CWE-770"], | |
| ["CAPEC-125", "CAPEC-469", "CAPEC-482", "CAPEC-486", "CAPEC-488", "CAPEC-130"], ["T1499", "T1499.001", "T1499.002", "T1499.003", "T1498", "T1498.001"], [], | |
| ["DoS Hulk", "DoS GoldenEye", "DoS slowloris", "DoS Slowhttptest", "DoS attacks-Hulk", "DoS attacks-GoldenEye", "DoS attacks-Slowloris", "DoS attacks-SlowHTTPTest", "DoS Slowloris", "DoS SlowHttpTest", "DoS", "dos"]), | |
| ("ddos", "Distributed denial of service incl. reflection/amplification floods", ["CWE-400", "CWE-406", "CWE-770"], | |
| ["CAPEC-125", "CAPEC-482", "CAPEC-486", "CAPEC-487", "CAPEC-488", "CAPEC-490"], ["T1498", "T1498.001", "T1498.002", "T1499.002"], [], | |
| ["DDoS", "DDOS attack-HOIC", "DDOS attack-LOIC-UDP", "DDoS attacks-LOIC-HTTP", "DrDoS_DNS", "DrDoS_LDAP", "DrDoS_MSSQL", "DrDoS_NTP", "DrDoS_NetBIOS", | |
| "DrDoS_SNMP", "DrDoS_SSDP", "DrDoS_UDP", "Syn", "TFTP", "UDP-lag", "WebDDoS", "ddos"]), | |
| ("port_scan", "Port / service scanning", [], ["CAPEC-300", "CAPEC-301", "CAPEC-287", "CAPEC-302", "CAPEC-303", "CAPEC-308"], ["T1046", "T1595", "T1595.001", "T1595.002"], [], | |
| ["PortScan", "Portscan", "scanning", "Scan", "Service_Scan", "OS_Fingerprint", "PartOfAHorizontalPortScan", "Scanning", "Infiltration - Portscan"]), | |
| ("reconnaissance", "Network reconnaissance / probing / fingerprinting", [], ["CAPEC-169", "CAPEC-292", "CAPEC-312", "CAPEC-300"], ["T1595", "T1046", "T1018", "T1590"], [], | |
| ["Reconnaissance", "Analysis", "Probe", "probing"]), | |
| ("botnet", "Botnet C2 and bot activity", [], [], ["T1071", "T1071.001", "T1583.005", "T1584.005", "T1571"], [], | |
| ["Bot", "Botnet", "C&C", "C&C-HeartBeat", "C&C-Mirai", "C&C-Torii", "Mirai", "Torii", "Okiru", "botnet"]), | |
| ("heartbleed", "OpenSSL Heartbleed TLS heartbeat over-read", ["CWE-125", "CWE-119"], ["CAPEC-540"], ["T1190", "T1040"], ["CVE-2014-0160"], | |
| ["Heartbleed"]), | |
| ("infiltration", "Internal infiltration after a user-executed payload (CIC-IDS2017/2018 'Infiltration')", [], ["CAPEC-185"], | |
| ["T1204", "T1204.002", "T1105", "T1046", "T1071"], [], ["Infiltration", "Infilteration"]), | |
| ("backdoor", "Backdoor / remote access implant traffic", ["CWE-912"], [], ["T1219", "T1071", "T1505.003"], [], ["Backdoor", "Backdoors", "backdoor"]), | |
| ("exploit", "Generic exploitation of a known vulnerability (public-facing service)", [], [], ["T1190", "T1210", "T1203"], [], ["Exploits", "Exploit", "exploit"]), | |
| ("shellcode", "Shellcode delivery / memory-corruption payloads", ["CWE-119", "CWE-787"], ["CAPEC-100"], ["T1203", "T1190"], [], ["Shellcode"]), | |
| ("worm", "Self-propagating worm traffic", [], [], ["T1210", "T1570"], [], ["Worms", "Worm"]), | |
| ("fuzzing", "Protocol / input fuzzing", [], ["CAPEC-28"], ["T1595.002"], [], ["Fuzzers", "Fuzzing"]), | |
| ("generic_crypto", "UNSW-NB15 'Generic': attacks against block-cipher implementations (collision / cryptanalysis)", ["CWE-327"], ["CAPEC-97"], [], [], ["Generic"]), | |
| ("data_theft", "Data theft / exfiltration and keylogging (BoT-IoT 'Theft')", [], ["CAPEC-568"], ["T1041", "T1056.001", "T1005"], [], ["Theft", "Data_Exfiltration", "Keylogging"]), | |
| ("mitm", "Man-in-the-middle (ARP/DNS spoofing etc.)", ["CWE-300"], ["CAPEC-94"], ["T1557", "T1557.002"], [], ["MITM", "mitm"]), | |
| ("ransomware", "Ransomware activity", [], [], ["T1486"], [], ["Ransomware", "ransomware"]), | |
| ("malware_download", "Download of malware / tools by an infected host", [], ["CAPEC-185"], ["T1105"], [], ["FileDownload", "C&C-FileDownload"]), | |
| ("background", "Unverified background traffic (CTU-13 'Background'); mostly benign but not ground-truthed", [], [], [], [], ["Background"]), | |
| ("benign", "Benign / normal traffic", [], [], [], [], ["BENIGN", "Benign", "Normal", "normal", "-"]), | |
| ] | |
| problems = [] | |
| for fam, desc, cw, cp, tt, cves, aliases in FAMILIES: | |
| for c in cw: | |
| if c not in cwe: problems.append(f"{fam}: unknown {c}") | |
| for c in cp: | |
| if c not in capec: problems.append(f"{fam}: unknown {c}") | |
| elif capec[c]["status"] == "Deprecated": problems.append(f"{fam}: deprecated {c}") | |
| for t in tt: | |
| if t not in attack: problems.append(f"{fam}: unknown {t}") | |
| elif attack[t]["deprecated"] or attack[t]["revoked"]: problems.append(f"{fam}: deprecated/revoked {t}") | |
| tax_rows.append(dict(family=fam, family_type="attack_family", description=desc, cwe_ids=cw, capec_ids=cp, attack_techniques=tt, | |
| capec_ids_direct=cp, attack_techniques_direct=tt, mapping_basis="curated", cve_ids=cves, label_aliases=aliases)) | |
| def write(name, rows): | |
| pq.write_table(pa.Table.from_pylist(rows), f"{PROC}/{name}.parquet", compression="zstd") | |
| print(name, len(rows)) | |
| write("weakness_kb", wk_rows) | |
| write("capec_kb", [dict(capec_id=p["capec_id"], name=p["name"], abstraction=p["abstraction"], status=p["status"], description=p["description"], | |
| likelihood=p["likelihood"], severity=p["severity"], parents=p["parents"], cwe_ids=p["cwe_ids"], | |
| attack_techniques_direct=p["attack_techniques_direct"], attack_techniques=p["attack_techniques"], attack_basis=p["attack_basis"]) | |
| for p in sorted(capec.values(), key=lambda x: int(x["capec_id"][6:]))]) | |
| for a in attack.values(): a.pop("stix_id") | |
| write("attack_kb", sorted(attack.values(), key=lambda x: x["technique_id"])) | |
| write("taxonomy_map", tax_rows) | |
| json.dump(dict(cwe_version=CWE_VERSION, capec_version=CAPEC_VERSION, attack_version=ATTACK_VERSION, family_validation_problems=problems, capec_attack_remapped=capec_attack_remapped, capec_attack_dropped=capec_attack_dropped), | |
| open(f"{ROOT}/processed/_intermediate/mitre_meta.json", "w"), indent=1) | |
| print("versions", CWE_VERSION, CAPEC_VERSION, ATTACK_VERSION); print("validation problems:", problems); print("capec->attack remapped", len(capec_attack_remapped), "dropped", len(capec_attack_dropped), capec_attack_dropped[:10]) | |
Xet Storage Details
- Size:
- 17.5 kB
- Xet hash:
- a6bfe6b960cc277842f5f6255e8d581426e05ab2bca9a532268f16a922b29301
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.