Browse CTFs New CTF Sign in

DNS Internals, Record Types & Anomaly Detection

foundation_networking Difficulty 1–2 70 min certifiable

Theory

Prerequisites

  • FND-K003: Networking Fundamentals for Security Practitioners

Why This Lesson Matters

DNS is the phonebook of the internet. Every connection a machine makes — to a legitimate website, to a malware C2 server, or to a data exfiltration endpoint — almost always begins with a DNS query. Understanding DNS deeply means you can read this phonebook and notice when entries look wrong, query rates spike unexpectedly, or query names carry encoded payloads.

DNS is consistently abused in real-world attacks because it is almost universally allowed through firewalls, it is high-volume (making anomalies easy to hide in noise), and it supports arbitrary-length subdomain strings that can carry encoded data.

This lesson takes you from the DNS resolution process all the way to hands-on anomaly detection in captured DNS traffic.


1. How DNS Resolution Works

When your browser visits www.example.com, the following chain of events occurs:

Your machine
  ↓ 1. Check local resolver cache (TTL-based)
  ↓ 2. If miss: query local recursive resolver (your router, ISP, or 8.8.8.8)

Local recursive resolver
  ↓ 3. If not cached: query a root nameserver
        (13 root server clusters globally: a.root-servers.net through m.root-servers.net)
  ↓ 4. Root returns referral: "I don't know www.example.com, but .com is handled by [TLD servers]"
  ↓ 5. Query .com TLD nameserver
  ↓ 6. TLD returns referral: "example.com is handled by ns1.example.com, ns2.example.com"
  ↓ 7. Query ns1.example.com (the authoritative nameserver)
  ↓ 8. Authoritative server returns: "www.example.com = 93.184.216.34, TTL 3600"

Local resolver caches the result and returns it to your machine.
Total elapsed time: typically 50–200ms for a cold lookup, <1ms for cached.

1.1 Iterative vs. Recursive Resolution

Recursive resolution: the resolver does all the legwork and returns a final answer to the client. Most end-user queries are recursive — you ask your local resolver and it figures everything out.

Iterative resolution: the resolver returns referrals ("go ask this other server"). The client must follow the chain itself. Used between resolvers and authoritative servers.

1.2 TTL — Time To Live

Every DNS record has a TTL (seconds). Once the TTL expires, the record must be re-queried. Security implications: - Short TTL (0–60s): Common in fast-flux networks (malware C2 that rapidly changes IPs to evade blacklisting) - Long TTL (86400s = 1 day): Normal for stable infrastructure; slow to propagate changes - TTL = 0: Record must not be cached — unusual for public records; suspicious on non-standard domains


2. DNS Record Types

Type Numeric Purpose Security relevance
A 1 IPv4 address Primary lookup; fast-flux detection
AAAA 28 IPv6 address IPv6 C2 infrastructure
MX 15 Mail server for domain Phishing infrastructure analysis
TXT 16 Arbitrary text SPF/DKIM/DMARC; data exfiltration; flag hiding
CNAME 5 Alias → canonical name Cloud hosting detection, dangling CNAME takeover
NS 2 Authoritative nameserver Domain delegation attacks
PTR 12 Reverse lookup (IP → name) Reconnaissance; spoofed PTR records
SOA 6 Zone authority info Zone transfer target
SRV 33 Service location records Active Directory DC discovery
DNSKEY / DS 48 / 43 DNSSEC signatures DNSSEC validation

2.1 The SPF/DKIM/DMARC Triad (Email Authentication)

These three mechanisms use DNS TXT records to authenticate email senders and instruct receiving servers on what to do with unauthenticated messages:

# Check SPF record (who is authorised to send email for this domain)
dig TXT example.com | grep "v=spf1"
# v=spf1 include:_spf.google.com ~all
#                              ^^^^
#                              ~all = softfail (mark as spam but deliver)
#                              -all = hardfail (reject)
#                              +all = accept all — DANGEROUS

# Check DMARC record (what to do with failures)
dig TXT _dmarc.example.com
# v=DMARC1; p=reject; rua=mailto:[email protected]
#              ^^^^^^
#              p=none    = monitor only (no protection)
#              p=quarantine = send to spam
#              p=reject  = reject unauthenticated email

