> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# DNS Deep Dive

> Master DNS - zones, records, resolution, propagation, and how domain names become IP addresses

# Module 12: DNS Deep Dive

DNS (Domain Name System) is often called the "phonebook of the internet," but it is more accurately the internet's distributed directory service. Unlike a phonebook (which is a single, static document), DNS is a globally distributed, hierarchical, real-time database that handles trillions of queries per day. This module takes you from basic understanding to mastering DNS architecture, record types, troubleshooting, and security.

A better analogy: DNS is like the information desk network at a large airport. You ask the first desk "Where is Gate B42?" They do not know, but they say "Go to Terminal B information." Terminal B information says "Gate B42 is in Concourse B-East, ask the desk there." The Concourse B-East desk finally tells you "Gate B42 is down the hall, third on the left." Each desk only knows about its own area, but by following the chain, you get your answer. And crucially, you remember the answer for next time (caching) so you do not have to ask again.

<Frame>
  <img src="https://mintcdn.com/devweeekends/X0Fp4X8lMl-ZftoO/images/courses/networking-mastery/dns-deep-dive.svg?fit=max&auto=format&n=X0Fp4X8lMl-ZftoO&q=85&s=47f14ee56e0785f6ac71fc435c149016" alt="DNS Resolution Flow" width="1080" height="1080" data-path="images/courses/networking-mastery/dns-deep-dive.svg" />
</Frame>

<Info>
  **Estimated Time**: 4-5 hours\
  **Difficulty**: Intermediate\
  **Prerequisites**: Module 6 (Application Layer basics)
</Info>

***

## 12.1 Why DNS Matters

Without DNS, you'd need to memorize IP addresses:

```
Instead of: google.com
You'd type: 142.250.190.46

Instead of: netflix.com  
You'd type: 54.237.226.164

Instead of: aws.amazon.com
You'd type: 54.239.28.85
```

DNS translates **human-readable names** to **machine-readable IP addresses**.

***

## 12.2 The DNS Hierarchy

DNS is a **distributed hierarchical database**, not a single server.

```
                           . (Root)
                              │
            ┌─────────────────┼─────────────────┐
            │                 │                 │
          .com              .org              .net
            │                 │                 │
     ┌──────┴──────┐    ┌────┴────┐      ┌────┴────┐
     │             │    │         │      │         │
  google       amazon  wikipedia  ...   cloudflare ...
     │
  ┌──┴──┐
mail   www
```

### DNS Components

| Component                 | Role                            | Example                                      |
| ------------------------- | ------------------------------- | -------------------------------------------- |
| **Root Servers**          | Top of hierarchy, point to TLDs | 13 root server clusters (a.root-servers.net) |
| **TLD Servers**           | Handle top-level domains        | .com, .org, .net, .io, .dev                  |
| **Authoritative Servers** | Hold actual DNS records         | ns1.google.com                               |
| **Recursive Resolvers**   | Query on behalf of clients      | 8.8.8.8 (Google), 1.1.1.1 (Cloudflare)       |

***

## 12.3 DNS Resolution Process

### Step-by-Step: Resolving [www.example.com](http://www.example.com)

