DNS Deep Dive
Breadth layernotes-security-core-knowledge.md
What DNS Does
DNS (Domain Name System) translates human-readable names (www.example.com) into IP addresses (93.184.216.34). It is a globally distributed, hierarchical, eventually-consistent database.
Why it matters for security
- Almost every network connection starts with a DNS lookup — DNS is a universal visibility point.
- DNS is trusted implicitly by most applications. Poisoning or hijacking it redirects all traffic.
- Attackers abuse DNS for C2 (DNS tunnelling), data exfiltration (encode data in subdomains), and DGA (generate unpredictable domains to evade blocklists).
DNS Hierarchy and Zones
. ← Root zone (13 root server clusters: a.root-servers.net … m.root-servers.net)
├── com. ← TLD (Top-Level Domain) — operated by Verisign
│ ├── example.com. ← Authoritative zone — operated by the domain owner
│ │ ├── www.example.com.
│ │ ├── mail.example.com.
│ │ └── _dmarc.example.com.
│ └── google.com.
├── org.
├── net.
└── uk.
└── co.uk.Zonea contiguous portion of the namespace that a single entity is authoritative for. A zone file contains all the records for that zone.
Delegationthe .com TLD nameserver doesn't hold all example.com records — it delegates by returning NS records pointing to example.com's authoritative nameservers. This delegation is how the hierarchy scales.
Memory hookwhy exactly 13 root servers?There are 13 root server names (
athroughm), not 13 machines. The number 13 comes from the original 512-byte UDP packet limit: 13 named IPv4 server addresses plus the DNS overhead was the most that fit in a single non-fragmented UDP response. Today each letter is actually hundreds of physical servers sharing one IP via anycast (the network routes you to the nearest one). So "13 root servers" really means "13 anycast addresses backed by 1000+ machines." This is a classic interview gotcha — interviewers love when you correct the "13 computers" myth.
Resolution — Step by Step
When your browser resolves www.example.com for the first time:
Browser → OS resolver (stub resolver)
→ checks /etc/hosts (local override file)
→ checks local DNS cache
→ queries Recursive Resolver (usually your ISP or 8.8.8.8 or 1.1.1.1)
Recursive Resolver (if not cached):
1. Query root servers: "Who handles .com?"
Root → NS records for .com (a.gtld-servers.net, etc.)
2. Query .com TLD servers: "Who handles example.com?"
.com TLD → NS records for example.com (ns1.example.com, ns2.example.com)
3. Query example.com authoritative nameserver: "What is www.example.com?"
NS → A record: www.example.com → 93.184.216.34
4. Return answer to stub resolver → browser → TCP connection to 93.184.216.34Total round-trips for a cold lookuptypically 3 UDP queries + 3 UDP responses (one per delegation level). With caching at each level, most queries are answered in 1 round-trip.
Memory hookrecursive vs. iterativeThe stub resolver (your OS) asks the recursive resolver "just get me the answer, I'll wait" — that's recursion. The recursive resolver then does the legwork by asking root → TLD → authoritative, each of which answers "I don't know, but ask them" — that's iteration. Mnemonic: you are lazy (recursive), the resolver does the walking (iterative). Only the recursive resolver sets the RD (Recursion Desired) flag and expects a full answer; root/TLD servers never recurse for you.
UDP vs TCP
- DNS typically uses UDP port 53 (low overhead, most responses fit in ≤512 bytes)
- TCP port 53 is used when:
- Response exceeds 512 bytes (the original limit; EDNS0 extends this to 4096 bytes over UDP)
- Zone transfers (AXFR/IXFR) — always TCP
- DNSSEC responses (large signatures)
- DoT (DNS over TLS) — always TCP/853
Record Types Reference
| Type | Purpose | Example |
|---|---|---|
| A | IPv4 address | www.example.com. 300 IN A 93.184.216.34 |
| AAAA | IPv6 address | www.example.com. 300 IN AAAA 2606:2800:220:1:248:1893:25c8:1946 |
| CNAME | Canonical name alias | blog.example.com. 300 IN CNAME example.com. (can't coexist with other types at apex) |
| MX | Mail server (with priority) | example.com. 300 IN MX 10 mail.example.com. |
| NS | Authoritative nameservers for a zone | example.com. 86400 IN NS ns1.example.com. |
| TXT | Arbitrary text; used for SPF, DKIM, DMARC, domain verification | example.com. 300 IN TXT "v=spf1 include:_spf.google.com ~all" |
| SOA | Start of Authority — zone metadata (serial, refresh, retry, expire, min TTL) | One per zone; defines the primary NS and timing parameters |
| PTR | Reverse DNS — IP → name | 34.216.184.93.in-addr.arpa. IN PTR www.example.com. |
| SRV | Service discovery (port + priority + weight) | _https._tcp.example.com. IN SRV 0 5 443 www.example.com. |
| CAA | Certification Authority Authorisation — which CAs may issue certs for the domain | example.com. IN CAA 0 issue "letsencrypt.org" |
| DNSKEY | DNSSEC public key | Holds the zone-signing key (ZSK) or key-signing key (KSK) |
| DS | Delegation Signer — hash of child zone's KSK, stored in parent zone | Establishes the chain of trust across zone boundaries |
| RRSIG | DNSSEC signature over a record set | Covers all records of the same type and name |
| NSEC/NSEC3 | DNSSEC proof of non-existence | Proves a name/type does not exist; NSEC3 uses hashes to prevent zone walking |
SPF / DKIM / DMARC (Email Authentication)
# SPF — who is authorised to send email for this domain
example.com. IN TXT "v=spf1 ip4:203.0.113.0/24 include:_spf.google.com -all"
# -all = hard fail (reject); ~all = soft fail (mark as spam); +all = allow all (terrible)
# DKIM — public key for verifying mail signatures
selector._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCS..."
# DMARC — policy: what to do when SPF/DKIM fail
_dmarc.example.com. IN TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100"
# p=reject: reject mail that fails DMARC alignment
# rua: aggregate report destinationMemory hookhow the three fit togetherThink of sending a letter: SPF checks the envelope's return address (is this server allowed to send for the domain?). DKIM is a tamper-proof wax seal (a cryptographic signature proving the message wasn't altered in transit). DMARC is the company policy telling the recipient what to do if the address or seal don't match — and it requires "alignment" (the visible From: domain must match what SPF/DKIM checked). Mnemonic: SPF = sender, DKIM = signature, DMARC = decision. The killer fact: SPF and DKIM alone do nothing on failure; only DMARC tells the receiver to actually reject.
Memory hookSPF qualifiersThe character before
allis the verdict for everything not explicitly listed:-all= fail/reject (the strict, correct choice),~all= softfail/quarantine,?all= neutral,+all= allow anything (effectively disables SPF — a misconfiguration attackers love). Remember: minus is the meanest, plus is the most permissive (and most dangerous).
DNS Message Format
DNS Message (UDP datagram): ┌─────────────────────────────────────────────────────┐ │ ID (16 bits) — transaction ID, matched in response │ │ Flags (16 bits): │ │ QR (1): 0=query, 1=response │ │ Opcode (4): 0=standard, 1=inverse, 2=status │ │ AA: Authoritative Answer │ │ TC: Truncated (use TCP) │ │ RD: Recursion Desired (set by client) │ │ RA: Recursion Available (set by resolver) │ │ Z: reserved │ │ RCODE (4): 0=NoError, 1=FormErr, 2=ServFail, │ │ 3=NXDomain, 5=Refused │ │ QDCOUNT — number of questions │ │ ANCOUNT — number of answer records │ │ NSCOUNT — number of authority records │ │ ARCOUNT — number of additional records │ ├─────────────────────────────────────────────────────┤ │ Question section: QNAME, QTYPE, QCLASS │ │ Answer section: resource records matching query │ │ Authority section: NS records (for delegation) │ │ Additional section: A/AAAA for NS names (glue) │ └─────────────────────────────────────────────────────┘
RCODE values
0 NOERROR— success2 SERVFAIL— resolver couldn't get an answer (network error, DNSSEC validation failure)3 NXDOMAIN— name does not exist (definitive non-existence from the authoritative server)5 REFUSED— server refuses to respond (access control)
Caching and TTL
Every DNS record has a TTL (Time To Live) in seconds. Resolvers cache responses for the TTL duration and don't query upstream again until it expires.
www.example.com. 300 IN A 93.184.216.34
^^^
TTL = 300 seconds (5 minutes)TTL trade-offs
- Short TTL (30–300s): changes propagate quickly; more DNS queries (more load, more latency for cold lookups)
- Long TTL (3600–86400s): fewer queries; stale cache persists longer during outages or IP changes
Negative cachingNXDOMAIN responses are also cached for the SOA's minimum TTL. This means DNS-based blocklists can be bypassed if the resolver already cached a positive answer.
TTL 0bypass resolver caching entirely. Used for health-check-driven failover, but causes high DNS load.
DNS Security Extensions (DNSSEC)
DNSSEC adds cryptographic signatures to DNS records to prevent tampering and spoofing. It does not provide confidentiality (responses are still plaintext).
Memory hookDNSSEC ≠ encryptionThis is the most-tested DNSSEC fact. DNSSEC is about authenticity and integrity (this answer really came from the domain owner and wasn't altered), not confidentiality (anyone on the path still sees your queries in plaintext). For privacy you want DoH/DoT instead. Mnemonic: DNSSEC signs, DoH/DoT hides. A subtle second fact: NSEC records (proof a name doesn't exist) accidentally let attackers "walk" the entire zone by following the chain of next-secure pointers — which is exactly why NSEC3 hashes the names.
Memory hookthe two keysKSK = King (signs only the keys, rarely rotated, its hash lives in the parent as a DS record). ZSK = Zealous worker (signs all the actual records, rotated often). The KSK delegates trust downward to the ZSK so you can rotate the busy ZSK monthly without ever bothering the registrar/parent.
How It Works
Zone signs its records with a private ZSK (Zone Signing Key):
A record + RRSIG(ZSK) → published in the zone
ZSK's public key is published as a DNSKEY record.
ZSK public key is signed by the KSK (Key Signing Key):
DNSKEY(ZSK) + RRSIG(KSK) → proves ZSK is authentic
KSK's fingerprint (DS record) is published in the PARENT zone:
Parent zone holds DS record → signed by parent's KSK
Chain of trust extends from the root:
Root (KSK in all resolvers as a trust anchor)
→ .com KSK (DS in root zone)
→ example.com KSK (DS in .com zone)
→ example.com ZSK (DNSKEY in example.com zone)
→ A records (RRSIG in example.com zone)Validationa DNSSEC-aware resolver builds and validates this chain on every lookup. If any signature is invalid or missing, the resolver returns SERVFAIL.
Key Management
done frequently (monthly) without parent involvement — new DNSKEY published, both keys active during transition (TTL overlap), old key removed.
requires updating the DS record in the parent zone — coordinated with the registrar. Rare (annual or less).
Algorithms
DNSSEC supports several signing algorithms (the DNSKEY/RRSIG "algorithm number"):
| Algorithm | Notes |
|---|---|
| RSA/SHA-256 (alg 8) | Most common historically; large keys/signatures |
| RSA/SHA-512 (alg 10) | Higher margin, even larger |
| ECDSA P-256/SHA-256 (alg 13) | Recommended today — much smaller signatures than RSA → less amplification, smaller responses |
| ECDSA P-384 (alg 14) | Higher security margin |
| Ed25519 (alg 15) / Ed448 (alg 16) | Modern EdDSA; deterministic, compact (adoption growing) |
Memory hookprefer ECDSA/EdDSA over RSA for DNSSECIt's not just "modern crypto" — RSA's huge signatures bloat DNS responses, which (a) push responses past UDP limits forcing TCP/fragmentation and (b) make DNSSEC a bigger DDoS amplification weapon (see below). ECDSA P-256 signatures are a fraction of the size, so the practical advice is "sign with algorithm 13."
Validation States (what a resolver concludes)
A validating resolver classifies every answer into one of four states — know these terms:
| State | Meaning |
|---|---|
| Secure | A valid signature chain to the trust anchor exists and verifies |
| Insecure | The zone simply isn't signed (no DS in parent) — legitimately unprotected, not an error |
| Bogus | Signatures exist but are invalid/expired/broken chain → resolver returns SERVFAIL |
| Indeterminate | Resolver can't determine (no trust anchor path) |
Memory hook"Bogus = SERVFAIL, and that's a real-world outage cause." The #1 operational DNSSEC pain: expired RRSIG signatures (signatures have a validity window and must be re-signed). Forget to re-sign and your perfectly-running zone goes Bogus → SERVFAIL → site offline for every validating resolver — this has taken down major domains. DNSSEC fails closed, so a key/signature mistake is an outage, which is a big reason adoption stays low.
NSEC vs NSEC3 — proving non-existence (and zone walking)
DNSSEC must also sign the absence of a record (you can't sign "this doesn't exist" on the fly without exposing the private key online), so it pre-signs gaps between names:
returns "the next name after a.example.com is c.example.com" — proving b doesn't exist. Side effect: you can walk the entire zone by repeatedly asking for names and following the NSEC chain — full zone enumeration for free.
hashes the names before chaining them, so you get the proof without handing out a plaintext list. Caveat: NSEC3 is still offline-crackable — tools like nsec3walker/hashcat brute-force the hashes, so it raises the cost of enumeration rather than preventing it. NSEC3 opt-out also exists to reduce signing overhead for large delegation-only zones (like TLDs).
The Root Trust Anchor & KSK Rollover
The whole chain roots in the root zone KSK, baked into validating resolvers as the trust anchor. The root KSK was rolled for the first time ever in October 2018 (from KSK-2010 to KSK-2017) — a globally coordinated, nerve-wracking event because any resolver with a stale trust anchor would break. RFC 5011 defines automated trust-anchor updates so resolvers can track rollovers.
DANE — using DNSSEC to authenticate TLS
DANE (DNS-based Authentication of Named Entities, RFC 6698) publishes a TLSA record stating "the cert for this host should be this one (or from this CA)." Because DNSSEC makes the record trustworthy, DANE lets you pin certificates via DNS instead of trusting the ~150 public CAs — defeating a rogue-CA misissuance. Widely used for SMTP/email (MTA-STS's cousin); rare for the web because browsers never adopted it (they rely on CT + the CA system instead).
DNSSEC's Downsides (be ready to critique it)
it signs, it doesn't encrypt (that's DoH/DoT). The most-tested fact.
signed responses are large, so DNSSEC-enabled resolvers are potent reflection/amplification weapons (a small spoofed query → a huge signed reply aimed at a victim). DNSSEC arguably made DNS a better DDoS tool.
expired signatures / botched key rollovers fail closed (SERVFAIL = outage). This is the main reason adoption is still low (well under half of zones).
ZSK/KSK lifecycle, DS coordination with registrars, re-signing schedules.
NSEC walking / NSEC3 cracking leaks the zone contents.
DNS over HTTPS / TLS
Traditional DNS sends queries in plaintext — ISPs, network admins, and attackers on the path can see every domain you query.
| Protocol | Port | Transport | Encrypted | Notes |
|---|---|---|---|---|
| DNS (plain) | 53 | UDP/TCP | No | Default everywhere |
| DoT (DNS over TLS) | 853 | TCP | Yes | IETF RFC 7858; kernel/resolver configured |
| DoH (DNS over HTTPS) | 443 | TCP | Yes | RFC 8484; looks like HTTPS traffic; used by browsers |
| DoQ (DNS over QUIC) | 853 | UDP/QUIC | Yes | RFC 9250; fast connection setup |
DoH vs DoT security trade-offs
- DoH blends in with HTTPS traffic → harder for enterprise to monitor/block
- DoT is easier to identify (port 853) → enterprise can proxy/inspect it
- Both break DNS-based blocking if the client uses an external resolver (8.8.8.8, 1.1.1.1)
DNS Attacks
Cache Poisoning (Kaminsky Attack)
Attacker races to inject a forged response into a resolver's cache before the real answer arrives.
1. Attacker sends many queries for random.example.com to the resolver
2. Attacker simultaneously floods the resolver with forged responses
with random transaction IDs — hoping to match one of the 65,536 IDs
3. Forged response also replaces the NS record for example.com
→ resolver now uses attacker's NS for all example.com queriesMitigations
2^16 ports × 2^16 transaction IDs = 2^32 combinations to brute-force
signature mismatch causes SERVFAIL regardless of forged content
randomise case in the query (eXaMpLe.CoM); authoritative servers echo it back; mismatch rejects the response
Memory hookwhy Kaminsky (2008) was a big deal. Before Dan Kaminsky's attack, resolvers only randomised the 16-bit transaction ID — just 65,536 guesses, brute-forceable in seconds. His twist: instead of poisoning one record, query for a random nonexistent subdomain and forge a response that also overwrites the NS record for the whole domain — poisoning everything at once, and you get unlimited fresh attempts because each random subdomain isn't cached yet. The emergency fix (source-port randomisation) multiplied the guesses to ~2^32. Remember: Kaminsky turned "one bad record" into "own the whole domain," and the patch was randomising the source port.
DNS Tunnelling / C2
DNS is almost never blocked by firewalls. Attackers encode data in DNS queries and responses to tunnel a C2 channel through DNS:
# Exfiltrating data via DNS subdomain encoding
# Encode "secret_data" in base32 → split into ≤63-char labels
MFRA.TORY.MJQXE.c2.attacker.com ← encoded payload in subdomains
# Tools: dnscat2, iodine, dns2tcpDetection
- High volume of TXT, NULL, or CNAME queries to a single domain
- Long subdomain labels (>30 chars) — legitimate hostnames are short
- High query rate for non-existent subdomains (data exfil over NXDOMAIN responses)
- Use entropy analysis on subdomain labels (base32/base64 has uniform character distribution)
Domain Generation Algorithms (DGA)
Malware generates a pseudorandom domain list daily using a seed (often the current date). The attacker registers only the one that will be active. Detection/blocking a hardcoded domain doesn't work.
# Simple DGA example (Conficker-style)
import datetime, hashlib
def dga(date, count=5):
for i in range(count):
seed = f"{date.strftime('%Y%m%d')}{i}".encode()
h = hashlib.md5(seed).hexdigest()
yield h[:12] + ".com"
for domain in dga(datetime.date.today()):
print(domain)DetectionNXDomain storms (many failed resolutions in bursts), high lexical entropy in domain names, machine learning on domain name features.
DNS Rebinding
Used to bypass Same-Origin Policy and access internal network resources via a victim's browser.
1. Victim visits attacker.com — DNS returns attacker's real IP
2. Attacker's server responds with a tiny HTML page + JS
3. Attacker sets DNS TTL to 0 or very short; re-registers attacker.com → 192.168.1.1
4. JS makes a same-origin request to attacker.com — browser resolves it now to 192.168.1.1
5. JS reads the response from the internal router/camera/API
6. Router does not implement Host header validation → treats it as a legitimate requestMitigationsDNS rebinding protection in routers/proxies (block external domains resolving to RFC 1918 addresses), validate Host header on internal services, use HTTPS with valid certs (invalid cert = browser warning).
NXDOMAIN Hijacking
ISPs and DNS providers redirect NXDOMAIN responses to their own ad pages or search portals — changes the DNS contract ("this domain does not exist") to profit. Also used by attackers who compromise resolvers.
Subdomain Takeover
example.com CNAME cdn.example.cloud (points to a CDN bucket)
→ CDN bucket is deleted / not claimed
→ Attacker creates the bucket → now controls content served at example.com subdomain
→ Can host phishing pages with a trusted certificate and originDetectionscan for CNAMEs pointing to unclaimed resources (Azure, AWS S3, GitHub Pages, Heroku, Fastly fingerprints).
Real-World Case Study: The Mirai Botnet & the Dyn DNS Attack
Mirai is the most important DNS-DDoS story and a landmark IoT-security event — worth knowing in detail because it ties together botnets, DDoS, default-credential abuse, and DNS as a single point of failure.
What Mirai was
Mirai (2016) was an IoT botnet that infected hundreds of thousands of internet-connected devices — IP cameras, DVRs, home routers, baby monitors — not PCs. It spread with brute-force simplicity:
1. Each bot scans the internet for open Telnet (23/2323) — sometimes SSH
2. Tries a hardcoded table of ~60 default credentials (admin/admin, root/12345,
root/xc3511, support/support — factory defaults IoT vendors never changed)
3. On success, reports the device + working creds to a ScanReceiver/report server
4. A "loader" logs in, identifies the CPU arch, and pushes the matching Mirai binary
5. The new bot kills competing malware, hides, and awaits C2 attack commands
— it ran in memory only, so a reboot cleaned a device... until it was reinfected
within minutes by the constant scanningMemory hookMirai weaponized "the password is still
admin." It carried no exploits — just a list of factory-default credentials for IoT gear that users never changed and vendors hardcoded. That's the whole lesson: default creds + internet-exposed management + millions of unpatched IoT devices = a botnet bigger than any prior DDoS source. It's why "change default credentials" and "don't expose Telnet" are IoT security gospel, and why regulations now ban default passwords on IoT.
The attacks
~620 Gbps, then the largest DDoS ever seen, knocked security journalist Brian Krebs offline (Akamai dropped the pro-bono protection because it was too costly).
~1+ Tbps against the French host.
the famous one: Mirai hammered Dyn, a major managed-DNS provider, with a massive DDoS. Because Dyn provided authoritative DNS for huge customers, taking Dyn down took out the DNS resolution for Twitter, Reddit, Netflix, Spotify, GitHub, Airbnb, PayPal, and more across the US/Europe — even though those sites themselves were perfectly healthy.
Memory hookDyn proved DNS is a single point of failure. The sites weren't attacked; their DNS provider was. If users can't resolve your name, your servers being up is irrelevant. The takeaway that every architecture interview rewards: use multiple, independent DNS providers (secondary DNS) so one provider's outage doesn't take you offline — a lesson the whole industry learned from Dyn.
Mirai's DDoS techniques (incl. a DNS-specific one)
Mirai supported ~10 attack vectors: SYN/ACK floods, UDP floods, GRE floods, HTTP floods — and a DNS-specific one:
- DNS Water Torture (random subdomain attack): bots query random, non-existent subdomains of the target's domain (
a8f3x9.victim.com,q2m1.victim.com). These can't be cached (each is unique) and force the victim's authoritative servers to do work answering NXDOMAIN, exhausting them. This is the DNS attack referenced in the DNS Tunnelling/abuse discussion's evil twin — and it's why a flood of NXDOMAINs for random subdomains is a DDoS signal, not just a DGA one.
The aftermath & why it still matters
- The author published Mirai's source code (Sept 2016) under the handle "Anna-senpai," spawning countless variants (Satori, Okiru, Mozi, etc.) that still operate today.
- The authors — Paras Jha, Josiah White, Dalton Norman — were identified and pleaded guilty (2017); their original motive was mundane (DDoS-for-hire and gaining advantage in Minecraft server-protection rackets), not nation-state.
- It permanently changed thinking on IoT security, DDoS scale (terabit attacks became normal), and DNS resilience.
Defenses the Mirai era cementedanycast + DDoS-scrubbing for DNS (Cloudflare, Akamai, Google), secondary/multi-provider DNS, IoT default-credential bans (e.g. California SB-327, UK PSTI), egress filtering of Telnet, and BCP 38 anti-spoofing.
Defensive DNS
log all DNS queries per client; feeds into SIEM for threat detection
redirect known malicious domains (C2, DGA families) to an internal sinkhole IP; client still connects, you log the infected host
BIND/Unbound feature for DNS-based blocking: replace responses for listed domains with NXDOMAIN or a sinkhole IP
enable on recursive resolvers (dnssec-validation auto in BIND)
except to authorised resolvers — forces all DNS through monitored resolvers; prevents DNS tunnelling over external resolvers
Diagnostic Commands
# Basic A record lookup
dig www.example.com
dig A www.example.com @8.8.8.8 # query specific resolver
# Trace full resolution path (shows all delegations)
dig +trace www.example.com
# Reverse DNS (PTR)
dig -x 93.184.216.34
# MX records
dig MX example.com
# SOA record (zone info)
dig SOA example.com
# DNSSEC — check if validation works
dig +dnssec www.example.com
dig DS example.com @a.root-servers.net # DS record at parent
# Check DMARC/SPF/DKIM
dig TXT _dmarc.example.com
dig TXT example.com # SPF
dig TXT selector._domainkey.example.com # DKIM public key
# Zone transfer attempt (should fail on public domains)
dig AXFR example.com @ns1.example.com
# nslookup (simpler, interactive)
nslookup www.example.com
nslookup -type=MX example.com
# host (brief output)
host www.example.com
host -t MX example.com
# Check what resolver a host uses
cat /etc/resolv.conf
resolvectl status # systemd-resolved
# Test DoH (DNS over HTTPS)
curl -H 'accept: application/dns-json' 'https://cloudflare-dns.com/dns-query?name=example.com&type=A'Interview Questions
www.example.com starting from your browser.The browser asks the OS stub resolver, which checks /etc/hosts and the local cache, then hands the query to a recursive resolver (ISP, 8.8.8.8, or 1.1.1.1). If nothing's cached, the recursive resolver walks the hierarchy iteratively: it asks a root server "who handles .com?" and gets NS records for the .com TLD servers; it asks those "who handles example.com?" and gets example.com's authoritative nameservers; it asks those "what's www.example.com?" and gets the A record. The resolver caches each answer for its TTL and returns the IP to the stub resolver, and the browser opens a TCP connection. Cold lookups take ~3 round-trips; warm ones are answered from cache in one.
A recursive resolver does the work of finding an answer on the client's behalf — it queries root, TLD, and authoritative servers in turn and caches results; it owns no records itself. An authoritative nameserver is the source of truth for a specific zone — it holds the actual records and answers definitively for the domains it's responsible for, but it doesn't go fetch answers for other domains. Mnemonic: the recursive resolver is the researcher; the authoritative server is the author.
Every record carries a TTL in seconds; resolvers cache the answer for that long and won't re-query upstream until it expires, which is what makes DNS fast and scalable. Short TTLs (30–300s) let you change records — like failing over to a new IP — quickly, at the cost of more query volume and load. Long TTLs (hours/days) cut query load but mean stale answers linger during migrations or outages. Negative responses (NXDOMAIN) are cached too, governed by the SOA minimum. A common pattern is to lower TTLs days before a planned IP change, then raise them again afterward.
DNSSEC signs record sets with private keys and publishes the signatures (RRSIG) and public keys (DNSKEY). Each zone's key-signing key is vouched for by a DS record in the parent zone, building a chain of trust from the root (which resolvers trust as an anchor) down to the record. A validating resolver checks that chain and returns SERVFAIL if any signature is bad. It protects integrity and authenticity — it stops cache poisoning and spoofing because forged records won't have valid signatures. It does not provide confidentiality — queries and answers are still plaintext on the wire — and it doesn't stop DDoS or guarantee availability. For privacy you need DoH/DoT.
In cache poisoning — the Kaminsky attack being the famous case — an attacker floods a recursive resolver with forged responses, trying to land one before the real answer and guessing the 16-bit transaction ID. Kaminsky's refinement queried random nonexistent subdomains (so nothing was cached, giving unlimited attempts) and forged a response that overwrote the domain's NS records, hijacking the whole domain. DNSSEC prevents it because a forged record won't carry a valid RRSIG signature chained to the trusted root, so a validating resolver rejects it with SERVFAIL. The non-DNSSEC mitigations are source-port randomisation (raising the guess space to ~2^32) and 0x20 case-randomisation.
DNS tunnelling abuses the fact that DNS is almost never blocked: an attacker encodes data into subdomain labels of queries to an attacker-controlled authoritative server, and encodes responses back in TXT/NULL/CNAME records — creating a covert C2 or exfiltration channel through DNS. Detection signals: abnormally long, high-entropy subdomain labels (legit hostnames are short and word-like); high query volume to a single parent domain; lots of TXT/NULL queries; and bursts of NXDOMAIN. Entropy analysis on labels and per-domain volume baselining catch most of it. Tools like iodine, dnscat2, and dns2tcp implement this.
A Domain Generation Algorithm has malware compute a large list of pseudo-random domains from a seed (often the date), then try them until one resolves. The attacker only needs to register one of the day's domains to receive the beacon. It defeats static blocklists because the domains change constantly and there's no single hardcoded domain to block — and sinkholing requires predicting and pre-registering the algorithm's output. Detection focuses on the behavior instead: NXDOMAIN storms from a host cycling through dead domains, and the high lexical entropy of the generated names, which ML classifiers can flag.
The attacker serves a page from attacker.com with a very short TTL, then re-points attacker.com's DNS to an internal address like 192.168.1.1. The victim's browser-side JavaScript keeps making requests to "attacker.com" — same origin, so SOP allows it — but the name now resolves to the internal device, so the script can talk to an internal router or API and read responses. It works because SOP keys on the hostname, not the IP, and many internal services don't validate the Host header. Mitigations: resolvers/routers that refuse to return RFC 1918 addresses for external names, Host-header validation on internal services, and TLS (the cert won't match).
Both encrypt DNS. DoT (DNS over TLS) runs on its own port 853, so it's easy to identify and an enterprise can choose to proxy, inspect, or block it. DoH (DNS over HTTPS) runs on 443 mixed in with normal web traffic, so it's much harder to distinguish or block — great for user privacy against an on-path snoop, but a headache for enterprises that rely on DNS visibility for security monitoring, and a tool attackers use to evade DNS-based controls. The trade-off is privacy/censorship-resistance (DoH) versus network operator control and visibility (DoT). Both also break DNS-based blocklists if the client bypasses the corporate resolver.
All three are TXT records. SPF lists which servers may send mail for the domain — the receiver checks the sending IP against it. DKIM publishes a public key; the sender signs each message, and the receiver verifies the signature to confirm the mail wasn't altered and came from the domain. DMARC ties them together: it tells receivers what to do when SPF/DKIM fail and, crucially, requires alignment — the visible From: domain must match the domain that SPF/DKIM validated — then sets a policy of none, quarantine, or reject, with reporting back to the domain owner. The key insight is that SPF and DKIM alone take no action on failure; DMARC is what actually causes spoofed mail to be rejected. Mnemonic: sender, signature, decision.
Mirai was a 2016 IoT botnet that infected hundreds of thousands of devices — cameras, DVRs, routers — purely by brute-forcing a table of factory-default credentials over Telnet, no exploits needed. On October 21, 2016 it launched a massive DDoS against Dyn, a major managed-DNS provider, and because Dyn served authoritative DNS for huge customers, it knocked out resolution for Twitter, Reddit, Netflix, GitHub, Spotify and others — even though those sites themselves were healthy. The core lesson is that DNS is a single point of failure: if users can't resolve your name, your servers being up doesn't matter, so you should use multiple independent DNS providers with secondary DNS so one provider's outage can't take you offline. The secondary lessons are the IoT default-credential problem that made the botnet possible — which drove laws banning default passwords — and that terabit-scale DDoS from IoT is now normal, requiring anycast and scrubbing for DNS infrastructure. Mirai also included a DNS water-torture vector, flooding a victim's authoritative servers with random non-existent subdomains that can't be cached.