DNS Tunneling, Explained: How Data Hides Inside Ordinary DNS Lookups
Most company firewalls say no to almost everything going out. But they nearly always say yes to one thing: DNS, the lookup that turns github.com into an IP address. Without it nothing works, so it stays open. DNS tunnel
Most company firewalls say no to almost everything going out. But they nearly always say yes to one thing: DNS, the lookup that turns github.com into an IP address. Without it nothing works, so it stays open.
DNS tunneling is what happens when an attacker notices that open door and starts walking data through it. This post explains how it works without assuming you know DNS internals, shows a small Python script that caught a simulated leak, and lists the defenses that help.
TL;DR
- The attacker registers a domain and runs its name server. Malware on a hacked laptop then "looks up" names like
<stolen-data>.exfil-demo.example. Your own resolver delivers the question, data and all, to the attacker.- Answers can carry commands back, usually in TXT records.
- In my test, 1.6 KB of fake card data needed 50 DNS queries. Long, random, unique names under one domain are the tell.
- Defend in layers: one approved resolver, query logs with scoring, DNS filtering, endpoint visibility, and hardened network gear.
First, how a normal lookup works
When your laptop wants github.com, it asks the company resolver. The resolver does not know every domain, so it asks the name server that is responsible for github.com, gets an IP address back, and hands it to you.
The important detail: the resolver will ask whoever owns the domain. That is the whole design. If someone owns exfil-demo.example, any question about any name under it ends up on their server.
The trick: put the data in the question
Think of it like mailing letters to a PO box you own, except the message is written on the envelope address instead of inside. The post office (the resolver) reads the address, delivers it faithfully, and never wonders why the address is so strange.
A tunnel works in five steps:
- The attacker already has a foothold. Tunneling is not how they get in. That part is phishing, a vulnerable app or stolen credentials.
- Malware encodes data as text that is legal in a domain name, usually Base32 or hex.
-
It splits the text into slices and asks for names like
<slice>.<number>.exfil-demo.example. - The attacker's name server logs every question and rebuilds the data from the slices.
- Replies can carry instructions back. A TXT record can hold arbitrary text, so the server can answer "run this next".
DNS has hard size limits: 63 bytes per label and 255 bytes for the full name on the wire, about 253 characters as typed (RFC 1035). That makes tunneling slow, which is both its weakness and why it hides well: a slow leak blends into normal traffic.
Real attackers use it
MITRE ATT&CK tracks it as T1071.004, Application Layer Protocol: DNS and lists dozens of real tools and groups that used it:
- SUNBURST, the SolarWinds backdoor, used DNS for command-and-control traffic made to look like normal SolarWinds API calls.
- OilRig malware such as BONDUPDATER used DNS and TXT records as its tunnel.
- Ember Bear used open-source tunneling tools such as dnscat2 and Iodine, according to a 2024 CISA advisory.
- Cobalt Strike and Sliver, common attack frameworks, both ship DNS channels.
Data theft over DNS has its own entry too: T1048, Exfiltration Over Alternative Protocol.
How to spot it: four signals
I wanted to see how loud a tunnel really is, so I built a small test: 3,000 normal lookups from 20 laptops (Google, GitHub, Microsoft, a CloudFront CDN name), plus one host leaking a 1.6 KB fake customer file to exfil-demo.example through TXT queries. Then I scored every client and domain pair on four signals.
What each one means in plain words:
- Long labels. Real names are short words. Encoded data fills the label close to the 63-byte cap.
-
Randomness. Base32 looks like noise, so its character entropy is high.
microsoftdoes not. - Many unique names under one domain. Each slice is a new name, so the same client never asks the same question twice. Normal browsing repeats itself all day.
- TXT share. Laptops mostly ask for A, AAAA and HTTPS records. A host that asks for nothing but TXT is unusual.
None of these is proof by itself. In the test, the CloudFront name already scored 12 characters and 3.58 bits, close to the tunnel but under the thresholds, and email security tools query TXT records all the time. The signal is several of them at once, from one host, to one domain.
Try it yourself: a 53-line hunter
The script reads a log with one query per line (client qname qtype), which most resolvers can export. Run it without arguments to see the simulated test above.
"""Flag DNS tunneling suspects in a query log: one line per query, "client qname qtype".
Scores each (client, parent domain) pair on label length, randomness, unique names and TXT share."""
import base64, collections, math, random, sys
def entropy(s):
n = len(s)
return -sum(c / n * math.log2(c / n) for c in collections.Counter(s).values()) if n else 0.0
def parent(qname):
return ".".join(qname.rstrip(".").split(".")[-2:]) # shortcut: ignores public suffixes like co.uk
def hunt(lines):
groups = collections.defaultdict(list)
for line in lines:
client, qname, qtype = line.split()
groups[(client, parent(qname))].append((qname, qtype))
report = []
for (client, dom), qs in groups.items():
subs = [q[: -len(dom) - 1] for q, _ in qs if len(q) > len(dom)]
longest = max((len(l) for s in subs for l in s.split(".")), default=0)
ent = sum(entropy(s.replace(".", "")) for s in subs) / len(subs) if subs else 0.0
uniq = len(set(subs))
txt = sum(t == "TXT" for _, t in qs) / len(qs)
score = (longest > 40) + (ent > 3.8) + (uniq > 50) + (txt > 0.5)
report.append((score, client, dom, len(qs), uniq, longest, round(ent, 2), f"{txt:.0%}"))
return sorted(report, reverse=True)
def demo_log():
rnd = random.Random(7)
log = []
normal = ["www.google.com", "github.com", "api.github.com", "fonts.gstatic.com", "outlook.office365.com",
"d3k2x9z1m0q8.cloudfront.net", "update.microsoft.com", "dev.to", "www.youtube.com"]
for _ in range(3000): # 20 ordinary laptops
log.append(f"10.0.0.{rnd.randint(10, 29)} {rnd.choice(normal)} {rnd.choice(['A', 'A', 'AAAA', 'HTTPS'])}")
secret = ("name,email,card\n" + "jane,[email protected],4111111111111111\n" * 40).encode()
chunk = base64.b32encode(secret).decode().rstrip("=").lower()
for i in range(0, len(chunk), 52): # one infected host, 52 chars per label (limit is 63)
log.append(f"10.0.0.66 {chunk[i:i + 52]}.{i // 52}.exfil-demo.example TXT")
rnd.shuffle(log)
return log
if __name__ == "__main__":
lines = open(sys.argv[1]).read().split("\n") if len(sys.argv) > 1 else demo_log()
lines = [l for l in lines if l.strip()]
print(f"{len(lines)} queries")
print(f"{'score':>5} {'client':<11} {'domain':<20} {'queries':>7} {'unique':>6} {'longest':>7} {'entropy':>7} {'TXT':>4}")
for r in hunt(lines)[:6]:
print(f"{r[0]:>5} {r[1]:<11} {r[2]:<20} {r[3]:>7} {r[4]:>6} {r[5]:>7} {r[6]:>7} {r[7]:>4}")
The output on the simulated log, trimmed to the top three:
3050 queries
score client domain queries unique longest entropy TXT
3 10.0.0.66 exfil-demo.example 50 50 52 4.32 100%
0 10.0.0.29 youtube.com 10 1 3 0.0 0%
0 10.0.0.29 office365.com 11 1 7 2.13 0%
The leaking host scores 3 of 4 and sits alone at the top. Every normal pair scores 0. The fourth point (more than 50 unique names) missed by one, because the file was small. A bigger leak trips it.
Two limits. The thresholds (40 characters, 3.8 bits, 50 names, 50% TXT) are starting points from this test, not universal truths, so tune them against a week of your own traffic. And a careful attacker can go low and slow, with short labels and a few queries an hour. Score over days, not minutes.
How to defend: five layers
- Make your resolvers the only way out. Block clients from sending DNS straight to the internet: port 53, DNS over TLS on 853, and known DNS over HTTPS (DoH) providers. MITRE notes that the BRICKSTORM backdoor used DoH "to resolve C2 infrastructure and obscure DNS traffic from inspection", which is exactly the gap this closes.
- Log every query on those resolvers and score it. The script above is the idea in miniature. Real deployments use the resolver's query log feeding a SIEM, or a network sensor such as Zeek.
- Filter domains. Block known-bad and freshly registered domains at the resolver with a Response Policy Zone (RPZ) or a DNS filtering service. Tunnels need a domain, and new domains are cheap but suspicious.
-
Ask the endpoint. Your EDR can tell you which process made the lookups. A browser asking for odd names is one thing.
rundll32.exeasking for 50 random names is another. - Harden the network gear underneath. CISA's guide to securing network infrastructure devices covers the base layer: segment the network, limit traffic between segments, manage routers and firewalls out of band, turn off unencrypted admin protocols, and check firmware integrity. If an attacker owns the router, your DNS logs are only telling you what they let you see.
Found something? What to do next
- Confirm first. Check that the domain is not a security product, VPN or CDN you already use.
- Keep the evidence. Save the resolver logs and the endpoint timeline before you clean anything.
- Find the process, then isolate the host and block the domain.
- Look for the way in. Blocking one domain only closes one channel. The malware and the original entry point are still there.
- Estimate what left. Slices and sequence numbers in the logs tell you roughly how much data went out.
References
- MITRE ATT&CK, T1071.004 Application Layer Protocol: DNS
- MITRE ATT&CK, T1048 Exfiltration Over Alternative Protocol
- CISA, Securing Network Infrastructure Devices
- IETF, RFC 1035: Domain Names, Implementation and Specification
Next in this series: HTTP request smuggling, where the attacker abuses a different kind of trust, the one between a proxy and the server behind it.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.


