SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 20

Cybersecurity Fundamentals · Lesson 20 of 90 · 16 min

DNS and its security

DNS resolutionstub resolverrecursive resolverauthoritative serverroot and TLD serversrecord types (A, AAAA, CNAME, MX, TXT, NS, SOA)TTLcachingDNS spoofing and cache poisoning (concept)DNSSECDNS over HTTPS (DoH)DNS over TLS (DoT)DNS tunnelling detectiondomain hijacking

These are the notes for Cybersecurity Fundamentals (defensive), episode 20. Last episode, TCP learned to reach any program, given an IP address and a port. But people type names, not numbers. Today we invent the Domain Name System (DNS) one problem at a time: DNS resolution with the stub resolver, recursive resolver, root, TLD and authoritative servers; the record types A, AAAA, CNAME, MX, TXT, NS and SOA; caching and TTL; DNS spoofing and cache poisoning; DNSSEC; DNS over TLS (DoT) and DNS over HTTPS (DoH); DNS tunnelling detection; domain hijacking and the registrar lock; and dangling DNS with subdomain takeover. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Ravi, the domains and every log line are made up. example.com, example.net and example.org are reserved for documentation, and the addresses are documentation-only (RFC 5737, RFC 3849). The resolver in these notes is simulated in plain Python: no real DNS server is queried, spoofed or poisoned. Every code sample runs with Python 3.13 (the DNSSEC demo also uses the cryptography package); outputs are real, copied from actual runs. In tracebacks, long file paths are shortened to the file name.

The problems you'll solve

Problem Idea it teaches
People type names; TCP needs numbers Hosts file, why one list can't scale
Ask whoever owns the name DNS resolution, stub and recursive resolvers, root, TLD and authoritative servers, delegation
What can you ask? Zone, record types A, AAAA, CNAME, MX, TXT, NS, SOA
Every lookup asks three servers Caching, TTL
The cache believes the first answer DNS spoofing, cache poisoning, query ID, source port randomisation, the 2008 Kaminsky flaw
Prove the answer is genuine DNSSEC: DNSKEY, RRSIG, DS, chain of trust, "bogus"
Anyone on the Wi-Fi reads your lookups DNS over TLS, DNS over HTTPS
Data smuggled inside names DNS tunnelling, entropy, detection
The name itself is stolen or forgotten Registrar, domain hijacking, registrar/registry lock, dangling DNS, subdomain takeover

Problem 1: names to numbers

Demo 1: the obvious way fails (one address book everywhere)

The obvious way: keep a list of names and IP addresses on every computer. Your computer still has such a file, called hosts (/etc/hosts on Linux and macOS).

# the obvious way: one address book on every computer
HOSTS = {"shop.example.com": "203.0.113.10",
         "mail.example.com": "203.0.113.25"}
# ...but yesterday the shop moved to 203.0.113.77

def lookup(name):
    return HOSTS[name]

print("shop ->", lookup("shop.example.com"), "(old!)")
print("news ->", lookup("news.example.org"))

Output:

shop -> 203.0.113.10 (old!)
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    print("news ->", lookup("news.example.org"))
                     ~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 7, in lookup
    return HOSTS[name]
           ~~~~~^^^^^^
KeyError: 'news.example.org'

Two failures: a stale answer (we would connect to the wrong machine) and a missing name. There is a huge number of names and they change every day; no single list can be complete and fresh on every computer. The answer has to come from whoever owns the name.

How DNS answers: a hierarchy of servers

Think of finding a phone number before smartphones: you ask a friend; the friend calls enquiry; the national office points to the state office, which points to the city office, which has the official directory.

Everyday DNS What it does
You ask a friend Stub resolver A tiny part of your operating system that just asks someone else
The friend does all the calling Recursive resolver A server (your ISP's, your office's, or a public one) that chases the answer for you
National office Root servers Know the servers for every top-level domain
State office TLD servers Know who runs each domain under .com, .in, ...
City directory Authoritative server Holds the official records for one domain, run by the owner or their DNS provider
  • DNS, the Domain Name System, is this whole system of asking (RFC 1034/1035, P. Mockapetris, November 1987).
  • A TLD (top-level domain) is the last part of a name: com, org, in.
  • Delegation means handing a part of the name tree to someone else: the root delegates com to the .com servers, which delegate example.com to its owner's servers.
  • DNS resolution is the whole process of turning a name into an answer.
  • There are 13 root server identities, operated by 12 independent organisations, each copied to many places worldwide (root-servers.org).

