Skip to content

DNS Tunneling, Explained: How Data Hides Inside Ordinary DNS Lookups

Published Last updated 9 min read

Key takeaways

  • DNS tunneling puts data inside the domain names a computer looks up. The attacker owns the domain, so every lookup for it lands on their server.
  • It works because firewalls block most traffic but almost always let DNS through to the company resolver.
  • DNS limits a label to 63 bytes, so data leaves in slices. In my test 1.6 KB of fake card data took 50 queries.
  • Four signals give it away when they show up together: long labels, random-looking names, many unique names under one domain, and a high share of TXT queries.
  • The fix is layered: force all DNS through your own resolvers, log and score queries there, filter bad domains, and ask the endpoint which process made the 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 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.

Two flows side by side. Normal lookup: a laptop asks the company resolver for github.com, the resolver asks github.com's name server, which answers with an IP address. Tunneled lookup: an infected laptop puts data in the name, the company resolver forwards it like any other query to the attacker's name server for exfil-demo.example, which reads the data from the name and can reply with commands in a TXT record. Example query: 64tqfzsxqylnobwgklbugeyt.7.exfil-demo.example TXT.

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:

  1. The attacker already has a foothold. Tunneling is not how they get in. That part is phishing, a vulnerable app or stolen credentials.
  2. Malware encodes data as text that is legal in a domain name, usually Base32 or hex.
  3. It splits the text into slices and asks for names like <slice>.<number>.exfil-demo.example.
  4. The attacker’s name server logs every question and rebuilds the data from the slices.
  5. Replies can carry instructions back. A TXT record can hold arbitrary text, so the server can answer “run this next”.

Anatomy of a tunneled DNS name: 64tqfzsxqylnobwgklbugeytcmjrgeytcmjrgeytcmjrbjvgc3tf.7.exfil-demo.example. The first label is the payload, Base32 text up to 63 bytes per label. The 7 is a sequence number so the pieces can be put back in order. exfil-demo.example is the attacker's domain, and every query for it ends up at their server. DNS limits each label to 63 bytes and a whole name to 255 bytes, so in the test 1.6 KB of fake card data took 50 queries.

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.

Four signals measured on 3,050 queries, tunnel host versus the highest normal value. Longest label: 52 characters versus 12. Randomness (entropy): 4.32 bits versus 3.58. Unique names per domain: 50 versus 1. TXT share: 100 percent versus 0 percent. One signal alone is not proof. Several at once on one host and one domain is worth a look.

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. microsoft does 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,jane@corp.example,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

Five defense layers. Approved resolvers only: block direct DNS on 53/udp, 853/tcp and known DNS over HTTPS endpoints from clients, so only your resolvers talk out. Resolver logs and baseline: log every query and alert on long labels, high entropy, many unique names and TXT spikes. DNS filtering: block known-bad and newly registered domains at the resolver with RPZ or a filtering service. Endpoint: EDR shows which process is making the lookups; PowerShell talking DNS at 3 a.m. is odd. Hardened network devices, from CISA: segment the network, manage devices out of band, no unencrypted admin protocols, check firmware.

  1. 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.
  2. 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.
  3. 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.
  4. Ask the endpoint. Your EDR can tell you which process made the lookups. A browser asking for odd names is one thing. rundll32.exe asking for 50 random names is another.
  5. 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

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.

Frequently asked questions

Is DNS tunneling always malicious?
No. Some VPN and captive-portal bypass tools use it, and testers use it with permission. It becomes a security problem when it runs without authorization, usually as a command channel for malware or a way to move data out.
Does blocking port 53 stop DNS tunneling?
Blocking direct port 53 from clients helps, because it forces lookups through your resolver where you can log them. It does not stop tunneling on its own: the resolver still forwards queries for the attacker's domain, and malware can also use DNS over HTTPS.
What is the quickest signal to check first?
Look for one client asking for many unique names under one domain, with labels over about 40 characters. Normal traffic almost never does both.
Share Share on X Share on LinkedIn

About the author

Portrait of Kiell Tampubolon

Security Engineer & Technical Writer

Security engineer and technical writer based in Batam, Indonesia. I review and harden MCP servers and AI agents, build security automation, and write up what holds and what fails. I also train on DNS security as a PANDI .id Academy trainer.

All writing | RSS | Markdown