Cyber / impl /src /pipeline /step07a_taxonomy_attack.py
pramodkachare's picture
Upload project files (excluding raw/derived dataset and venv)
aefa98b verified
Raw History Blame Contribute Delete
10.2 kB
"""STEP 07a: ground the 31 attack classes in MITRE ATT&CK (Enterprise v20.0) and derive Taxonomy v1; compare with provisional v0.
Inputs : data/external/attack/enterprise-attack.json (MITRE ATT&CK STIX, downloaded), artifacts/step07a/attack_mapping_raw.json
(per-source extraction from the dataset papers + an independent skeptic pass; produced by an agent workflow on 2026-10-31).
Method : the mapping of every (source dataset, label) is curated below from the extraction and the skeptic's corrections. Every technique
id is looked up in the STIX file (must exist, not deprecated/revoked); names and tactics come from the file, not from memory.
Rule : family_v1 = ATT&CK technique cluster of the label's PRIMARY technique (cluster table below). Where a label is mapped differently
in different sources, the higher-confidence mapping is used; ties are resolved by the label's own meaning (documented override).
Outputs: artifacts/step07a/{taxonomy_attack_mapping.csv, taxonomy_v1.csv, taxonomy_comparison.csv, summary.json}
Limits : ATT&CK describes adversary behaviour, not flow statistics; flow observability is recorded per row. Most UNSW class definitions are
one-line umbrellas, so their mapping confidence is low. Quotes extracted by the agents were re-checked by a skeptic pass but not by a human.
"""
import csv, json
from .common import *
NAME = "step07a"
STIX = os.path.join(DATA, "external", "attack", "enterprise-attack.json")
# (source, label): (primary technique, [secondary techniques], confidence) confidence after the skeptic pass
MAP = {
("NF-UNSW-NB15-v3", "Analysis"): ("T1190", ["T1595"], "low"),
("NF-UNSW-NB15-v3", "Backdoor"): ("T1205", [], "low"),
("NF-UNSW-NB15-v3", "DoS"): ("T1499", ["T1498"], "medium"),
("NF-UNSW-NB15-v3", "Exploits"): ("T1190", ["T1210"], "low"),
("NF-UNSW-NB15-v3", "Fuzzers"): ("T1499.004", ["T1595.002"], "low"),
("NF-UNSW-NB15-v3", "Generic"): (None, [], "low"),
("NF-UNSW-NB15-v3", "Reconnaissance"): ("T1595", ["T1046"], "medium"),
("NF-UNSW-NB15-v3", "Shellcode"): ("T1059", ["T1055"], "low"),
("NF-UNSW-NB15-v3", "Worms"): ("T1210", ["T1570"], "medium"),
("NF-ToN-IoT-v3", "Backdoor"): ("T1190", [], "low"),
("NF-ToN-IoT-v3", "DDoS"): ("T1499", ["T1499.002"], "medium"),
("NF-ToN-IoT-v3", "DoS"): ("T1499", ["T1498.001"], "medium"),
("NF-ToN-IoT-v3", "injection"): ("T1190", ["T1565"], "medium"),
("NF-ToN-IoT-v3", "mitm"): ("T1557.002", ["T1557", "T1040"], "high"),
("NF-ToN-IoT-v3", "password"): ("T1110.001", [], "high"),
("NF-ToN-IoT-v3", "ransomware"): ("T1486", ["T1190"], "medium"),
("NF-ToN-IoT-v3", "scanning"): ("T1595", ["T1595.001", "T1595.002"], "medium"),
("NF-ToN-IoT-v3", "xss"): ("T1190", ["T1059.007"], "medium"),
("NF-BoT-IoT-v3", "DDoS"): ("T1498.001", ["T1499.001", "T1499.002"], "medium"),
("NF-BoT-IoT-v3", "DoS"): ("T1498.001", ["T1499.001", "T1499.002"], "medium"),
("NF-BoT-IoT-v3", "Reconnaissance"): ("T1595", ["T1046"], "high"),
("NF-BoT-IoT-v3", "Theft"): ("T1041", ["T1056.001", "T1110.001"], "medium"),
("NF-CSE-CIC-IDS2018-v3", "Bot"): ("T1071", ["T1584.005"], "medium"),
("NF-CSE-CIC-IDS2018-v3", "Brute_Force_-Web"): ("T1110.001", [], "low"),
("NF-CSE-CIC-IDS2018-v3", "Brute_Force_-XSS"): ("T1190", ["T1059.007"], "low"),
("NF-CSE-CIC-IDS2018-v3", "DDOS_attack-HOIC"): ("T1499.002", ["T1498.001"], "low"),
("NF-CSE-CIC-IDS2018-v3", "DDOS_attack-LOIC-UDP"): ("T1498.001", [], "low"),
("NF-CSE-CIC-IDS2018-v3", "DDoS_attacks-LOIC-HTTP"): ("T1499.002", ["T1498.001"], "low"),
("NF-CSE-CIC-IDS2018-v3", "DoS_attacks-GoldenEye"): ("T1499.002", [], "low"),
("NF-CSE-CIC-IDS2018-v3", "DoS_attacks-Hulk"): ("T1499.002", [], "low"),
("NF-CSE-CIC-IDS2018-v3", "DoS_attacks-SlowHTTPTest"): ("T1499", [], "low"),
("NF-CSE-CIC-IDS2018-v3", "DoS_attacks-Slowloris"): ("T1499", ["T1499.002"], "low"),
("NF-CSE-CIC-IDS2018-v3", "FTP-BruteForce"): ("T1110.001", [], "high"),
("NF-CSE-CIC-IDS2018-v3", "SSH-Bruteforce"): ("T1110.001", [], "high"),
("NF-CSE-CIC-IDS2018-v3", "Infilteration"): ("T1566.001", ["T1203"], "medium"),
("NF-CSE-CIC-IDS2018-v3", "SQL_Injection"): ("T1190", [], "high"),
}
CLUSTERS = [ # (technique id prefix, family)
("T1498", "DENIAL_OF_SERVICE"), ("T1499", "DENIAL_OF_SERVICE"), ("T1595", "RECON_DISCOVERY"), ("T1046", "RECON_DISCOVERY"),
("T1110", "CREDENTIAL_ACCESS"), ("T1557", "CREDENTIAL_ACCESS"), ("T1190", "EXPLOIT_PUBLIC_APP"), ("T1205", "COMMAND_AND_CONTROL"),
("T1071", "COMMAND_AND_CONTROL"), ("T1210", "LATERAL_MOVEMENT"), ("T1059", "EXECUTION"), ("T1486", "RANSOMWARE_IMPACT"),
("T1041", "EXFILTRATION"), ("T1566", "CLIENT_INITIAL_ACCESS"),
]
OVERRIDE = {"Backdoor": ("COMMAND_AND_CONTROL", "UNSW maps to T1205 (traffic signaling, C2) and ToN-IoT to T1190, both low confidence: resolved by the label's meaning")}
CONF = {"high": 3, "medium": 2, "low": 1}
def cluster(tid):
if tid is None: return "UNMAPPED_NO_ATTACK_COUNTERPART"
for pre, fam in CLUSTERS:
if tid.startswith(pre): return fam
raise KeyError(tid)
def run(force=False):
out = step_dir(NAME)
stix = json.load(open(STIX))["objects"]
tech = {}
for o in stix:
if o.get("type") == "attack-pattern":
for r in o.get("external_references", []):
if r.get("source_name") == "mitre-attack": tech[r["external_id"]] = o
def info(tid):
o = tech.get(tid); assert o is not None, f"{tid} not in ATT&CK"
assert not o.get("x_mitre_deprecated") and not o.get("revoked"), f"{tid} deprecated/revoked"
return o["name"], ",".join(p["phase_name"] for p in o.get("kill_chain_phases", []))
raw = json.load(open(os.path.join(out, "attack_mapping_raw.json")))
ev = {}
for s in raw:
ch = {v["label"]: v for v in s["challenge"]["verdicts"]}
for c in s["mapping"]["classes"]:
ev[(s["source"], c["label"])] = (c, ch.get(c["label"], {}))
rows, per_label = [], {}
sizes = {(a, s): c for a, s, c in connect().execute(f"SELECT Attack, source, count(*) FROM read_parquet('{PARQUET_SRC}') GROUP BY ALL").fetchall()}
for (src, lab), (prim, sec, conf) in MAP.items():
c, v = ev[(src, lab)]
pn, pt = info(prim) if prim else ("(no ATT&CK technique)", "")
secs = "; ".join(f"{t} {info(t)[0]}" for t in sec)
fam = cluster(prim)
rows.append([src, lab, sizes.get((lab, src), 0), prim or "", pn, pt, secs, fam, conf, c["netflow_observable"],
c["documented_behaviour"][:300], c["evidence"][:300], c["caveat"][:300], ("accepted" if v.get("mapping_ok") else "corrected by skeptic"), (v.get("problem") or "")[:300]])
per_label.setdefault(lab, []).append((src, prim, fam, conf, sizes.get((lab, src), 0)))
with open(os.path.join(out, "taxonomy_attack_mapping.csv"), "w", newline="") as f:
w = csv.writer(f)
w.writerow(["source", "label", "flows", "primary_technique", "primary_technique_name", "primary_tactics", "secondary_techniques", "family_v1_cluster", "confidence",
"netflow_observable", "documented_behaviour", "evidence", "caveat", "skeptic_status", "skeptic_note"]); w.writerows(rows)
fam1, notes = {}, {}
for lab, ms in per_label.items():
fams = {m[2] for m in ms}
if len(fams) == 1: fam1[lab] = fams.pop()
elif lab in OVERRIDE: fam1[lab], notes[lab] = OVERRIDE[lab]
else:
best = max(ms, key=lambda m: (CONF[m[3]], m[4])); fam1[lab] = best[2]; notes[lab] = "higher-confidence / larger mapping used"
labels_data = {a for a, in connect().execute(f"SELECT DISTINCT Attack FROM read_parquet('{PARQUET_SRC}')").fetchall()} - {"Benign"}
assert set(fam1) == labels_data, set(fam1) ^ labels_data
with open(os.path.join(out, "taxonomy_v1.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["Attack", "family"]); w.writerows(sorted(fam1.items(), key=lambda x: (x[1], x[0])))
co0 = {a: frozenset(b for b in fam1 if FAMILY_OF[b] == FAMILY_OF[a]) for a in fam1} # classes sharing a family with a, under v0
co1 = {a: frozenset(b for b in fam1 if fam1[b] == fam1[a]) for a in fam1} # ... under v1
comp = [[a, FAMILY_OF[a], fam1[a], int(co0[a] != co1[a]), notes.get(a, "")] for a in sorted(fam1, key=lambda a: (fam1[a], a))] # changed = group membership differs
with open(os.path.join(out, "taxonomy_comparison.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["Attack", "family_v0", "family_v1", "changed", "note"]); w.writerows(comp)
# agreement of the two partitions (adjusted Rand index over the 31 classes, flow-weighted too)
import numpy as np
cls = sorted(fam1); tot = {a: sum(c for (x, s), c in sizes.items() if x == a) for a in cls}
def ari(wt):
v0 = [FAMILY_OF[a] for a in cls]; v1 = [fam1[a] for a in cls]; w_ = np.array([wt[a] for a in cls], float)
f0 = {k: i for i, k in enumerate(sorted(set(v0)))}; f1 = {k: i for i, k in enumerate(sorted(set(v1)))}
M = np.zeros((len(f0), len(f1)))
for a, x, y in zip(cls, v0, v1): M[f0[x], f1[y]] += w_[cls.index(a)]
c2 = lambda x: x * (x - 1) / 2
n = M.sum(); sij = c2(M).sum(); sa = c2(M.sum(1)).sum(); sb = c2(M.sum(0)).sum(); exp = sa * sb / c2(n)
return float((sij - exp) / (0.5 * (sa + sb) - exp))
fam_counts = {}
for a, f in fam1.items(): fam_counts.setdefault(f, []).append(a)
save_json({"attack_version": "Enterprise ATT&CK v20.0", "n_mapped_rows": len(rows), "families_v1": {k: sorted(v) for k, v in sorted(fam_counts.items())},
"n_families_v1": len(fam_counts), "n_families_v0": len(set(FAMILY_OF.values())) - 1, "classes_changed_v0_to_v1": [c[0] for c in comp if c[3]],
"ari_unweighted": round(ari({a: 1 for a in cls}), 3), "ari_flow_weighted": round(ari(tot), 3),
"confidence_counts": {k: sum(1 for r in rows if r[8] == k) for k in CONF}, "skeptic_corrected": sum(1 for r in rows if r[13] != "accepted"),
"unmapped": [r[1] for r in rows if not r[3]], "overrides": notes}, os.path.join(out, "summary.json"))
print(open(os.path.join(out, "summary.json")).read())