# Check DKIM public key
dig TXT selector1._domainkey.example.com

A domain with p=none DMARC policy is trivially spoofable — any attacker can send email appearing to come from that domain. This is the most common configuration weakness enabling phishing.

2.2 Zone Transfers (AXFR)

A zone transfer replicates all DNS records from a primary to a secondary nameserver. If a nameserver is misconfigured to allow zone transfers from any IP, an attacker can enumerate every hostname in the domain:

# Attempt zone transfer (will fail on properly configured servers)
dig AXFR example.com @ns1.example.com

# If successful: every record in the zone is returned
# This reveals internal hostnames, IP ranges, mail servers, etc.

3. DNS Query Analysis in PCAPs

3.1 DNS Packet Structure

DNS queries and responses share the same packet structure:

Transaction ID: 0x1a2b       (matched between query and response)
Flags: 0x0100                (QR=0=query, RD=1=recursion desired)
Questions: 1
Question: www.example.com IN A
Transaction ID: 0x1a2b
Flags: 0x8180                (QR=1=response, RA=1=recursion available)
Answers: 1
Answer: www.example.com 300 IN A 93.184.216.34

3.2 tshark DNS Analysis

# List all DNS queries
tshark -r capture.pcap -Y "dns.flags.response == 0" 
  -T fields -e frame.time -e ip.src -e dns.qry.name -e dns.qry.type

# List all DNS responses with answers
tshark -r capture.pcap -Y "dns.flags.response == 1 && dns.count.answers > 0" 
  -T fields -e dns.qry.name -e dns.a

# Find NXDOMAIN responses (domain not found)
tshark -r capture.pcap -Y "dns.flags.rcode == 3" 
  -T fields -e dns.qry.name
# Many NXDOMAINs = possible DGA (Domain Generation Algorithm) malware
# or subdomain brute-forcing

# Count queries per domain (find suspicious volumes)
tshark -r capture.pcap -Y "dns.flags.response == 0" 
  -T fields -e dns.qry.name | sort | uniq -c | sort -rn | head -20

4. DNS-Based Attacks

4.1 DNS Spoofing / Cache Poisoning

Mechanism: An attacker injects a forged DNS response into a resolver's cache, causing all clients that use that resolver to receive a false IP address for a domain.

Classic Kaminsky attack (2008): Exploited the fact that DNS transaction IDs are only 16 bits (65,536 possibilities) and source ports were predictable. An attacker could flood a resolver with forged responses and statistically win the race. DNSSEC was the primary mitigation; source port randomisation (RFC 5452) was the practical short-term fix.

Modern impact: Cache poisoning can redirect users to phishing pages or malware download sites without any interaction from the victim beyond making a normal connection.

4.2 Domain Generation Algorithms (DGA)

Malware uses DGA to generate hundreds or thousands of potential C2 domain names from a seed (often the current date). The malware operators register only one or a few of these domains each day. This makes blacklisting ineffective — defenders cannot pre-block all possible domains.

Detection signatures: - High NXDOMAIN rate from a single host - Queries for names with high character entropy (random-looking rather than word-based) - Short TTLs on responding domains - Fast-flux A records (IP changes every few minutes)

# Python entropy function for detecting random-looking domain names
python3 << 'PYEOF'
import math, collections

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

legit = ["google", "microsoft", "example", "amazon"]
dga   = ["xj3kpqm", "a8z2vbn", "qwerty12", "7hfnbvc"]

print("Legitimate domain labels:")
for d in legit:
    print(f"  {d:<15} entropy={entropy(d):.2f}")
print("DGA domain labels:")
for d in dga:
    print(f"  {d:<15} entropy={entropy(d):.2f}")
# Legitimate: typically < 3.5 bits/char
# DGA: typically > 3.5 bits/char
PYEOF

4.3 DNS Tunnelling (Data Exfiltration)

DNS tunnelling encodes data inside DNS query labels and uses the DNS protocol as a covert communication channel. It is popular for: - Data exfiltration from environments where only DNS is allowed outbound - C2 communication through firewalls that block direct TCP/UDP - Bypassing captive portals

How it works:

Exfiltrated data: "secret-data"
Base32 encode each chunk: "ONQWW23F"
Send DNS query: ONQWW23F.exfil.attacker-c2.com

