Sub topic 10
DNS Messages and Transport over UDP and TCP
This chapter assumes you know the lookup path from the earlier chapters (stub resolver, recursive resolver, authoritative servers). It also assumes you can read hexadecimal and run Python and dig. Here you will look at the bytes of a DNS query and response, and at how DNS chooses between UDP and TCP.
One message format for queries and responses
DNS uses a single binary message layout for both questions and answers. A message has a fixed 12-byte header followed by four variable-length sections.
| Part | Contents |
|---|---|
| Header | ID, flags, and four counts (12 bytes) |
| Question | The name, type, and class being asked about |
| Answer | Records that answer the question |
| Authority | Usually NS records pointing to the zone's name servers, or an SOA record in negative answers |
| Additional | Extra helpful records, such as glue addresses and the EDNS OPT record |
The header holds six 16-bit fields in this order: ID, flags, QDCOUNT, ANCOUNT, NSCOUNT, ARCOUNT. The four counts say how many entries each section contains.
The ID is chosen by the client and copied into the reply. It lets the client match a reply to its query. It is also a defense against spoofing, because an attacker has to guess it. Resolvers therefore pick IDs randomly and also randomize the UDP source port.
The flags field
The 16 flag bits pack several small fields.
| Field | Bits | Meaning |
|---|---|---|
| QR | 1 | 0 for a query, 1 for a response |
| Opcode | 4 | 0 is a standard query |
| AA | 1 | Authoritative Answer: the responder is authoritative for the name |
| TC | 1 | Truncated: the answer did not fit, so retry over TCP |
| RD | 1 | Recursion Desired: set by the client to ask for full resolution |
| RA | 1 | Recursion Available: set by a server that offers recursion |
| AD | 1 | Authenticated Data: the resolver validated the answer with DNSSEC |
| CD | 1 | Checking Disabled: the client asks the resolver to skip validation |
| RCODE | 4 | Result code |
The common RCODE values are listed below.
| RCODE | Name | Meaning |
|---|---|---|
| 0 | NOERROR | The query succeeded. The answer section may still be empty (this is called NODATA). |
| 1 | FORMERR | The server could not parse the query. |
| 2 | SERVFAIL | The server failed to get an answer, for example because of a broken delegation or a DNSSEC failure. |
| 3 | NXDOMAIN | The name does not exist. |
| 5 | REFUSED | The server refuses to answer you, often because of an access policy. |
NXDOMAIN and NODATA are different. NXDOMAIN means no record of any type exists for the name. NODATA means the name exists but has no record of the type you asked for. For example, a host with only an A record returns NODATA for an AAAA query.
Building a query by hand
The script below builds a query for an A record, sends it over UDP, and decodes the response header. Replace the resolver address if you prefer another one.
import secrets
import socket
import struct
RESOLVER = "1.1.1.1"
def build_query(name, qtype=1):
ident = secrets.randbits(16)
flags = 0x0100 # RD=1, everything else 0
header = struct.pack("!HHHHHH", ident, flags, 1, 0, 0, 0)
labels = name.rstrip(".").split(".")
qname = b"".join(bytes([len(l)]) + l.encode("ascii") for l in labels) + b"\x00"
question = qname + struct.pack("!HH", qtype, 1) # class 1 = IN
return ident, header + question
def parse_header(data):
ident, flags, qd, an, ns, ar = struct.unpack("!HHHHHH", data[:12])
return {
"id": ident,
"qr": flags >> 15,
"opcode": (flags >> 11) & 0xF,
"aa": (flags >> 10) & 1,
"tc": (flags >> 9) & 1,
"rd": (flags >> 8) & 1,
"ra": (flags >> 7) & 1,
"ad": (flags >> 5) & 1,
"rcode": flags & 0xF,
"counts": (qd, an, ns, ar),
}
ident, query = build_query("example.com")
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(3)
s.sendto(query, (RESOLVER, 53))
data, _ = s.recvfrom(4096)
info = parse_header(data)
print("ID matches:", info["id"] == ident)
print(info)Expect qr to be 1, rd and ra to be 1, and rcode to be 0. The counts show one question and at least one answer.
Names on the wire
A name is encoded as a series of labels. Each label is a length byte followed by that many characters. A zero byte ends the name. So example.com becomes 07 example 03 com 00.
Responses often repeat names, so DNS uses compression. A two-byte pointer starting with the bits 11 says "continue reading the name at this offset from the start of the message". The answer record's name is usually the pointer C0 0C, which points to offset 12, where the question's name begins. A parser must follow pointers and must guard against loops. Malformed pointer loops are a classic source of parser bugs.
Transport: UDP first, TCP when needed
DNS servers listen on port 53 for both UDP and TCP. The default is UDP, because a lookup is one small request and one small reply. UDP needs no handshake, so a lookup costs one round trip and the server keeps no connection state.
Size limits and truncation
The original standard limited UDP responses to 512 bytes. If an answer did not fit, the server set the TC bit and returned what fit, possibly with an empty answer section. The client then repeated the query over TCP.
EDNS(0) removes most of this limit. The client adds an OPT pseudo-record to the additional section. The record advertises the largest UDP payload the client can accept. It also carries extended flags, including the DO bit, which asks for DNSSEC records. OPT is not a real record in a zone. It only carries parameters for this one exchange.
Large UDP messages are fragmented at the IP layer, and fragments are often dropped by firewalls. Fragments can also be forged more easily. Since the 2020 DNS Flag Day, the common recommendation is to advertise about 1232 bytes. That value fits in a 1280-byte IPv6 minimum MTU, so it avoids fragmentation.
TCP framing
TCP is a byte stream with no message boundaries. DNS therefore prefixes every message with a 2-byte length, so a TCP message can be at most 65535 bytes. The same message format follows the prefix.
import socket
import struct
def recv_exact(sock, n):
buf = b""
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("connection closed early")
buf += chunk
return buf
def query_tcp(query, server="1.1.1.1"):
with socket.create_connection((server, 53), timeout=5) as s:
s.sendall(struct.pack("!H", len(query)) + query)
(length,) = struct.unpack("!H", recv_exact(s, 2))
return recv_exact(s, length)Call query_tcp(query) with the query bytes built earlier. It returns the full response, which parse_header can decode. TCP is also used for zone transfers (AXFR and IXFR), which copy a whole zone between servers. Zone transfers can be far larger than any UDP packet. Modern servers also use TCP when they must answer large DNSSEC responses, and they keep TCP connections open for several queries.
Seeing it with dig
dig shows header flags and the EDNS pseudo-section. The first command forces TCP. The second advertises a 512-byte buffer and ignores truncation, so you can see the TC flag in the header line for a large answer such as DNSKEY.
dig +tcp example.com A
dig +bufsize=512 +ignore example.com DNSKEYIn the output, the ;; flags: line lists the flags (qr rd ra, and tc if truncated). The status: field shows the RCODE. The ;; OPT PSEUDOSECTION shows the advertised UDP size. The ;; MSG SIZE rcvd line gives the response length in bytes.
Common errors
- Treating an empty answer as an error. NOERROR with zero answers is NODATA, and it is a valid result.
- Ignoring the ID and source port when writing a client. Accepting any reply makes spoofing easy.
- Assuming 512 bytes is still the limit. Clients and servers use EDNS, and a stale firewall rule limiting DNS to 512 bytes breaks DNSSEC.
- Reading a TCP response with a single
recv. The stream may deliver the message in pieces, so read exactly the number of bytes the length prefix gives.
Exercise
A client sends a query over UDP and gets a response with TC=1 and an empty answer section. What should it do, and what framing detail matters on the next attempt?
Show answer
It should repeat the same question over TCP to port 53 on the same server. On TCP, each message is preceded by a 2-byte big-endian length field, and the client must read exactly that many bytes for the response.
Exercise
A query for the name shop.example.com returns RCODE NOERROR with ANCOUNT 0 when you ask for AAAA, but returns an address when you ask for A. Is the name missing? Explain.
Show answer
No. The name exists, so the server does not return NXDOMAIN. It has no AAAA record, so the answer is NODATA: NOERROR with an empty answer section.