DNS Spoofing, Cache Poisoning and DNSSEC
If an attacker can make a resolver believe that www.lab.test is at their address, every client of that resolver goes there: no phishing email, no malware on the victim's machine, just a wrong answer cached for hours. DNS spoofing is answering a query with a forged response; cache poisoning is getting a resolver to store the forgery and hand it to everyone. The previous lesson showed which fields a forged response must match. This one works out the odds an attacker faces, explains the 2008 attack that changed them, and shows how DNSSEC makes forged answers detectable. The first overview is in Security Foundations' DNS and ARP Spoofing.
Everything runnable here is arithmetic, a signature in Python, or a query to the lab DNS server in your sandbox.
Two positions, two difficulties
- On-path (the attacker sees the query, for example after ARP spoofing on the same LAN, or on a compromised router): the ID and port are visible, so a forged answer that arrives first always wins. Nothing in plain DNS stops it.
- Off-path (the attacker can only send packets): it must guess the ID, the resolver's source port and the timing, and its forged answer must arrive before the real one.
The odds of an off-path race
A resolver sends a query and waits a few milliseconds. In that window the attacker sends k forged responses with different guesses. With N equally likely combinations, one race succeeds with probability about k/N. The program compares a resolver with a fixed source port (only the 16-bit ID is unknown) with one that randomises the port (RFC 5452, about 16 more bits).
N_ID = 2**16
N_PORT = 64512 # ports 1024-65535 a resolver may choose from
k = 200 # forged responses that arrive inside one race window
for label, N in [("fixed source port (ID only)", N_ID), ("unpredictable port + ID", N_ID * N_PORT)]:
p = k / N
print(f"{label:<28} one race: {p:.2e}")
for races in (1, 100, 10_000):
print(f"{'':<28} {races:>6} races: P(success) = {1 - (1 - p) ** races:.4f}")fixed source port (ID only) one race: 3.05e-03
1 races: P(success) = 0.0031
100 races: P(success) = 0.2633
10000 races: P(success) = 1.0000
unpredictable port + ID one race: 4.73e-08
1 races: P(success) = 0.0000
100 races: P(success) = 0.0000
10000 races: P(success) = 0.0005
With a fixed port, about 230 races give an even chance and a few thousand make success practically certain. With random ports, even 10,000 races succeed with probability 0.0005.
Why many races? Before 2008, a poisoner could only try when the resolver had no cached answer, so one failed race meant waiting out the TTL. Dan Kaminsky's 2008 technique removed that wait: query random, non-existent names (r4nd0m1.lab.test, r4nd0m2.lab.test, …), each of which forces a fresh lookup, and in each forged response include an authority section saying "the name server for lab.test is at the attacker's address". One win poisons the whole zone. Coordinated patches released on 8 July 2008 (CERT VU#800113, CVE-2008-1447) made BIND, Microsoft DNS and other resolvers that used predictable ports randomise them (djbdns, PowerDNS and Unbound already did), which is why the second row matters.
What the lab server's answers carry
Query the lab server with DNSSEC records requested (+dnssec sets the DO bit). The zone is not signed, so there is nothing to validate: the answer has no RRSIG and no ad (authenticated data) flag. That is the situation of most zones on the Internet today: their answers can be forged without detection by anyone on the path.
dnsmasq --conf-file=$SAMPLES/dns/lab.test.conf --pid-file="$PWD/dns.pid"
for i in $(seq 50); do dig @127.0.0.1 -p 5353 +short lab.test >/dev/null 2>&1 && break; sleep 0.1; done
dig @127.0.0.1 -p 5353 +dnssec www.lab.test | grep -E 'flags:|EDNS|IN'
echo "RRSIG records in the answer: $(dig @127.0.0.1 -p 5353 +dnssec www.lab.test | grep -c RRSIG)"
kill "$(cat dns.pid)";; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
; EDNS: version: 0, flags: do; udp: 1232
;www.lab.test. IN A
www.lab.test. 0 IN A 10.10.0.10
RRSIG records in the answer: 0
DNSSEC in one picture
DNSSEC (RFC 4033–4035) signs DNS data, so a resolver can check that an answer came from the zone's owner, however it travelled:
- RRSIG: a signature over a set of records (an RRset, such as all A records of
www). - DNSKEY: the zone's public keys, published in the zone itself.
- DS: a hash of the zone's key, published in the parent zone (
.testforlab.test). The parent's DS is signed by the parent's key, whose DS is in the root, whose key is the trust anchor configured in every validating resolver. That is the chain of trust. - NSEC / NSEC3: signed proofs that a name does not exist, so NXDOMAIN can't be forged either.
The program models one link of that chain with Ed25519 (DNSSEC algorithm 15, RFC 8080), using a fixed lab key (real zones generate keys randomly and keep them offline or in an HSM). The record encoding is simplified, not the exact wire format of RFC 4034, but the logic is the same: the resolver accepts an answer only if its signature verifies with the zone key it already trusts.
import hashlib
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization
from cryptography.exceptions import InvalidSignature
zone_key = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(b"lab.test zone key, lab only").digest())
dnskey = zone_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
ds = hashlib.sha256(b"lab.test." + dnskey).hexdigest() # what the parent zone publishes
print("DS (SHA-256 of the key), published in the parent:", ds[:16], "...")
def rrset(name, rtype, ttl, value):
return f"{name} {ttl} IN {rtype} {value}".encode()
real = rrset("www.lab.test.", "A", 300, "10.10.0.10")
rrsig = zone_key.sign(real) # done once, by the zone owner
def validate(answer, sig, key_bytes):
if hashlib.sha256(b"lab.test." + key_bytes).hexdigest() != ds:
return "BOGUS: key doesn't match the parent's DS"
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
try:
Ed25519PublicKey.from_public_bytes(key_bytes).verify(sig, answer)
return "SECURE: signature valid"
except InvalidSignature:
return "BOGUS: signature invalid, answer dropped (SERVFAIL)"
forged = rrset("www.lab.test.", "A", 300, "203.0.113.66")
attacker_key = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(b"attacker").digest())
attacker_pub = attacker_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
print("real answer, real RRSIG: ", validate(real, rrsig, dnskey))
print("forged address, real RRSIG: ", validate(forged, rrsig, dnskey))
print("forged, signed by own key: ", validate(forged, attacker_key.sign(forged), attacker_pub))
print("signature size:", len(rrsig), "bytes")DS (SHA-256 of the key), published in the parent: f00ebe9b21ad4637 ...
real answer, real RRSIG: SECURE: signature valid
forged address, real RRSIG: BOGUS: signature invalid, answer dropped (SERVFAIL)
forged, signed by own key: BOGUS: key doesn't match the parent's DS
signature size: 64 bytes
The forged address fails because the signature covers the data; the attacker's own key fails because it doesn't match the DS in the parent. A validating resolver answers SERVFAIL rather than return bogus data, so the attack becomes a denial of service at worst.
How poisoning is detected
- Resolver statistics: many responses with mismatched IDs or ports for one outstanding query (a spoofing race in progress). BIND, Unbound and others count them.
- Bursts of queries for random subdomains of one zone arriving at your resolver from outside clients (only possible if it is an open resolver) or from one internal host.
- Answer changes: compare answers for important names with passive-DNS history; an A record that suddenly points to an unknown network, a new NS for a zone, or a TTL that is much longer than the zone's usual one.
- DNSSEC validation failures (SERVFAIL with "bogus" in the logs) for a signed zone: either a misconfiguration or an attack.
How it is fixed or prevented
| Layer | Control |
|---|---|
| resolver | source-port and ID randomisation (default since 2008), 0x20 case randomisation, no open recursion, DNSSEC validation on |
| zone owner | sign the zone with DNSSEC, keep the DS at the registrar correct, plan key rollovers |
| client to resolver | encrypted DNS (DoT, DoH, DoQ) so on-path attackers near the client can't read or forge answers |
| applications | TLS with certificate validation: a poisoned name leads to a certificate error rather than a silent compromise (HSTS makes the error non-bypassable) |
| local network | DAI and DHCP snooping against the on-path position (ARP spoofing, rogue DHCP) |
Pitfalls
- Thinking DNSSEC encrypts DNS. It signs; queries and answers remain readable. Privacy needs DoT/DoH.
- Signing a zone but leaving validation off on your own resolvers, so your users get none of the benefit.
- Breaking the chain at the registrar during key rollovers: a stale DS makes the whole zone BOGUS and unreachable for validating resolvers.
- Believing port randomisation is enough. NAT devices that rewrite source ports to sequential ones undo it on the way out.
Practice
1. In the odds program, how many races does the fixed-port attacker need for a 50 % chance?
Solve with : races. The Kaminsky technique makes each race a fresh random name, so that takes seconds.
2. Why does the Kaminsky attack use names that don't exist?
A non-existent name is never cached, so every query starts a new race immediately; the payload is in the authority section (a forged NS for the whole zone), so it doesn't matter that the queried name itself is useless.
3. A user reports a certificate warning for your intranet site, but only on the guest Wi-Fi. What could be going on and what do you check?
Possibly DNS spoofing (or a captive portal) on that network: the name resolves to another host, which can't present your certificate. Compare the resolved address on the guest network with the correct one, check which resolver the guest network hands out via DHCP, and look for rogue DHCP or ARP spoofing on it.
Test yourself
Which fields must an off-path attacker guess to forge a DNS response to a modern resolver?
- Only the TTL
- The 16-bit ID and the resolver's random source port (and win the timing race)
- The resolver's private key
- Nothing; resolvers accept any response
What made the 2008 Kaminsky attack so effective?
- It broke DNSSEC
- Queries for random non-existent names allow unlimited races, and a forged authority section poisons the whole zone
- It used TCP
- It required on-path access
In DNSSEC, which record in the parent zone links it to the child zone's key?
- RRSIG
- DS
- NSEC
- SOA
What does a validating resolver return when a signature check fails?
- The forged answer with a warning
- SERVFAIL
- NXDOMAIN
- The answer from its cache with TTL 0