Part 3 · Ports, connections and names

How DNS works: resolution, records, DNSSEC and encrypted DNS

lesson 08 / 1919 min1 labpublished updated
Course contents
On this page
  1. The name hierarchy
  2. Resolution: from stub to authoritative
  3. Caching and TTL
  4. Zones and delegation
  5. DNS record types
  6. dig: the main tool
  7. DNS message format and transport
  8. DNSSEC: authenticity, not confidentiality
  9. Encrypted DNS
  10. DNS security and operational pitfalls

In lesson 1 you met DNS as the Internet’s phone book: you give it a name like example.com and it gives you back an IP address. Now that you know how packets, ports and UDP work, this lesson opens the phone book. You’ll see who actually holds the answers, how your computer finds them in a few milliseconds, why changes to DNS “take time to propagate”, and how to ask DNS questions yourself with dig. Programmers can then go one step further and write a DNS client from raw bytes.

DNS (RFC 1034 and RFC 1035) is a distributed, hierarchical database that maps names to records: IP addresses, mail servers, keys and more. Almost every connection on the Internet starts with a DNS query, which is why engineers have a saying: “It’s always DNS.”

The name hierarchy

www.example.com.
|   |       |  `- root (final dot)
|   |       `--- TLD: com
|   `------- second level
`--- subdomain: www
  • Root (.): the top of the tree. The trailing dot is usually left out; the full name written with its trailing dot is an FQDN (fully qualified domain name).
  • TLDs: generic gTLDs (.com, .org, .net), country-code ccTLDs (.ir, .de, .uk), the newer gTLDs (.app, .dev, .shop), and IDNs, which are non-Latin names encoded with Punycode. For example, xn--mgba3a4f16a is Iran’s country TLD written in Persian script.
  • Each level can delegate the management of a subtree to someone else.

Resolution: from stub to authoritative

No single server knows every name. Each domain’s records are kept by its authoritative name servers, the servers that have the final word for that domain. Your computer never talks to them directly; a recursive resolver does the legwork for it:

ResolverRoot.com TLDAuthoritativestub (your OS) asks the recursive resolverA? www.example.comask .com serversA? www.example.comask ns1.example.netA? www.example.comA 203.0.113.10 TTL=300answer cached for 300 s, returned to the stub
A recursive resolver finds the answer with three queries (root, TLD and authoritative) and caches it.
  1. Your program calls getaddrinfo("www.example.com"). The operating system’s stub resolver (glibc, systemd-resolved) first checks /etc/hosts and the local cache (the order is set in /etc/nsswitch.conf), then asks the recursive resolver configured in /etc/resolv.conf.
  2. The recursive resolver belongs to your ISP, your company, or a public service such as 1.1.1.1, 8.8.8.8 and 9.9.9.9. If it doesn’t have the answer cached:
    1. It asks a root server. The answer: “I don’t know, but here are the .com servers” (a referral).
    2. It asks a .com server. The answer: “Here are the name servers for example.com.”
    3. It asks the authoritative server for example.com. The final answer: an A record (the record type that holds an IPv4 address) with a TTL, the number of seconds the answer may be kept.
  3. The resolver caches the answer for the length of its TTL and returns it to the stub.

The stub’s query to the resolver is recursive (“bring me the final answer”). The resolver’s queries to the authoritative servers are iterative: each one only tells you the next step.

Caching and TTL

  • Every record has a TTL in seconds. Until it runs out, resolvers return the answer without asking again.
  • Negative caching: a “this name does not exist” answer (called NXDOMAIN) is cached too, for a time the domain’s owner sets in its SOA record (one of the record types below; RFC 2308).
  • “DNS propagation” isn’t really propagation. It is just waiting for old cached copies in resolvers around the world to expire.

Zones and delegation

A zone is the part of the tree that one group of servers, its authoritative name servers, has the final word on. The parent announces where a child zone lives with NS records. Records are written in the standard zone-file format, one per line: the name, the TTL (how many seconds it may be cached), the class (IN, for Internet, always), the type, and the value. All the types are in the table in the next section.

; in the .com zone (run by its registry)
example.com.  172800 IN NS ns1.example.net.
example.com.  172800 IN NS ns2.example.net.
; name server INSIDE the delegated zone:
; the parent must also hold its address
; (a "glue" record)
example.org.  172800 IN NS ns1.example.org.
ns1.example.org. 172800 IN A 192.0.2.53

Without glue, finding ns1.example.org would mean resolving example.org, which itself needs ns1.example.org: an infinite loop.

DNS record types

TypeContentsNotes
AIPv4 address—
AAAAIPv6 address—
CNAMEAn alias for another nameNo other record may share its name, so not at the apex (example.com); workaround: ALIAS or CNAME flattening
MXThe domain’s mail servers, with prioritiesMust point to a name, not an IP or a CNAME
TXTArbitrary textSPF, DKIM, DMARC, domain ownership checks
NSThe zone’s name serversDelegation
SOAZone info: primary, admin email, serial, refresh, retry, expire, minimumThe serial must go up with every change
PTRReverse DNS: from IP to nameUnder in-addr.arpa (e.g. 4.3.2.1.in-addr.arpa) and ip6.arpa; matters for mail servers
SRVWhere a service lives: priority, weight, port, target_sip._tcp.example.com; Kubernetes, XMPP, LDAP
CAAWhich CAs may issue certificates for the domainSecurity; CAs are required to check it
HTTPS / SVCBConnection info: ALPN (HTTP/3 support), IP hints, ECH keyRFC 9460; browsers use it to discover HTTP/3 and ECH
DS, DNSKEY, RRSIG, NSECDNSSECSee below