The attacker's DNS server (authoritative for attacker-c2.com) receives the
query, decodes the subdomain, and reconstructs the exfiltrated payload.

Visible signatures in a PCAP:

Normal DNS:     www.google.com (14 chars)
Normal DNS:     api.example.com (15 chars)
Tunnelled:      aGVsbG8gd29ybGQgdGhpcyBpcyBhIHN0cmluZw==.c2.evil.com (51 chars)
Tunnelled:      MJQWK3TFNRQWCYLBMFRA.c2.evil.com (38 chars)

Detection in tshark:

# Extract all query labels and show their length
tshark -r capture.pcap -Y "dns.flags.response == 0" 
  -T fields -e dns.qry.name 
  | awk -F'.' '{print length($1), $0}' 
  | awk '$1 > 30' 
  | sort -rn

# Label lengths > 30 characters are suspicious
# Legitimate subdomains are almost always < 20 characters

# Reassemble a tunnelled payload (once you've identified the exfil domain)
tshark -r capture.pcap -Y "dns.qry.name contains ".attacker-c2.com"" 
  -T fields -e dns.qry.name 
  | sed 's/.attacker-c2.com//' 
  | tr -d '
' 
  | base32 -d 2>/dev/null

5. Practical Wireshark Display Filters for DNS

# All DNS traffic
dns

# Only queries (not responses)
dns.flags.response == 0

# Only responses
dns.flags.response == 1

# Find NXDOMAIN (name not found)
dns.flags.rcode == 3

# Find queries for a specific name
dns.qry.name == "www.example.com"

# Find queries containing a partial name
dns.qry.name contains "attacker"

# Find TXT record queries
dns.qry.type == 16

# Find MX queries
dns.qry.type == 15

# Find very long query names (> 50 chars = possible tunnelling)
dns.qry.name && frame.len > 100

6. Common Mistakes

Mistake 1: Thinking DNS only runs on port 53 UDP. DNS uses UDP for standard queries but falls back to TCP for large responses (> 512 bytes without EDNS, > 4096 bytes with EDNS). DNS over HTTPS (DoH) runs on port 443. DNS over TLS (DoT) runs on port 853. Filtering for udp.port == 53 misses all of these.

Mistake 2: Ignoring PTR (reverse DNS) queries during reconnaissance. Attackers performing network reconnaissance use PTR queries to map IP addresses to hostnames. A burst of PTR queries from a single source is a recon indicator.

Mistake 3: Assuming NXDOMAIN = innocent. A flood of NXDOMAIN responses to a single host is a strong indicator of DGA malware probing for its active C2 domain.

Mistake 4: Trusting short TTL responses as legitimate. Fast-flux networks use very short TTLs (0–60 seconds). A newly registered domain with extremely short TTLs and rapidly changing A records is a classic malware infrastructure signature.

Mistake 5: Forgetting that DNS responses can be spoofed without DNSSEC. Without DNSSEC validation, a DNS response has no cryptographic binding to the authoritative server. Treat DNS data as untrusted unless DNSSEC is validated end-to-end.


7. Guided Example — Identifying DNS Tunnelling

Objective: Given a PCAP, determine whether DNS tunnelling is occurring and reconstruct the exfiltrated payload.

Step 1: Get an overview of DNS traffic

tshark -r suspicious.pcap -Y "dns.flags.response == 0" 
  -T fields -e dns.qry.name | head -30

Output (truncated):

www.google.com
api.stripe.com
aGVsbG8gd29y.exfil.corp-monitor.com
bGQ=.exfil.corp-monitor.com
dGhpcyBpcyBh.exfil.corp-monitor.com
IHRlc3Q=.exfil.corp-monitor.com

The exfil.corp-monitor.com domain is suspicious. The subdomains look like Base64.

Step 2: Extract all queries to that domain

tshark -r suspicious.pcap -Y "dns.qry.name contains "exfil.corp-monitor.com"" 
  -T fields -e frame.time -e dns.qry.name | sort

Step 3: Extract and decode the subdomain labels

tshark -r suspicious.pcap 
  -Y "dns.qry.name contains "exfil.corp-monitor.com" && dns.flags.response == 0" 
  -T fields -e dns.qry.name 
  | sed 's/.exfil.corp-monitor.com//' 
  | tr -d '