A name is read right to left: the invisible root ., then the TLD com, then the domain example, then the label shop. Each part between dots is a label.

Record types: what you can ask

The data for one domain lives in a zone, as records, and every record has a type:

Type Meaning Example
A Name → IPv4 address shop.example.com A 203.0.113.77
AAAA ("quad A") Name → IPv6 address shop.example.com AAAA 2001:db8::77
CNAME (canonical name) This name is an alias of another name www.example.com CNAME shop.example.com
MX (mail exchanger) Which server receives email for the domain (with a priority) example.com MX 10 mail.example.com
TXT Free text: ownership proofs, email anti-spoofing policies example.com TXT "v=spf1 mx -all"
NS (name server) Which servers are authoritative for the domain (how delegation is written) example.com NS ns1.example.com
SOA (start of authority) The zone's admin details: primary server, contact, serial number, timers One per zone

Demo 2: a toy resolver

ROOT = {"com": "the .com TLD server"}      # knows the TLDs
TLD = {"example.com": "ns1.example.com"}   # knows the domains
ZONE = {                                   # the real answers
    ("shop.example.com", "A"): "203.0.113.77",
    ("shop.example.com", "AAAA"): "2001:db8::77",
    ("www.example.com", "CNAME"): "shop.example.com",
    ("example.com", "MX"): "10 mail.example.com",
    ("example.com", "TXT"): "v=spf1 mx -all"}
asked = 0
def resolve(name, rtype):
    global asked
    print("  root: ask", ROOT[name.split(".")[-1]])
    print("  .com: ask", TLD[".".join(name.split(".")[-2:])])
    asked += 3                             # 3 servers asked
    return ZONE[(name, rtype)]

print("A  =", resolve("shop.example.com", "A"))
print("MX =", resolve("example.com", "MX"))
print("servers asked so far:", asked)

Output:

  root: ask the .com TLD server
  .com: ask ns1.example.com
A  = 203.0.113.77
  root: ask the .com TLD server
  .com: ask ns1.example.com
MX = 10 mail.example.com
servers asked so far: 6

The answers are always fresh, because the owner answers. But six servers for two answers would melt the root servers when billions of people look up the same popular names.

Problem 2: caching and TTL

You don't call enquiry every time you want pizza: you write the number on a sticky note. That's a cache: a nearby copy of an answer you already got. But numbers change, so the note says "valid till Sunday". Every DNS record carries a TTL (time to live): how many seconds a resolver may keep it before asking again.

Demo 3: a cache with a TTL

cache = {}                      # name -> (answer, expires at)
asked = 0

def resolve(name, now, ttl=300):
    global asked
    if name in cache and now < cache[name][1]:
        return cache[name][0] + "  (from cache)"
    asked += 3                  # root, TLD, authoritative
    cache[name] = ("203.0.113.77", now + ttl)
    return cache[name][0] + "  (asked 3 servers)"

for t in [0, 5, 120, 299, 300, 301]:   # seconds
    print(f"t={t:3}s  shop ->", resolve("shop.example.com", t))
print("servers asked:", asked)

Output:

t=  0s  shop -> 203.0.113.77  (asked 3 servers)
t=  5s  shop -> 203.0.113.77  (from cache)
t=120s  shop -> 203.0.113.77  (from cache)
t=299s  shop -> 203.0.113.77  (from cache)
t=300s  shop -> 203.0.113.77  (asked 3 servers)
t=301s  shop -> 203.0.113.77  (from cache)
servers asked: 6

Six servers asked instead of eighteen. TTL is a trade-off: long TTLs are fast and cheap but changes spread slowly; short TTLs let you move quickly (useful during an incident). And the catch: the cache trusts whatever it stored, for the whole TTL.

Problem 3: DNS spoofing and cache poisoning

Classic DNS travels over UDP port 53 (episode 19: no handshake). The resolver sends a question carrying a 16-bit query ID, a reference number, and accepts the first reply whose ID (and addresses and ports) match.

  • An attacker can race the real server, sending forged replies with guessed IDs and a fake source address (easy with UDP). A forged DNS reply is DNS spoofing.
  • If a fake wins, it's written into the cache, and every user of that resolver is sent to the attacker's server for the whole TTL. That is cache poisoning: one lie, many victims.