CAA and the ECH key in HTTPS records tie DNS to certificates and TLS; the HTTPS record is also how browsers find out a site speaks HTTP/3.

dig: the main tool

dig asks a DNS server a question and prints the whole answer. It’s the tool you’ll use for every DNS problem, so it’s worth learning to read its output:

dig example.com                    # full answer with flags, TTLs and the server used
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 51040
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; QUESTION SECTION:
;example.com.			IN	A

;; ANSWER SECTION:
example.com.		300	IN	A	23.192.228.80
example.com.		300	IN	A	23.192.228.84

;; Query time: 12 msec
;; SERVER: 1.1.1.1#53(1.1.1.1) (UDP)

status: NOERROR means success. Learn to read the flags: qr (this is a response), rd (recursion was requested) and ra (the resolver supports recursion). The 300 is the TTL, so the answer may be cached for 300 seconds. SERVER tells you which resolver answered.

dig +short example.com AAAA        # just the answer
dig @1.1.1.1 example.com MX        # ask a specific resolver
dig +trace example.com             # do the iterative resolution yourself, from the root down
dig +norecurse @a.gtld-servers.net example.com NS   # see a referral (not a final answer)
dig -x 8.8.8.8                     # reverse lookup (PTR)
dig +dnssec cloudflare.com         # RRSIG records and the "ad" (authenticated data) flag
dig example.com SOA +multiline
resolvectl status                  # systemd-resolved: which resolver each interface uses
getent hosts example.com           # resolve exactly as applications do (incl. /etc/hosts)

DNS message format and transport

A DNS message has a 12-byte header followed by four sections: Question, Answer, Authority and Additional. In code, the header is a fixed struct of six 16-bit fields: the ID, the flags and the four section counts.

  • The header holds the ID (16 bits, used to match a reply to its query), the flags QR (query or response), AA (authoritative answer), TC (truncated), RD (recursion desired) and RA (recursion available), and the RCODE.
  • The RCODEs that matter: NOERROR (0), SERVFAIL (2: the resolver couldn’t get an answer, often because of a DNSSEC failure or a dead authoritative server), NXDOMAIN (3: the name does not exist) and REFUSED (5).
  • DNS usually runs over UDP port 53. If the answer is too big, the server sets the TC bit and the client asks again over TCP port 53. Zone transfers (AXFR and IXFR) always use TCP. So don’t block TCP 53.
  • EDNS0 (RFC 6891) allows UDP messages larger than 512 bytes and carries the DNSSEC flag. The recommended size today is 1232 bytes, small enough to avoid fragmentation.
  • Names are encoded as length-prefixed labels (\x07example\x03com\x00). To save space, a repeated name is replaced by a compression pointer: two bytes, starting with the bits 11, that point back to the earlier copy.

DNSSEC: authenticity, not confidentiality

By default, DNS gives you no guarantee that an answer really came from the zone’s owner. DNSSEC signs the records:

  • Each zone publishes its keys in DNSKEY records, and each record set carries an RRSIG signature. There are usually two keys: the KSK (key-signing key, which signs the keys) and the ZSK (zone-signing key, which signs the records).
  • The parent vouches for the child with a DS record, a hash of the child’s key. The chain continues up to the root KSK, the key managed in ICANN’s key-signing ceremonies, which every validating resolver has configured as its trust anchor.
  • NSEC/NSEC3: a signed proof that a name does not exist.
  • If validation fails, the resolver answers SERVFAIL. Expired signatures or a wrong DS record at the registrar are a common cause of site outages.
  • DNSSEC does not encrypt anything. For confidentiality, you need encrypted DNS.

Encrypted DNS

ProtocolTransportPortNotes
Plain DNS (Do53)UDP/TCP53Plaintext; your ISP and anyone on the path can see and change it
DoT (RFC 7858)TLS over TCP853A dedicated port, so it is easy to block
DoH (RFC 8484)HTTPS443Looks like normal web traffic; the default in many browsers
DoQ (RFC 9250)QUIC853 (UDP)Faster, no head-of-line blocking
curl -s -H 'accept: application/dns-json' 'https://cloudflare-dns.com/dns-query?name=example.com&type=A'

DNS security and operational pitfalls

  • Cache poisoning: injecting a forged answer into a resolver’s cache. The Kaminsky attack in 2008 showed that the 16-bit ID alone is not enough, so since then the query’s source port is randomized too (32 bits of entropy combined). DNSSEC is the real fix.
  • DNS amplification: small queries sent with the victim’s spoofed IP trigger large answers that land on the victim. It is a common DDoS tool. Lock down “open” resolvers, the ones that answer anyone in the world.
  • Domain hijacking: someone takes over your registrar account. Use registrar lock and MFA.
  • Subdomain takeover: a CNAME points to a service that no longer exists, such as a deleted bucket or app. An attacker registers the same name on that service and serves their own content on your domain. Delete dangling records.
  • Split-horizon DNS: one name gets different answers for internal and external users (like a private hosted zone in the cloud). Useful, but a source of confusion when you debug.
  • DNS in Kubernetes: remember that ndots:5 and the search domains cause several extra queries for every external name.
  • Caching in applications: some runtimes and connection pools hold on to an IP forever and never see a DNS change. Know how your runtime behaves.