TExcelTAD
Home › Computer Networking › DNS Messages

DNS Messages

DNS uses one compact binary message format for both questions and answers (RFC 1035). In this lesson you build a real DNS query byte by byte, the same bytes dig sends to port 53, and parse a real-format response, including the name compression trick.

Message layout

text
+---------------------+
| Header (12 bytes)   |  ID, flags, and four counts
+---------------------+
| Question            |  the name, type and class being asked about
+---------------------+
| Answer RRs          |  resource records answering the question
+---------------------+
| Authority RRs       |  name servers (for referrals)
+---------------------+
| Additional RRs      |  extra helpful records (e.g. the NS servers' addresses)
+---------------------+

The header's flags field packs several bits:

Bits Name Meaning
1 QR 0 = query, 1 = response
4 Opcode 0 = standard query
1 AA authoritative answer
1 TC truncated (retry over TCP)
1 RD recursion desired (set by clients)
1 RA recursion available (set by resolvers)
4 RCODE 0 = NOERROR, 2 = SERVFAIL, 3 = NXDOMAIN

Encoding a name

Names are not sent as www.example.com. Each label is prefixed by its length, and a zero byte ends the name:

python · try it yourself
def encode_name(name):
    out = b""
    for label in name.rstrip(".").split("."):
        raw = label.encode("ascii")
        if not 1 <= len(raw) <= 63:
            raise ValueError(f"bad label {label!r}")
        out += bytes([len(raw)]) + raw
    return out + b"\x00"

encoded = encode_name("www.example.com")
print(encoded)
print(encoded.hex(" "))
print(len(encoded), "bytes")
b'\x03www\x07example\x03com\x00'
03 77 77 77 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00
17 bytes

Building a query

python · try it yourself
import struct

def encode_name(name):
    return b"".join(bytes([len(p)]) + p.encode() for p in name.rstrip(".").split(".")) + b"\0"

TYPES = {"A": 1, "NS": 2, "CNAME": 5, "MX": 15, "TXT": 16, "AAAA": 28}

def build_query(name, qtype="A", query_id=0x2b1d, recursion=True):
    flags = 0x0100 if recursion else 0x0000           # RD bit
    header = struct.pack("!HHHHHH", query_id, flags, 1, 0, 0, 0)
    question = encode_name(name) + struct.pack("!HH", TYPES[qtype], 1)   # class IN = 1
    return header + question

query = build_query("www.example.com", "A")
print(len(query), "bytes")
print("header:  ", query[:12].hex(" "))
print("question:", query[12:].hex(" "))
33 bytes
header:   2b 1d 01 00 00 01 00 00 00 00 00 00
question: 03 77 77 77 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 00 01 00 01

Those 33 bytes are a complete, valid DNS query. Sent in a UDP datagram to port 53 of a resolver, they would get a real answer. Here's how you could do it on your own machine:

python
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(2)
sock.sendto(query, ("1.1.1.1", 53))
response, _ = sock.recvfrom(512)

Parsing a response

Below is the kind of response a resolver returns for that query. It contains the original question plus one A record. The answer's name is just two bytes, c0 0c: a compression pointer. If the top two bits of a length byte are 11, the remaining 14 bits are an offset into the message where the rest of the name can be found. Offset 12 (0x0c) is the name in the question, so it doesn't need repeating.

python · try it yourself
import socket
import struct

response = bytes.fromhex(
    "2b1d81800001000100000000"                 # header: id, flags, counts
    "03777777076578616d706c6503636f6d00"       # question name: www.example.com
    "00010001"                                 # type A, class IN
    "c00c" "0001" "0001" "00000e10" "0004"     # answer: pointer, A, IN, TTL 3600, length 4
    "5db8d70e"                                 # 93.184.215.14
)

def read_name(msg, offset):
    labels, jumped, end = [], False, None
    while True:
        length = msg[offset]
        if length & 0xC0 == 0xC0:                       # compression pointer
            pointer = struct.unpack("!H", msg[offset:offset + 2])[0] & 0x3FFF
            if not jumped:
                end = offset + 2
            offset, jumped = pointer, True
            continue
        if length == 0:
            return ".".join(labels) + ".", (end if jumped else offset + 1)
        labels.append(msg[offset + 1:offset + 1 + length].decode())
        offset += 1 + length

ident, flags, qd, an, ns, ar = struct.unpack("!HHHHHH", response[:12])
print(f"id=0x{ident:04x} response={bool(flags & 0x8000)} RD={bool(flags & 0x0100)} "
      f"RA={bool(flags & 0x0080)} rcode={flags & 0xF} answers={an}")

name, offset = read_name(response, 12)
qtype, qclass = struct.unpack("!HH", response[offset:offset + 4])
offset += 4
print("question:", name, "type", qtype)

for _ in range(an):
    name, offset = read_name(response, offset)
    rtype, rclass, ttl, rdlength = struct.unpack("!HHIH", response[offset:offset + 10])
    offset += 10
    rdata = response[offset:offset + rdlength]
    offset += rdlength
    value = socket.inet_ntoa(rdata) if rtype == 1 else rdata.hex()
    print(f"answer:   {name} TTL {ttl} type {rtype} -> {value}")
id=0x2b1d response=True RD=True RA=True rcode=0 answers=1
question: www.example.com. type 1
answer:   www.example.com. TTL 3600 type 1 -> 93.184.215.14

The flags 0x8180 decode as: response, recursion desired, recursion available, no error.

Errors: NXDOMAIN

When a name doesn't exist, the response has no answers and RCODE 3 (NXDOMAIN). Decoding just the flags is enough to tell:

python · try it yourself
RCODES = {0: "NOERROR", 1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 5: "REFUSED"}

def describe_flags(flags):
    bits = [name for mask, name in [(0x8000, "QR"), (0x0400, "AA"), (0x0200, "TC"),
                                   (0x0100, "RD"), (0x0080, "RA")] if flags & mask]
    return f"0x{flags:04x} {' '.join(bits):<14} {RCODES[flags & 0xF]}"

for flags in [0x0100, 0x8180, 0x8183, 0x8582, 0x8380]:
    print(describe_flags(flags))
0x0100 RD             NOERROR
0x8180 QR RD RA       NOERROR
0x8183 QR RD RA       NXDOMAIN
0x8582 QR AA RD RA    SERVFAIL
0x8380 QR TC RD RA    NOERROR

0x8380 has the TC (truncated) bit: the answer didn't fit in a UDP datagram, so the client should repeat the query over TCP. Modern DNS uses the EDNS(0) extension to allow UDP answers of around 1232 bytes, which avoids most truncation.

Seeing it on the wire

bash
sudo tcpdump -n -i any -X 'udp port 53' -c 1

Sample output:

text
10:31:07.412870 IP 192.168.1.20.40912 > 1.1.1.1.53: 11037+ A? www.example.com. (33)
        0x0000:  4500 003d 8c31 4000 4011 2b0a c0a8 0114  E..=.1@.@.+.....
        0x0010:  0101 0101 9fd0 0035 0029 8f3e 2b1d 0100  .......5.).>+...
        0x0020:  0001 0000 0000 0000 0377 7777 0765 7861  .........www.exa
        0x0030:  6d70 6c65 0363 6f6d 0000 0100 01         mple.com.....

You can now read the whole packet: an IPv4 header (45, protocol 11 = UDP), a UDP header to port 0035 (53), and then our exact 33-byte query starting with ID 2b1d (11037 in decimal, shown by tcpdump with + for "recursion desired").

Test yourself

How is the name 'mail.example.org' encoded in a DNS message?

  1. As the text mail.example.org followed by a newline
  2. \x04mail\x07example\x03org\x00
  3. As a 4-byte hash
  4. \x10mail.example.org

What do the bytes c0 0c mean where a name is expected?

  1. An error
  2. A pointer to the name at offset 12 in the message
  3. The number 49164 as a TTL
  4. The end of the message

A response has RCODE 3. What does that mean?

  1. The server failed
  2. The query was refused
  3. The name does not exist (NXDOMAIN)
  4. The answer was truncated