' 
  | base64 -d

Output: hello world this is a test

Step 4: Document

  • Exfiltration domain: exfil.corp-monitor.com
  • Technique: DNS tunnelling via Base64-encoded subdomains
  • Data recovered: hello world this is a test
  • ATT&CK: T1048.003 — Exfiltration Over Alternative Protocol: DNS
  • Recommended action: Block exfil.corp-monitor.com at DNS resolver; investigate source host for malware

8. Practice Exercises

  1. Using dig, retrieve:
  2. The A record for dns.google
  3. The MX records for a domain you are authorised to query
  4. The TXT records for _dmarc.gmail.com and explain what the policy means

  5. Open a PCAP in Wireshark. Apply the filter dns.flags.rcode == 3. How many NXDOMAIN responses are there? If there are many from a single source IP, what would you investigate next?

  6. You observe these DNS query names in a PCAP: Y2xhc3NpZmllZA==.internal.update-svc.net aW5mb3JtYXRpb24=.internal.update-svc.net ZWQGAML3SDNL.internal.update-svc.net

  7. Decode the first two Base64 labels. What data is being exfiltrated?
  8. What would you look for in the network equipment to block this?

  9. Write a tshark one-liner that outputs the count of DNS queries grouped by second-level domain, sorted by count descending.


9. Lab

Assessment mode: flag

challenge_spec_id: 7 — DNS tunneling detection

You are given a capture.pcap file containing mixed normal and DNS-tunnelled traffic.

Task: 1. Identify the domain being used for DNS tunnelling 2. Extract all subdomain labels belonging to that domain, in query order 3. Concatenate and Base32-decode the labels to reconstruct the hidden message 4. The message contains the flag in PREFIX{...} format


10. Framework Alignment

Framework Domain / Role Competency Confidence
CCSSF-COA Cyber Security Operations Analyst DNS anomaly detection, threat enrichment High
CCSSF-CIR Cyber Incident Responder DNS exfiltration and C2 investigation High
CCSSF-DFA Digital Forensics Analyst PCAP-based network forensics High
CCSSF-CTI OSINT & Threat Intelligence DNS-based threat infrastructure analysis Medium
NICE 2.2.0 Cyber Defense Analyst (PR-CDA-001) K0332 — Network architecture concepts High
NICE 2.2.0 All roles K0179 — DNS operations and security High

11. Further Reading

  • RFC 1034 / RFC 1035 — The original DNS specifications; still authoritative
  • "DNS Security" — Men and Mice — https://menandmice.com/dns-knowledge-base — Practical reference
  • Julia Evans — "How DNS Works" zine — Highly visual; available at https://jvns.ca
  • SANS Whitepaper: DNS Tunneling — Jonathan Katz — Step-by-step technical breakdown
  • iodine / dnscat2 — DNS tunnelling tools; reading their READMEs explains the protocol perfectly
  • Blocking DNS Tunnelling — Cloudflare blog — Practical perspective on detection and mitigation

Learning Objectives

["Describe the recursive DNS resolution chain from client query through root, TLD, and authoritative nameservers", "Identify the DNS record types relevant to email security (MX, TXT with SPF/DKIM/DMARC) and explain what a weak DMARC policy enables", "Use tshark to count DNS queries per domain, find NXDOMAIN responses, and identify anomalously long subdomain labels", "Reconstruct a Base32-encoded DNS-tunnelled payload from a PCAP by extracting and concatenating subdomain labels in query order"]

Lesson Outline

Prerequisites → Why this matters → DNS resolution chain (iterative vs recursive, TTL) → DNS record types in depth (A, MX, TXT, NS, SOA, PTR) → SPF/DKIM/DMARC email auth → Zone transfer (AXFR) → DNS query analysis in PCAPs with tshark → DNS-based attacks (cache poisoning, DGA, tunnelling with worked examples) → Practical Wireshark filters → Common mistakes → Guided example (DNS tunnelling identification and payload reconstruction) → Practice exercises → Lab (flag, spec 7) → Framework alignment → Further reading

Challenge Lab

Reinforce your learning with a hands-on generated challenge based on this card's competency.