<Steps>
  <Step title="Browser Cache">
    Browser checks its local DNS cache.

    ```
    Cache hit? → Return IP immediately
    Cache miss? → Continue
    ```
  </Step>

  <Step title="OS Cache">
    Operating system checks its DNS cache.

    ```bash theme={null}
    # View DNS cache on Windows
    ipconfig /displaydns

    # Clear DNS cache
    ipconfig /flushdns  # Windows
    sudo dscacheutil -flushcache  # macOS
    ```
  </Step>

  <Step title="Recursive Resolver">
    Query is sent to configured DNS resolver (usually ISP's or 8.8.8.8).

    ```
    Your PC → "What's the IP of www.example.com?" → Resolver
    ```
  </Step>

  <Step title="Root Server Query">
    Resolver asks a root server:

    ```
    Resolver → Root: "Where's www.example.com?"
    Root → Resolver: "I don't know, but .com is handled by these servers..."
    ```
  </Step>

  <Step title="TLD Server Query">
    Resolver asks the .com TLD server:

    ```
    Resolver → .com TLD: "Where's www.example.com?"
    .com TLD → Resolver: "example.com is handled by ns1.example.com"
    ```
  </Step>

  <Step title="Authoritative Server Query">
    Resolver asks the authoritative server:

    ```
    Resolver → ns1.example.com: "What's www.example.com?"
    ns1.example.com → Resolver: "93.184.216.34"
    ```
  </Step>

  <Step title="Response to Client">
    Resolver caches the answer and returns it:

    ```
    Resolver → Your PC: "www.example.com = 93.184.216.34"
    ```
  </Step>
</Steps>

### Visual Flow

```
Your PC                    Resolver                  DNS Servers
   │                          │                          │
   │──"www.example.com?"─────►│                          │
   │                          │──"Where's .com?"────────►│ Root
   │                          │◄─"Try these TLD servers"─│
   │                          │                          │
   │                          │──"Where's example.com?"─►│ .com TLD
   │                          │◄─"ns1.example.com"───────│
   │                          │                          │
   │                          │──"www.example.com?"─────►│ Authoritative
   │                          │◄─"93.184.216.34"─────────│
   │                          │                          │
   │◄─"93.184.216.34"─────────│                          │
   │                          │                          │
```

***

## 12.4 DNS Record Types

### Essential Records

| Record    | Purpose               | Example                                |
| --------- | --------------------- | -------------------------------------- |
| **A**     | Maps name to IPv4     | `www` → `93.184.216.34`                |
| **AAAA**  | Maps name to IPv6     | `www` → `2606:2800:220:1:...`          |
| **CNAME** | Alias to another name | `blog` → `www.example.com`             |
| **MX**    | Mail server           | `@` → `mail.example.com` (priority 10) |
| **TXT**   | Text data             | SPF, DKIM, domain verification         |
| **NS**    | Nameserver            | `@` → `ns1.example.com`                |
| **SOA**   | Zone authority        | Serial, refresh, retry info            |

### Record Examples

```dns theme={null}
; A Records - IPv4 addresses
example.com.        A       93.184.216.34
www.example.com.    A       93.184.216.34

; AAAA Record - IPv6 address  
www.example.com.    AAAA    2606:2800:220:1:248:1893:25c8:1946

; CNAME - Alias (cannot coexist with other records for same name)
blog.example.com.   CNAME   www.example.com.

; MX - Mail servers (lower number = higher priority)
example.com.        MX      10 mail1.example.com.
example.com.        MX      20 mail2.example.com.

; TXT - Verification, SPF, DKIM
example.com.        TXT     "v=spf1 include:_spf.google.com ~all"
example.com.        TXT     "google-site-verification=abc123..."

; NS - Nameservers for this domain
example.com.        NS      ns1.example.com.
example.com.        NS      ns2.example.com.
```

### Advanced Records

| Record        | Purpose                    | Use Case                                       |
| ------------- | -------------------------- | ---------------------------------------------- |
| **SRV**       | Service location           | `_sip._tcp.example.com` → specific server:port |
| **PTR**       | Reverse lookup             | IP → hostname (for reverse DNS)                |
| **CAA**       | Certificate Authority Auth | Which CAs can issue SSL certs                  |
| **DNSKEY/DS** | DNSSEC                     | Cryptographic verification                     |

***

## 12.5 TTL (Time To Live)

TTL determines **how long DNS records are cached**.

```dns theme={null}
www.example.com.    300     A     93.184.216.34
                     ↑
                 TTL in seconds (5 minutes)
```

### TTL Trade-offs

| Low TTL (e.g., 60s)         | High TTL (e.g., 86400s) |
| --------------------------- | ----------------------- |
| Fast propagation of changes | Slower propagation      |
| More DNS queries            | Fewer DNS queries       |
| More load on DNS servers    | Less load               |
| Good during migrations      | Good for stable records |

### TTL Strategy for Migrations

This is one of the most important operational patterns in DNS management. Getting it wrong can cause hours of downtime.

```
Step 1: Days before migration
  - Lower TTL from 3600s to 60s
  - WAIT for the old TTL to fully expire (at least 3600s = 1 hour)
  - This ensures all caches worldwide will refresh within 60 seconds

Step 2: Make the change
  - Update the DNS record to point to the new IP

Step 3: Verify it works
  - Check from multiple locations: dig @8.8.8.8, dig @1.1.1.1
  - Use whatsmydns.net to verify global propagation
  - Test the application at the new IP

Step 4: After migration is confirmed stable
  - Raise TTL back to normal (3600s or higher)
  - Higher TTL = fewer DNS queries = faster resolution for users
```

<Warning>
  **The classic mistake**: Changing the DNS record without lowering the TTL first. If the TTL was 86400 seconds (24 hours), some users will continue hitting the old IP for up to 24 hours after the change, regardless of what you do. There is no way to force a cache flush on every resolver worldwide. The only defense is to lower the TTL before the migration and wait for the old TTL to expire.
</Warning>

***

## 12.6 DNS Zones

A **zone** is a portion of the DNS namespace managed by a specific organization.

### Zone File Example

```dns theme={null}
$TTL 86400
@   IN  SOA     ns1.example.com. admin.example.com. (
                2024010101  ; Serial
                7200        ; Refresh (2 hours)
                3600        ; Retry (1 hour)
                1209600     ; Expire (2 weeks)
                86400       ; Minimum TTL (1 day)
)

; Nameservers
@       IN      NS      ns1.example.com.
@       IN      NS      ns2.example.com.

; A Records
@       IN      A       93.184.216.34
www     IN      A       93.184.216.34
mail    IN      A       93.184.216.35

; Mail
@       IN      MX      10 mail.example.com.

; CNAME
blog    IN      CNAME   www.example.com.
```

### Zone Types

| Type                  | Description                        |
| --------------------- | ---------------------------------- |
| **Primary (Master)**  | The authoritative source, editable |
| **Secondary (Slave)** | Read-only copy, syncs from primary |
| **Forward**           | Name → IP resolution               |
| **Reverse**           | IP → Name resolution               |

***

## 12.7 DNS Propagation

When you change DNS records, the change doesn't happen instantly worldwide.

### Why Propagation Takes Time

```
1. You update record on authoritative server
2. Old records still cached at:
   - Recursive resolvers worldwide
   - ISP DNS servers
   - Browser caches
   - OS caches
3. Each must wait for TTL to expire
4. Then they query again and get new record
```

### Propagation Timeline

```
TTL = 3600 (1 hour)

0:00  - Record changed
0:01  - Users with fresh cache see new IP
0:30  - ~50% of caches expired, see new IP
1:00  - Most caches expired
1:30  - Stragglers with extended caching
2:00  - 99%+ should have new record
```

### Checking Propagation

```bash theme={null}
# Query specific DNS server
dig @8.8.8.8 example.com
dig @1.1.1.1 example.com

# Check multiple locations
# Use: dnschecker.org, whatsmydns.net
```

***

## 12.8 DNS Query Types

### Recursive vs Iterative

```
RECURSIVE (client → resolver):
Client: "Give me the final answer"
Resolver: Does all the work, returns final IP

ITERATIVE (resolver → authoritative):  
Resolver: "Where should I look next?"
Server: "Try this other server"
(Resolver follows the chain)
```

### Query Tools

```bash theme={null}
# nslookup (basic)
nslookup google.com

# dig (detailed)
dig google.com
dig google.com MX
dig +trace google.com  # Show full resolution path

# host (simple)
host google.com
```

### dig Output Explained

```bash theme={null}
$ dig example.com

; <<>> DiG 9.16.1 <<>> example.com
;; QUESTION SECTION:
;example.com.                   IN      A        ← What we asked

;; ANSWER SECTION:
example.com.            3600    IN      A      93.184.216.34
                         ↑                          ↑
                        TTL                        Answer

;; AUTHORITY SECTION:
example.com.            3600    IN      NS     ns1.example.com.

;; Query time: 25 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)  ← Resolver used
;; WHEN: Tue Jan 01 12:00:00 UTC 2024
```

***

## 12.9 Common DNS Configurations

### Subdomain Setup

```dns theme={null}
; Main site
@       IN      A       93.184.216.34
www     IN      A       93.184.216.34

; Subdomains pointing to different servers
api     IN      A       93.184.216.100
blog    IN      A       93.184.216.101
shop    IN      CNAME   shopify.com.

; Wildcard (matches anything)
*       IN      A       93.184.216.34
```

### Load Balancing with DNS

```dns theme={null}
; Round-robin (multiple A records)
www     IN      A       93.184.216.34
www     IN      A       93.184.216.35
www     IN      A       93.184.216.36

; Each query returns records in different order
```

### Geographic DNS

Cloud providers offer geo-based DNS:

```
User in US → Route to us-east-1
User in EU → Route to eu-west-1
User in Asia → Route to ap-southeast-1
```

***

## 12.10 DNS Security

### Common Attacks

<CardGroup cols={2}>
  <Card title="DNS Spoofing" icon="mask">
    Attacker returns fake DNS responses, redirecting users to malicious sites.
  </Card>

  <Card title="DNS Cache Poisoning" icon="skull">
    Corrupting resolver cache to serve wrong IPs.
  </Card>

  <Card title="DNS Amplification DDoS" icon="explosion">
    Using open resolvers to amplify attack traffic.
  </Card>

  <Card title="DNS Tunneling" icon="tunnel">
    Encoding data in DNS queries to bypass firewalls.
  </Card>
</CardGroup>

### DNSSEC

**DNS Security Extensions** add cryptographic signatures to DNS records.

```
Zone signs records with private key
    ↓
DS record in parent zone (chain of trust)
    ↓
Resolvers verify signatures
    ↓
Tampered records are rejected
```

### DNS over HTTPS (DoH) / DNS over TLS (DoT)

Traditional DNS is unencrypted (port 53, plaintext). This means anyone between you and the DNS resolver -- your ISP, a coffee shop Wi-Fi operator, or a MITM attacker -- can see exactly which domains you are querying. It is like asking for directions by shouting across a crowded room -- everyone hears where you are trying to go.

| Protocol | Port | Encryption | Privacy                 |
| -------- | ---- | ---------- | ----------------------- |
| DNS      | 53   | None       | ISP can see all queries |
| DoT      | 853  | TLS        | Queries encrypted       |
| DoH      | 443  | HTTPS      | Hidden in web traffic   |

### What a DNS query looks like at the packet level

```
Traditional DNS (port 53, unencrypted):
  Your PC -> Resolver (8.8.8.8):
    Query: A record for secretproject.company.com
    [Visible to anyone capturing packets on the network]

DNS over HTTPS (port 443, encrypted):
  Your PC -> Resolver (1.1.1.1):
    [Encrypted HTTPS traffic -- looks identical to any web browsing]
    [Snooper sees traffic to 1.1.1.1:443 but cannot read the query]
```

<Tip>
  **Troubleshooting DNS at the packet level**: When DNS issues are subtle (intermittent failures, slow resolution), `tcpdump` or Wireshark are your best friends. Capture DNS traffic with `sudo tcpdump -i eth0 port 53 -w dns-capture.pcap`. In Wireshark, filter by `dns` and look for: (1) queries with no response (the resolver or authoritative server might be unreachable), (2) responses with NXDOMAIN status (the domain does not exist -- typo in the record?), (3) responses with SERVFAIL (the authoritative server has a configuration problem), or (4) unusually high query times (the resolver is overloaded or the network path is congested).
</Tip>

***

## 12.11 Private DNS and Split-Horizon

### Private DNS Zones

For internal resources not visible to the public:

```
Public DNS (internet):
app.company.com → 203.0.113.50 (public IP)

Private DNS (internal):  
app.company.com → 10.0.1.100 (private IP)
db.company.com → 10.0.2.50 (no public record)
```

### Split-Horizon DNS

Same domain returns different results based on where you query from:

```
External user → api.company.com → 203.0.113.50 (through load balancer)
Internal user → api.company.com → 10.0.1.100 (direct to server)
```

***

## 12.12 DNS Troubleshooting Checklist

<Accordion title="Website not resolving">
  ```bash theme={null}
  # 1. Check if DNS returns any result
  dig example.com

  # 2. Check specific nameserver
  dig @ns1.example.com example.com

  # 3. Verify nameservers are correct
  dig example.com NS

  # 4. Check propagation
  # Use whatsmydns.net
  ```
</Accordion>

<Accordion title="Email not working">
  ```bash theme={null}
  # 1. Check MX records
  dig example.com MX

  # 2. Verify MX target resolves
  dig mail.example.com A

  # 3. Check SPF record
  dig example.com TXT

  # 4. Check DKIM
  dig selector._domainkey.example.com TXT
  ```
</Accordion>

<Accordion title="SSL certificate issues">
  ```bash theme={null}
  # 1. Check CAA records
  dig example.com CAA

  # 2. Verify domain validation records
  dig _acme-challenge.example.com TXT

  # 3. Check for CNAME issues (can block CAA lookup)
  dig example.com CNAME
  ```
</Accordion>

***

## 12.13 Key Takeaways

<CardGroup cols={2}>
  <Card title="Hierarchy Matters" icon="sitemap">
    Root → TLD → Authoritative. Understand the chain.
  </Card>

  <Card title="TTL Controls Caching" icon="clock">
    Lower before changes, raise after for stability.
  </Card>

  <Card title="Records Have Purposes" icon="list">
    A for IPv4, AAAA for IPv6, CNAME for aliases, MX for mail.
  </Card>

  <Card title="Propagation Takes Time" icon="hourglass">
    Changes spread globally based on TTL, not instantly.
  </Card>
</CardGroup>

***

## Next Module

<Card title="Module 13: Load Balancing & Proxies" icon="arrow-right" href="/courses/networking-mastery/13-load-balancing">
  Understand how traffic is distributed across servers and how proxies work.
</Card>
