DNS Messages in Packets
dig shows you a DNS answer after it has been decoded. Sensors, resolvers and attackers deal with the bytes: a 12-byte header, a question, and resource records whose names may be compressed with pointers. Reading those bytes yourself is how you check what a tool reports, write a detection that a tool doesn't have, and understand why spoofing a response is a matter of matching a few fields. The message format is described in DNS Messages; this lesson decodes the two responses in $SAMPLES/pcap/dns.pcap.
The header
| Bytes | Field | Notes |
|---|---|---|
| 2 | ID | chosen by the client; the response must echo it |
| 2 | flags | QR (response), opcode, AA, TC (truncated), RD, RA, AD (authenticated data), CD, RCODE (0 NOERROR, 2 SERVFAIL, 3 NXDOMAIN, 5 REFUSED) |
| 2 × 4 | counts | questions, answers, authority records, additional records |
Each name is a sequence of labels, each prefixed by its length, ending with a zero byte: www.lab.test is 03 77 77 77 03 6c 61 62 04 74 65 73 74 00. To save space, a name can end with a pointer (two bytes starting with bits 11) to an earlier position in the message.
A decoder
The program decodes the two responses from the sample capture (the DNS payloads after the UDP headers, copied in). It follows compression pointers, prints the sections, and decodes the SOA record that comes with the NXDOMAIN answer.
import struct, ipaddress
responses = {
"response 1": "1a2b8580000100010000000003777777036c61620474657374000001000103777777036c6162"
"047465737400000100010000012c00040a0a000a",
"response 2": "1a2c85830001000000010000046e6f7065036c616204746573740000010001036c616204746573"
"7400000600010000012c0036026e73036c61620474657374000a686f73746d6173746572036c61"
"6204746573740078c27b6d00000e1000000258000151800000012c",
}
TYPES = {1: "A", 2: "NS", 5: "CNAME", 6: "SOA", 15: "MX", 16: "TXT", 28: "AAAA"}
RCODES = {0: "NOERROR", 2: "SERVFAIL", 3: "NXDOMAIN", 5: "REFUSED"}
def name(msg, off):
labels, jumped, end = [], False, None
while True:
n = msg[off]
if n & 0xC0 == 0xC0: # compression pointer
if not jumped:
end = off + 2
off, jumped = struct.unpack("!H", msg[off:off + 2])[0] & 0x3FFF, True
continue
if n == 0:
return ".".join(labels) + ".", (end if jumped else off + 1)
labels.append(msg[off + 1:off + 1 + n].decode())
off += 1 + n
def decode(msg):
ident, flags, qd, an, ns, ar = struct.unpack("!HHHHHH", msg[:12])
bits = [b for b, m in [("QR", 0x8000), ("AA", 0x0400), ("TC", 0x0200), ("RD", 0x0100), ("RA", 0x0080)] if flags & m]
print(f" id 0x{ident:04x} flags {' '.join(bits)} rcode {RCODES[flags & 15]} counts {qd}/{an}/{ns}/{ar}")
off = 12
for _ in range(qd):
q, off = name(msg, off)
qtype, qclass = struct.unpack("!HH", msg[off:off + 4]); off += 4
print(f" question {q} {TYPES[qtype]}")
for section, count in [("answer", an), ("authority", ns)]:
for _ in range(count):
rr, off = name(msg, off)
rtype, rclass, ttl, rdlen = struct.unpack("!HHIH", msg[off:off + 10]); off += 10
rdata = msg[off:off + rdlen]
if rtype == 1:
value = str(ipaddress.IPv4Address(rdata))
elif rtype == 6:
mname, p = name(msg, off); rname, p = name(msg, p)
serial, refresh, retry, expire, minimum = struct.unpack("!IIIII", msg[p:p + 20])
value = f"{mname} {rname} serial {serial} refresh {refresh} retry {retry} expire {expire} min {minimum}"
else:
value = rdata.hex()
off += rdlen
print(f" {section:<9} {rr} TTL {ttl} {TYPES[rtype]} {value}")
for label, hx in responses.items():
msg = bytes.fromhex(hx)
print(f"{label}: {len(msg)} bytes")
decode(msg)response 1: 58 bytes
id 0x1a2b flags QR AA RD RA rcode NOERROR counts 1/1/0/0
question www.lab.test. A
answer www.lab.test. TTL 300 A 10.10.0.10
response 2: 105 bytes
id 0x1a2c flags QR AA RD RA rcode NXDOMAIN counts 1/0/1/0
question nope.lab.test. A
authority lab.test. TTL 300 SOA ns.lab.test. hostmaster.lab.test. serial 2026011501 refresh 3600 retry 600 expire 86400 min 300
The NXDOMAIN answer carries the zone's SOA in the authority section. Its last field, the minimum (300 s), tells resolvers how long they may cache the fact that nope.lab.test doesn't exist (negative caching, RFC 2308).
The same fields with tshark
Wireshark's DNS field names (dns.id, dns.flags.rcode, dns.qry.name, dns.a, dns.time) work in tshark, so a one-line command gives a table of every query and its outcome; dns.time is the delay between query and response, computed by matching the ID.
cd $SAMPLES/pcap
tshark -r dns.pcap -T fields -E header=y -e frame.number -e ip.src -e udp.srcport -e dns.id \
-e dns.flags.response -e dns.qry.name -e dns.flags.rcode -e dns.a -e dns.time
echo "--- failed lookups only:"
tshark -r dns.pcap -Y 'dns.flags.response == 1 && dns.flags.rcode != 0'frame.number ip.src udp.srcport dns.id dns.flags.response dns.qry.name dns.flags.rcode dns.a dns.time
1 10.10.0.5 40001 0x1a2b False www.lab.test
2 10.10.0.53 53 0x1a2b True www.lab.test 0 10.10.0.10 0.001200000
3 10.10.0.5 40002 0x1a2c False nope.lab.test
4 10.10.0.53 53 0x1a2c True nope.lab.test 3 0.001100000
--- failed lookups only:
4 0.501100 10.10.0.53 → 10.10.0.5 DNS 147 Standard query response 0x1a2c No such name A nope.lab.test SOA ns.lab.test
What the matching fields mean for security
A resolver accepts a response if it arrives from the server it asked, at the source port it used, with the same ID and the same question. Those are all the defences a plain DNS response has. An off-path attacker who wants to inject a fake answer must guess them before the real answer arrives:
- the 16-bit ID: 65,536 possibilities;
- the source port, if the resolver randomises it (RFC 5452): about 2^16 more;
- the question is known to the attacker if it triggered the lookup itself.
The next lesson turns that into odds and shows why DNSSEC was the real fix.
Detecting anomalies in DNS traffic
The checks below run on a list of decoded messages, as a sensor would. The traffic is synthetic: a normal exchange, a response that answers no outstanding query (a sign of spoofing attempts), and a burst of failed lookups from one host.
from collections import defaultdict
msgs = [ # (time, src, sport, dst, dport, id, is_response, qname, rcode)
(0.00, "10.10.0.5", 40001, "10.10.0.53", 53, 0x1a2b, False, "www.lab.test", None),
(0.01, "10.10.0.53", 53, "10.10.0.5", 40001, 0x1a2b, True, "www.lab.test", "NOERROR"),
(0.02, "10.10.0.53", 53, "10.10.0.5", 40001, 0x7777, True, "www.lab.test", "NOERROR"),
] + [(1.0 + i * 0.1, "10.10.0.9", 41000 + i, "10.10.0.53", 53, 0x2000 + i, False, f"x{i}q.example", None)
for i in range(6)] + [
(1.05 + i * 0.1, "10.10.0.53", 53, "10.10.0.9", 41000 + i, 0x2000 + i, True, f"x{i}q.example", "NXDOMAIN")
for i in range(6)]
pending, nx = {}, defaultdict(list)
for t, src, sp, dst, dp, ident, resp, q, rc in sorted(msgs):
if not resp:
pending[(src, sp, dst, ident, q)] = t
continue
key = (dst, dp, src, ident, q)
if key not in pending:
print(f"t={t:.2f} UNMATCHED response id=0x{ident:04x} for {q} to {dst}:{dp} (spoofing attempt or late duplicate)")
continue
del pending[key]
if rc == "NXDOMAIN":
nx[dst].append(t)
for host, times in nx.items():
window = [t for t in times if t - times[0] <= 1.0]
if len(window) >= 5:
print(f"{host}: {len(window)} NXDOMAIN answers within 1 s (DGA or misconfiguration)")
print("queries still unanswered:", len(pending))t=0.02 UNMATCHED response id=0x7777 for www.lab.test to 10.10.0.5:40001 (spoofing attempt or late duplicate)
10.10.0.9: 6 NXDOMAIN answers within 1 s (DGA or misconfiguration)
queries still unanswered: 0
How DNS is protected at the packet level
- Randomised source ports and IDs in resolvers (RFC 5452), and 0x20 encoding (random capitalisation of the query name, which the response must echo) to add guessing entropy.
- DNSSEC validation, so a forged answer fails a signature check whatever fields it guesses.
- Encrypted transports between client and resolver: DNS over TLS (RFC 7858, TCP 853), DNS over HTTPS (RFC 8484), DNS over QUIC (RFC 9250). They protect the path from client to resolver, not the resolver's own lookups.
- Monitoring: unmatched responses, many responses with wrong IDs for one query (a spoofing race), and NXDOMAIN rates per host.
Pitfalls
- Parsing names without a loop limit. A malicious pointer that points to itself sends a naive decoder into an infinite loop; real decoders cap the number of jumps.
- Assuming DNS is UDP only. TCP is used for large answers, zone transfers and DNS over TLS.
- Treating the ID alone as the match key; it is only 16 bits. Port, server and question belong to the key.
Practice
1. Decode the flags word 0x8583.
1000 0101 1000 0011: QR = 1 (response), opcode 0, AA = 1, TC = 0, RD = 1, RA = 1, rcode = 3 (NXDOMAIN). That is the second response in the capture.
2. The responses in the capture don't use compression. How many bytes would a pointer to the question name save in response 1?
The answer repeats www.lab.test (14 bytes). A pointer c0 0c (to offset 12, where the question name starts) is 2 bytes, saving 12: the message would be 46 bytes instead of 58.
3. Add a loop guard to name().
Count jumps and raise an error after, say, 10, or require every pointer to point strictly backwards (target < off). Both stop a self-referencing pointer.
Test yourself
Which RCODE means the name doesn't exist?
- 0
- 2
- 3
- 5
What does a DNS compression pointer start with?
- A zero byte
- The two high bits set (11)
- The byte 0x2e ('.')
- The query ID
Why does an NXDOMAIN response include the zone's SOA record?
- To prove the zone is signed
- So resolvers know how long to cache the negative answer
- To list the zone's servers
- It is required for TCP
In the anomaly program, why is the response with ID 0x7777 flagged?
- It is an NXDOMAIN
- It matches no outstanding query
- It came over TCP
- Its TTL is too high