Demo 4: the odds (simulated, no real DNS)

import random
random.seed(4)
IDS = 2 ** 16                     # 16-bit query ID
PORTS = 60999 - 32768 + 1         # random source ports
GUESSES = 100                     # fake replies per race
cache = {}
def race(space):                  # attacker vs real server
    secret = random.randrange(space)
    return secret in random.sample(range(space), GUESSES)

races = 1
while not race(IDS):              # keep forcing new lookups
    races += 1
cache["bank.example"] = "198.51.100.66"  # the fake reply won
print("ID only: poisoned after", races, "races:", cache)

p = GUESSES / (IDS * PORTS)
print(f"ID + random port: {p:.1e} per race,",
      f"about {1 / p:,.0f} races")

Output:

ID only: poisoned after 542 races: {'bank.example': '198.51.100.66'}
ID + random port: 5.4e-08 per race, about 18,502,124 races
  • With only the 16-bit ID, 100 guesses per race succeed after a few hundred races: minutes of work.
  • If the resolver also picks a random source port (here from this Linux machine's ephemeral range, 28,232 ports), the attacker must guess both: about 18.5 million races on average.

Real history: the 2008 Kaminsky flaw

On 8 July 2008 a DNS flaw found by Dan Kaminsky was announced (CVE-2008-1447, US-CERT VU#800113). Asking a resolver for random, made-up names that are never in the cache gave attackers a fresh race every time, and a winning forged reply could carry a fake delegation, so "the bad guy now owns the entire zone" (as an explainer quoted on the BIND users list puts it). Kaminsky worked with a coalition of vendors who released patches simultaneously. The interim fix widened the range of UDP source ports (randomisation); ISC called DNSSEC the only full solution. Randomness only makes guessing harder; we need proof.

Problem 4: DNSSEC

Instead of trusting whoever answers first, trust only answers that carry a real seal. DNSSEC, the DNS Security Extensions (overview: RFC 4033, March 2005), adds digital signatures (episode 16) to DNS:

Record What it is Everyday version
DNSKEY The zone's public key, published in DNS The office's official seal, on display
RRSIG A signature over a set of records (an "RRset") The seal pressed on every letter
DS (delegation signer) A fingerprint of the child zone's key, published and signed in the parent zone The ministry vouching for the office's seal

The chain of trust: the root vouches for .com (DS in the root), .com vouches for example.com (DS in .com), and example.com signs its own records. A validating resolver already trusts the root's key (the trust anchor) and checks every link. An answer that fails validation is called bogus and is dropped.

Demo 5: a simplified DNSSEC check

from cryptography.hazmat.primitives.asymmetric.ed25519 import (
    Ed25519PrivateKey)
from cryptography.exceptions import InvalidSignature

zone_key = Ed25519PrivateKey.generate()   # example.com's secret
dnskey = zone_key.public_key()            # published in DNS
record = b"shop.example.com A 203.0.113.77"
rrsig = zone_key.sign(record)             # signature record

def check(rec):
    try:
        dnskey.verify(rrsig, rec)
        return "valid, cache it"
    except InvalidSignature:
        return "BOGUS, drop it"

print(record.decode(), "->", check(record))
fake = b"shop.example.com A 198.51.100.66"
print(fake.decode(), "->", check(fake))

Output:

shop.example.com A 203.0.113.77 -> valid, cache it
shop.example.com A 198.51.100.66 -> BOGUS, drop it

Ed25519 is a real DNSSEC signing algorithm; real DNSSEC signs records in a precise binary format, with validity dates, but the idea is exactly this: without the zone's private key, a forged record can't carry a valid signature, no matter how many guesses an attacker makes.

What DNSSEC does NOT do

RFC 4033 is explicit: DNSSEC provides origin authentication and integrity; "these extensions do not provide confidentiality", and "DNSSEC does not protect against denial of service attacks". Answers are signed, not secret.

Problem 5: everyone sees your lookups

Demo 6: a DNS question, byte by byte

import struct

def dns_query(name, qid=0x1a2b):        # build it by hand
    header = struct.pack(">HHHHHH", qid, 0x0100, 1, 0, 0, 0)
    labels = b"".join(bytes([len(p)]) + p.encode()
                      for p in name.split("."))
    return header + labels + b"\0" + struct.pack(">HH", 1, 1)

q = dns_query("skin-clinic.example")    # type A, class IN
print(len(q), "bytes on the wire to port 53:")
print(q)
print("readable by anyone on the Wi-Fi:",
      b"skin-clinic" in q)

Output:

37 bytes on the wire to port 53:
b'\x1a+\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x0bskin-clinic\x07example\x00\x00\x01\x00\x01'
readable by anyone on the Wi-Fi: True

How the bytes break down: a 12-byte header (the query ID 0x1a2b, flags 0x0100 = "recursion desired", one question), then the name as length-prefixed labels (\x0b = 11, "skin-clinic"; \x07 = 7, "example"; \x00 = the root), then type 1 (A) and class 1 (IN, Internet). The name is in plain text: anyone on the café Wi-Fi, or along the path, can read every name you look up, and an attacker in the middle could change it. DNSSEC doesn't hide this.

The fix: encrypt DNS

DNS over TLS (DoT) DNS over HTTPS (DoH)
Standard RFC 7858 (May 2016) RFC 8484 (P. Hoffman, P. McManus, October 2018)
Port Its own port, 853 (TCP) 443, the normal HTTPS port
How DNS messages inside a TLS connection DNS messages (application/dns-message) inside HTTPS requests
Looks like Clearly DNS (easy to allow or block) Ordinary web traffic

TLS (Transport Layer Security) is the encryption behind the browser padlock (episode 22). With DoT or DoH, the café Wi-Fi only sees that you talk to a resolver.

Two catches:

  1. The resolver itself still sees every name: choose one you trust.
  2. Because DoH looks like ordinary web traffic, it can bypass a company's DNS security filters and logging. Defenders configure an approved resolver for managed devices and block unknown DoH servers.

Problem 6: DNS tunnelling

Firewalls block most outgoing traffic, but DNS almost always gets through, because everything breaks without it. So malware can smuggle data out inside the names it looks up: it encodes stolen data as long labels under a domain the attacker runs, and the attacker's authoritative server simply collects the questions (and can hide commands in its answers). That is DNS tunnelling.

You can't block every bad domain in advance, but you can measure the names:

  • Length: normal labels are short; encoded data makes long ones.
  • Entropy: a measure of how random-looking a string is, in bits per character. Words repeat letters; encoded data uses many different characters evenly.
  • Volume: many unique names under one rarely used domain.

Demo 7: length and entropy on a made-up log

import math
from collections import Counter

def entropy(s):               # how random-looking? (bits/char)
    n = len(s)
    return sum(c / n * math.log2(n / c)
               for c in Counter(s).values())

log = ["www.example.com", "mail.example.com",  # made up
       "onqwyylspewxg2dfmv2c46dmon4ca4br.t.example.net",
       "onqwyylspewxg2dfmv2c46dmon4ca4bs.t.example.net",
       "api.example.com"]
for q in log:
    first = q.split(".")[0]                # first label
    e = entropy(first)
    flag = "ok"
    if len(first) > 20 and e > 3.5:
        flag = "SUSPICIOUS"
    print(f"{first[:20]:20} len={len(first):2} H={e:.2f} {flag}")

Output:

www                  len= 3 H=0.00 ok
mail                 len= 4 H=2.00 ok
onqwyylspewxg2dfmv2c len=32 H=4.35 SUSPICIOUS
onqwyylspewxg2dfmv2c len=32 H=4.29 SUSPICIOUS
api                  len= 3 H=1.58 ok

The two long labels are base32 (a way to write any bytes using only letters a–z and digits 2–7, which are allowed in DNS names) for salary-sheet.xlsx p1 and ... p2: a file leaving one name at a time. The best structural defence: only your own resolvers may talk DNS to the Internet, so every lookup is logged and checked.

Problem 7: losing the name itself

Domain hijacking and the registrar lock

You register a domain through a registrar, a company that sells and manages names on behalf of the registry (the operator of a TLD). If someone gets into your registrar account, or tricks the registrar, they can transfer the domain or change its NS records: that's domain hijacking, and they now answer for your whole name (website, email, everything).

Defences:

  • Registrar lock: the status clientTransferProhibited makes the registry reject transfer requests until you remove it (ICANN EPP status codes).
  • Registry lock: registry-level statuses such as serverTransferProhibited and serverUpdateProhibited, offered by some registries as a "Registry Lock Service"; removing them needs extra manual steps, which is the point.
  • Strong MFA on the registrar account and a monitored contact email.

Dangling DNS and subdomain takeover

A dangling DNS record is a record, usually a CNAME, that still points to a cloud resource you have deleted. Anyone who then creates a resource with that same name in their own account serves content on your subdomain: a subdomain takeover (Microsoft Learn describes exactly this flow). Your users trust the subdomain, the attacker can even get a valid certificate for it, and cookies scoped to your whole domain may be exposed.

Demo 8: audit the zone against the inventory

# our DNS zone: subdomain -> CNAME target in the cloud
zone = {"www.example.com": "shop-prod.cloudhost.example",
        "blog.example.com": "blog-2023.cloudhost.example",
        "docs.example.com": "docs-v2.cloudhost.example"}

# our cloud inventory: resources we still own today
owned = {"shop-prod.cloudhost.example",
         "docs-v2.cloudhost.example"}     # blog-2023 deleted!

for name, target in zone.items():
    if target in owned:
        print(f"{name:17} -> {target:28} ok")
    else:
        print(f"{name:17} -> {target:28} DANGLING:",
              "anyone can claim it")

Output:

www.example.com   -> shop-prod.cloudhost.example  ok
blog.example.com  -> blog-2023.cloudhost.example  DANGLING: anyone can claim it
docs.example.com  -> docs-v2.cloudhost.example    ok

Fixes: make "remove the DNS record" a step in every shutdown checklist, review zones regularly against the inventory like this, keep a catalogue of names and owners, and use the cloud's domain verification TXT records so only your account can attach your names.

The next problem

DNS gave us the address and TCP connected. Now the browser actually asks for a page and the server answers: requests, responses, headers and cookies. That's HTTP from a security view, next episode.

The whole chain

  1. One big list failed → ask the owner: stub → recursive → root → TLD → authoritative
  2. Too many questions → cache with a TTL
  3. First answer wins → spoofing and cache poisoning; random IDs and ports only slow it down
  4. Prove it → DNSSEC: DNSKEY, RRSIG, DS, chain of trust
  5. Plain-text lookups → DoT (853) and DoH (443)
  6. Data hidden in names → tunnelling detection (length, entropy, volume)
  7. The name itself → registrar/registry lock, dangling DNS audits

...and you just invented DNS, and how to defend it.

Common mistakes (and what they print)

Mistake What you get Why Fix
Hard-coding IPs in a hosts file Stale address, or KeyError: 'news.example.org' Names move; one list can't keep up Resolve through DNS; lower the TTL before a move
Trusting any DNS answer A poisoned cache: users sent to the attacker UDP replies are easy to forge Random IDs and ports; validate DNSSEC
"DNSSEC makes DNS private" Lookups still readable on the wire DNSSEC signs, it doesn't encrypt DoT / DoH to a trusted resolver
Very long TTLs everywhere Changes (and fixes) take days to spread Caches keep answers for the TTL Reasonable TTLs; shorten before planned moves
Letting any device use any resolver Tunnels and DoH bypass your filters DNS to the Internet goes unchecked Force DNS through your own resolvers and log it
Deleting a cloud app but keeping its CNAME DANGLING: anyone can claim it The record outlives the resource Remove records on shutdown; audit zones
No lock or MFA on the registrar account Domain transferred or name servers changed The registrar account controls everything Registrar/registry lock, MFA, monitoring

Mini project: Ravi's DNS log triage

Combine two checks on a made-up resolver log: devices that use an unapproved resolver (possible DoH/DNS bypass) and random-looking long labels (possible tunnelling).

import math
from collections import Counter, defaultdict

APPROVED_RESOLVERS = {"10.0.0.53"}            # our own DNS servers
# made-up log: (client, resolver it used, name asked)
log = [("10.0.1.5", "10.0.0.53", "www.example.com"),
       ("10.0.1.6", "10.0.0.53", "mail.example.com"),
       ("10.0.1.7", "198.51.100.53", "shop.example.com")]
log += [("10.0.1.9", "10.0.0.53", f"{w}.t.example.net") for w in
        ["onqwyylspewxg2dfmv2c46dmon4ca4br", "onqwyylspewxg2dfmv2c46dmon4ca4bs",
         "onqwyylspewxg2dfmv2c46dmon4ca4bt"]]

def entropy(s):
    n = len(s)
    return sum(c / n * math.log2(n / c) for c in Counter(s).values())

findings = defaultdict(list)
for client, resolver, name in log:
    if resolver not in APPROVED_RESOLVERS:
        findings[client].append(f"used unapproved resolver {resolver}")
    first = name.split(".")[0]
    if len(first) > 20 and entropy(first) > 3.5:
        domain = ".".join(name.split(".")[-2:])
        findings[client].append(f"random-looking {len(first)}-char label under {domain}")

for client in sorted({c for c, _, _ in log}):
    issues = findings.get(client, [])
    print(client, "OK" if not issues else f"{len(issues)} issue(s)")
    for issue, n in Counter(issues).items():
        print(f"   - {issue} (x{n})")

Output:

10.0.1.5 OK
10.0.1.6 OK
10.0.1.7 1 issue(s)
   - used unapproved resolver 198.51.100.53 (x1)
10.0.1.9 3 issue(s)
   - random-looking 32-char label under example.net (x3)

Ideas to extend it: add the "many unique names per domain" rule from Practice 3, and output a CSV for the security team.

Practice

1. Homework: add a TXT lookup to the toy resolver, and follow CNAMEs.

Solution
ZONE = {("shop.example.com", "A"): "203.0.113.77",
        ("example.com", "MX"): "10 mail.example.com",
        ("example.com", "TXT"): "v=spf1 mx -all",
        ("www.example.com", "CNAME"): "shop.example.com"}

def resolve(name, rtype):
    if (name, rtype) in ZONE:
        return ZONE[(name, rtype)]
    if (name, "CNAME") in ZONE:                  # follow the alias
        target = ZONE[(name, "CNAME")]
        return f"{target} -> " + resolve(target, rtype)
    return "NXDOMAIN / no such record"

print("TXT  example.com      :", resolve("example.com", "TXT"))
print("A    www.example.com  :", resolve("www.example.com", "A"))
print("A    nope.example.com :", resolve("nope.example.com", "A"))

Output:

TXT  example.com      : v=spf1 mx -all
A    www.example.com  : shop.example.com -> 203.0.113.77
A    nope.example.com : NXDOMAIN / no such record

NXDOMAIN ("non-existent domain") is DNS's real answer code for "this name does not exist".

2. Homework: make the cache use each record's own TTL.

Solution
RECORDS = {"shop.example.com": ("203.0.113.77", 300),   # (answer, TTL)
           "cdn.example.com": ("203.0.113.90", 30)}
cache = {}

def resolve(name, now):
    if name in cache and now < cache[name][1]:
        return cache[name][0] + " (cache)"
    answer, ttl = RECORDS[name]                # the record's own TTL
    cache[name] = (answer, now + ttl)
    return answer + f" (asked, TTL {ttl}s)"

for t in [0, 20, 40, 299, 301]:
    print(f"t={t:3}", resolve("shop.example.com", t), "|",
          resolve("cdn.example.com", t))

Output:

t=  0 203.0.113.77 (asked, TTL 300s) | 203.0.113.90 (asked, TTL 30s)
t= 20 203.0.113.77 (cache) | 203.0.113.90 (cache)
t= 40 203.0.113.77 (cache) | 203.0.113.90 (asked, TTL 30s)
t=299 203.0.113.77 (cache) | 203.0.113.90 (asked, TTL 30s)
t=301 203.0.113.77 (asked, TTL 300s) | 203.0.113.90 (cache)

The short-TTL record is re-asked often; the long one stays cached. The owner of a name controls its TTL.

3. Homework: add a "many unique names per domain" rule to the tunnelling detector.

Solution
from collections import defaultdict
log = ["www.example.com", "mail.example.com", "api.example.com"]
log += [f"q{i:04x}.t.example.net" for i in range(300)]   # made-up burst

per_domain = defaultdict(set)
for q in log:
    domain = ".".join(q.split(".")[-2:])       # last two labels
    per_domain[domain].add(q)

for domain, names in per_domain.items():
    flag = "SUSPICIOUS: many unique names" if len(names) > 100 else "ok"
    print(f"{domain:12} {len(names):4} unique names  {flag}")

Output:

example.com     3 unique names  ok
example.net   300 unique names  SUSPICIOUS: many unique names

The labels here are short and not very random, so the entropy rule alone would miss them; the volume rule catches them. Layers again.

4. Comment question: what does DNSSEC NOT protect?

Answer

Confidentiality (anyone on the path can still read the names and answers) and availability (it doesn't stop denial-of-service attacks, and adds some new costs). It also doesn't help if the domain itself is hijacked at the registrar, or if a dangling record points to a resource someone else now owns: those answers are validly signed by the owner's own zone.

5. Why does random source port selection make cache poisoning so much harder?

Answer

A forged reply must match the query ID and the destination port the resolver used. With 65,536 IDs and about 28,000 ports, the search space grows from 65,536 to about 1.85 billion, so the expected number of races grows by the same factor (542 vs about 18.5 million in Demo 4).

6. A colleague says: "We use DoH on every laptop, so our DNS is secure." What's missing?

Answer

DoH protects the lookup in transit, but: the resolver still sees everything (is it trusted and logged?), answers are not authenticated end to end unless the resolver validates DNSSEC, the company's own DNS filters and logs may be bypassed, and the domains themselves still need registrar locks and dangling-record audits.

Quick quiz

A resolver caches a poisoned record set by the attacker:

bank.example.  86400  IN  A  198.51.100.66

How long can the resolver keep serving it without asking again?

A. 86 seconds B. 1 hour C. 1 day D. Forever

Answer

C. The second field is the TTL in seconds: 86,400 s = 24 hours = 1 day. Attackers pick long TTLs, which is why rejecting forged records up front (DNSSEC validation) matters more than cleaning caches afterwards.

Interview questions

  1. Walk me through what happens when you type a URL and DNS resolves it. The stub resolver asks the configured recursive resolver; if not cached, the recursive asks a root server (referral to the TLD), the TLD server (referral to the domain's NS), then the authoritative server (the answer); the answer is cached for its TTL and returned.
  2. Recursive vs authoritative server? A recursive resolver finds answers on behalf of clients and caches them; an authoritative server holds the official records for a zone.
  3. What are A, AAAA, CNAME, MX, TXT, NS and SOA records? IPv4 address; IPv6 address; alias to another name; mail server; free text (SPF, verification); name servers for the zone; zone administration info.
  4. What is DNS cache poisoning and how is it mitigated? Getting forged answers accepted into a resolver's cache; mitigated by random query IDs and source ports, DNSSEC validation, restricting recursion to your own clients, and monitoring.
  5. What did the 2008 Kaminsky flaw change? Random non-cached names gave unlimited races and forged delegations could take over whole zones, which drove industry-wide source port randomisation and DNSSEC deployment.
  6. What does DNSSEC provide, and what doesn't it? Origin authentication and integrity via signatures (RRSIG, DNSKEY, DS, chain of trust); not confidentiality and not DoS protection.
  7. DoT vs DoH? Both encrypt DNS with TLS; DoT uses port 853 and is easy to identify, DoH uses HTTPS on 443 and blends with web traffic, which helps privacy but can bypass enterprise controls.
  8. How would you detect DNS tunnelling? Long, high-entropy labels; many unique subdomains under one domain; unusual record types (TXT) or volumes; devices using unapproved resolvers.
  9. What is a subdomain takeover and how do you prevent it? A dangling DNS record points to a deprovisioned resource that an attacker claims; prevent it by removing records on decommission, auditing zones against inventory, and using domain verification.
  10. How do you protect a domain from hijacking? Registrar lock (clientTransferProhibited), registry lock for critical domains, MFA on the registrar account, monitored contacts, and alerts on NS changes.

Glossary

Term Meaning in plain words Example
DNS Domain Name System: turns names into addresses and other data shop.example.com → 203.0.113.77
Hosts file A local list of names and addresses on one computer /etc/hosts
DNS resolution The whole process of finding an answer for a name Stub → recursive → root → TLD → authoritative
Stub resolver The tiny resolver in your OS that just asks a recursive resolver Your laptop's DNS client
Recursive resolver A server that chases answers for clients and caches them Your ISP's or office's DNS server
Root servers The top of the tree; refer to the TLD servers 13 identities, 12 operators
TLD Top-level domain: the last label of a name com, org, in
TLD server Knows which servers are authoritative for each domain under a TLD The .com servers
Authoritative server Holds the official records for a zone ns1.example.com
Delegation Handing part of the name tree to another set of servers (NS records) .com → example.com
Label One part of a name between dots shop
Zone The records for one domain (or part of one) example.com
Record (RR) One piece of DNS data with a name, type, TTL and value shop A 203.0.113.77
A / AAAA Name → IPv4 / IPv6 address 2001:db8::77
CNAME This name is an alias of another name www → shop
MX The domain's mail server, with a priority 10 mail.example.com
TXT Free text: ownership proofs, email policies v=spf1 mx -all
NS The authoritative name servers for a zone ns1.example.com
SOA Start of authority: the zone's admin details Serial number, timers
NXDOMAIN DNS's answer for "this name does not exist" nope.example.com
Cache A nearby saved copy of an answer The resolver's memory
TTL Time to live: seconds an answer may be cached 300
Query ID A 16-bit number matching a reply to its question 0x1a2b
DNS spoofing Sending a forged DNS reply A fake A record
Cache poisoning Getting a forged answer stored in a resolver's cache Everyone sent to the attacker
Source port randomisation Using a random UDP port per query so forgers must guess it too 2008 patches
Kaminsky flaw The 2008 DNS poisoning technique using random names (CVE-2008-1447) Multi-vendor patch
DNSSEC DNS Security Extensions: signed DNS answers (RFC 4033) Validating resolvers
DNSKEY A zone's public key record —
RRSIG A signature record over a set of records —
DS Delegation signer: the parent's fingerprint of a child's key In .com for example.com
Chain of trust Each parent vouches for its child's key, up to the root Root → .com → example.com
Trust anchor A key trusted in advance; for DNSSEC, the root key Built into validating resolvers
Bogus DNSSEC's word for an answer that fails validation Dropped
TLS Transport Layer Security: the encryption behind the padlock Episode 22
DoT DNS over TLS, port 853 (RFC 7858) Encrypted DNS
DoH DNS over HTTPS, port 443 (RFC 8484) Browser DNS
DNS tunnelling Smuggling data in DNS names and answers Base32 labels
Entropy How random-looking a string is, in bits per character 4.35 vs 2.00
Base32 Writing bytes with letters a–z and digits 2–7 onqwyyls...
Registrar The company you register and manage a domain through —
Registry The operator of a TLD The .com registry
Domain hijacking Taking control of someone's domain at the registrar or registry Changed NS records
Registrar lock clientTransferProhibited: the registry rejects transfers Removed only when you ask your registrar
Registry lock Registry-level locks needing manual verification to change For high-value domains
Dangling DNS A record pointing to a resource you no longer own blog-2023.cloudhost.example
Subdomain takeover An attacker claims the resource a dangling record points to Content on blog.example.com

Summary

  • DNS turns names into answers by asking the owner: stub → recursive → root → TLD → authoritative, via delegation. Records come in types: A, AAAA, CNAME, MX, TXT, NS, SOA.
  • Resolvers cache answers for their TTL: fast, but they trust what they stored.
  • DNS spoofing races the real server; a win is cache poisoning. Random query IDs and source ports make guessing much harder (the 2008 Kaminsky fix); DNSSEC makes forgeries fail validation.
  • DNSSEC = DNSKEY, RRSIG, DS, chain of trust: integrity and origin, not confidentiality, not DoS protection.
  • Classic DNS is plain text; DoT (853) and DoH (443) encrypt it, but the resolver still sees everything and DoH can bypass company controls.
  • DNS tunnelling hides data in names; detect it by length, entropy and volume, and force DNS through your own resolvers.
  • Protect the name itself: registrar/registry lock and MFA against hijacking; remove records and audit zones against dangling DNS and subdomain takeover.

Next episode: HTTP from a security view: requests and responses, methods, status codes, headers, cookies and sessions, HTTP/2 and HTTP/3, proxies, load balancers and CDNs.

Sources: RFC 1035, Domain Names: Implementation and Specification (P. Mockapetris, Nov 1987); root-servers.org (13 identities, 12 operators); ISC knowledge base AA-00924 on CVE-2008-1447 / VU#800113 (8 Jul 2008); Black Hat webcast page on Kaminsky's DNS discovery; bind-users mailing list, "Understanding Kaminsky exploit" (Apr 2013); RFC 4033, DNS Security Introduction and Requirements (Mar 2005); RFC 7858, DNS over TLS (May 2016); RFC 8484, DNS Queries over HTTPS (Oct 2018); Microsoft Learn, "Prevent dangling DNS entries and avoid subdomain takeover"; ICANN, EPP Status Codes. Code outputs from Python 3.13. Fetched 30 Oct 2026.