mvd001/cyberset / scripts /net /ids /run_exploit_pcaps.py
mvd001's picture
download
raw
8.3 kB
#!/usr/bin/env python3
"""CVE-tagged exploit pcap collections -> derived flow features + labels only (no pcaps, no payloads are published).
Pcaps are inert input to an offline Suricata read; nothing in the repos is executed, replayed or built.
tagged captures (filename/README pins the CVE): all flows, label_source=exploit_pcap (benign counterpart captures -> benign)
untagged captures (no verifiable CVE): only flows alerted by a CVE-referencing ET rule, label_source=ids_signature
Output: net_flow dataset=exploit_pcap, units <collection>-tagged / <collection>-ids; net_alert dataset=exploit_pcap."""
import os, re, sys, json, glob, time, shutil, subprocess
sys.path.insert(0, "/workspace/security-dataset/scripts/net/ids")
import idslib as I, pcapfix, build_unit
ROOT = I.ROOT; RAW = f"{ROOT}/raw/net/exploit_pcaps"; BASE = f"{I.W}/exploit"; DS = "exploit_pcap"
MS17_010 = "CVE-2017-0143,CVE-2017-0144,CVE-2017-0145,CVE-2017-0146,CVE-2017-0147,CVE-2017-0148"
NOLIC = "no licence file in the upstream repository (all rights reserved by default); only derived flow features + labels are published, never pcaps or payloads"
COLL = {
"ExploitPcapCollection": dict(repo="https://github.com/safest-place/ExploitPcapCollection", lic=f"ExploitPcapCollection (safest-place, GitHub): {NOLIC}"),
"selected-cve-dataset-2024": dict(repo="https://github.com/vitalii-moholivskyi/selected-cve-dataset-2024", lic=f"selected-cve-dataset-2024 (V. Moholivskyi, GitHub): {NOLIC}"),
"shadowbrokers_pcaps": dict(repo="https://www.dropbox.com/sh/kk24ewnqi9qjdvt/AACj7AHJrDHQeyJTuo1oBqeQa", zip="raw/net/exploit_pcaps2/shadowbrokers.zip",
lic=f"Shadowbrokers PCAPs (Eric Conrad, 2017; public Dropbox share listed in the Netresec PCAP index): {NOLIC}"),
"curveball_lua": dict(repo="https://github.com/dlee35/curveball_lua", lic=f"curveball_lua (D. Lee, GitHub; CVE-2020-0601 CurveBall test captures): {NOLIC}"),
}
def tag(coll, rel):
"""-> (cve_tag, tag_conf, split_key) ; cve_tag None = untagged ; '' = benign counterpart capture"""
n = os.path.basename(rel).lower()
if coll == "selected-cve-dataset-2024":
att = {"1": "CVE-2024-27983", "2": "CVE-2024-31449", "3": "CVE-2024-21538", "4": "CVE-2024-21534"} # README: Attack N <-> malicious_N / benign_N
m = re.match(r"(malicious|benign)_(\d)", n)
if not m: return None, None, None
return (att[m.group(2)] if m.group(1) == "malicious" else ""), "0.85", att[m.group(2)]
if coll == "shadowbrokers_pcaps": # README.txt (E. Conrad): Equation Group tool runs against lab hosts
if n.startswith("eternalblue-success"): return "CVE-2017-0144", "0.85", "CVE-2017-0143"
if n.startswith("eternalblue-failed-patched"): return "CVE-2017-0144", "0.6", "CVE-2017-0143"
if n.startswith("eternalromance"): return "CVE-2017-0145", "0.85", "CVE-2017-0143"
if n.startswith("metasploit-ms017-010"): return MS17_010, "0.85", "CVE-2017-0143"
if n.startswith("esteemedaudit-failed"): return "CVE-2017-0176", "0.6", "CVE-2017-0176"
return None, None, None # doublepulsar backdoor connect: implant C2, no CVE -> IDS only
if coll == "curveball_lua": # README: pcaps to find CVE-2020-0601 (CurveBall, spoofed ECC certificate) exploit attempts
if n.startswith("badcurveball"): return "CVE-2020-0601", "0.8", "CVE-2020-0601"
if n.startswith("goodcurveball"): return "", "0.8", "CVE-2020-0601" # legitimate-certificate counterpart
return None, None, None
m = re.findall(r"cve[-_](\d{4})[-_](\d{4,7})", n)
if m: c = ",".join(sorted({f"CVE-{a}-{b}" for a, b in m})); return c, "0.85", c.split(",")[0]
if "ms17-010" in n:
conf = "0.85" if "exploit" in n else ("0.6" if "patched" in n else "0.7") # exploit run / vulnerability-check probe / probe vs patched host
return MS17_010, conf, "CVE-2017-0143"
if n.startswith("fastjson1224"): return "CVE-2017-18349", "0.8", "CVE-2017-18349" # Fastjson 1.2.24 autoType deserialisation RCE
return None, None, None
def main():
import argparse; ap = argparse.ArgumentParser(); ap.add_argument("--colls", default=""); ap.add_argument("--rebuild", action="store_true",
help="skip Suricata, rebuild units from existing stage + files.json"); a = ap.parse_args()
os.makedirs(BASE, exist_ok=True); summary = json.load(open(f"{BASE}/summary.json")) if os.path.exists(f"{BASE}/summary.json") else {}
for coll, meta in COLL.items():
if a.colls and coll not in a.colls.split(","): continue
if a.rebuild:
fj = json.load(open(f"{BASE}/{coll}/files.json")); head, recs = fj["commit"], fj["files"]; files = recs; st_dir = f"{BASE}/{coll}"
S1 = build_unit.build(DS, f"{coll}-tagged", f"{st_dir}/tagged/*", "exploit_pcap", meta["lic"], "cve_group_hash (80/10/10 by CVE)")
S2 = build_unit.build(DS, f"{coll}-ids", f"{st_dir}/ids/*", "ids", meta["lic"], "time (per collection, by flow start)")
summary[coll] = dict(commit=head, files=len(recs), tagged=sum(r["cve_tag"] is not None for r in recs), tagged_unit=S1, ids_unit=S2)
I.log(coll, "rebuilt", json.dumps(summary[coll], default=str)); continue
head = subprocess.run(["git", "-C", f"{RAW}/{coll}", "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() if not meta.get("zip") else \
"sha256:" + __import__("hashlib").sha256(open(f"{ROOT}/{meta['zip']}", "rb").read()).hexdigest()
files = sorted(glob.glob(f"{RAW}/{coll}/**/*.pcap", recursive=True))
st_dir = f"{BASE}/{coll}"; os.makedirs(f"{st_dir}/tagged", exist_ok=True); os.makedirs(f"{st_dir}/ids", exist_ok=True)
recs = []
for f in files:
rel = os.path.relpath(f, f"{RAW}/{coll}"); cve, conf, key = tag(coll, rel); safe = re.sub(r"[^A-Za-z0-9._-]", "_", rel)
tmp = f"{I.W}/tmp/x_{safe}"; os.makedirs(tmp, exist_ok=True)
with open(f, "rb") as src, open(f"{tmp}/x.pcap", "wb") as dst: fx = pcapfix.repair(src, dst)
if not fx.get("ok"): # pcapng etc: let Suricata read the original file directly
shutil.copy(f, f"{tmp}/x.pcap")
sr = I.run_suricata(f"{tmp}/x.pcap", f"{tmp}/o")
fl, al, hs = I.harvest(f"{tmp}/o/eve.json", keep_all_flows=cve is not None)
extra = dict(capture_id=f"{coll}@{head[:12]}/{rel}", sub_dataset=coll)
if cve is not None: extra.update(cve_tag=cve, tag_conf=conf, split_key=key)
I.write_stage(fl, al, extra, f"{st_dir}/{'tagged' if cve is not None else 'ids'}/{safe}")
shutil.rmtree(tmp, ignore_errors=True)
recs.append(dict(file=rel, bytes=os.path.getsize(f), cve_tag=cve, tag_conf=conf, repair=fx, suricata=sr, harvest=hs))
I.log(coll, rel, cve, sr.get("packets"), hs)
json.dump(dict(commit=head, files=recs), open(f"{st_dir}/files.json", "w"), indent=1)
S1 = build_unit.build(DS, f"{coll}-tagged", f"{st_dir}/tagged/*", "exploit_pcap", meta["lic"], "cve_group_hash (80/10/10 by CVE)")
S2 = build_unit.build(DS, f"{coll}-ids", f"{st_dir}/ids/*", "ids", meta["lic"], "time (per collection, by flow start)")
summary[coll] = dict(commit=head, files=len(files), tagged=sum(r["cve_tag"] not in (None,) for r in recs), tagged_unit=S1, ids_unit=S2)
I.log(coll, json.dumps(summary[coll], default=str))
with open(f"{ROOT}/logs/net/downloads.jsonl", "a") as fh:
fh.write(json.dumps(dict(dataset=f"exploit_pcap_{coll}", version=head[:19] if meta.get("zip") else head[:12], url=meta["repo"] + ("?dl=1" if meta.get("zip") else ".git"), page=meta["repo"], name=f"{coll}@{head}",
path=f"raw/net/exploit_pcaps/{coll}", license=meta["lic"], status="ok", size_bytes=sum(r["bytes"] for r in recs),
checked_ist=time.strftime("%Y-%m-%d %H:%M IST", time.gmtime(time.time() + 19800)),
sha256=head[7:] if meta.get("zip") else None,
note=(f"zip download; {len(files)} pcaps extracted and" if meta.get("zip") else f"git clone --depth 1; {len(files)} pcaps") + " read offline by Suricata; deleted after processing")) + "\n")
json.dump(summary, open(f"{BASE}/summary.json", "w"), indent=1, default=str)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
8.3 kB
·
Xet hash:
94bce578719bdbcfba31bd246dbd024aa8019c68fa31885137773b46a7aea1f0

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.