Type something to search...
What Is DNS Tunneling, and Why Is It a Security Risk?

What Is DNS Tunneling, and Why Is It a Security Risk?

Almost every network on the planet lets DNS out. Firewalls that block outbound SSH, unknown ports, and direct internet access still have to let devices resolve names, because nothing works without it. That near-universal permission is exactly what makes DNS attractive to attackers: if you can encode arbitrary data inside DNS lookups, you have a communication channel that slips through controls designed for everything else. That technique is called DNS tunneling. This article explains how it works at the protocol level, why it is a real security risk rather than a theoretical one, what it looks like in your logs, and the defensive controls that shut it down. If you need a refresher on the lookup path first, see how DNS works and the role of a DNS resolver.

What Is DNS Tunneling?

DNS tunneling is the practice of carrying non-DNS data inside DNS queries and responses. Instead of asking a question because it wants an answer, a tunneling client asks questions whose names are the payload, and a cooperating server replies with answers whose record data is the return payload.

It does not exploit a bug in DNS. It abuses a design feature: any recursive resolver will faithfully forward a query for any name to whichever server is authoritative for that domain. If an attacker controls the authoritative server for a domain, every query for a subdomain of it is effectively a message delivered to them, relayed by your own trusted resolver.

DNS tunneling shows up in three main forms:

  1. Data exfiltration. Stolen data (credentials, database rows, documents) is chunked, encoded, and smuggled out as subdomain labels.
  2. Command and control (C2). Malware on an infected host polls an attacker-controlled domain and receives instructions in the responses, often at a slow, low-volume rate to avoid notice.
  3. Full IP-over-DNS tunnels. General-purpose tools wrap entire network sessions in DNS traffic, typically to bypass captive portals or restrictive egress policies. Open-source projects such as iodine and dnscat2 are well known examples, and security teams often use them in controlled tests to validate detection.

How DNS Tunneling Works Under the Hood

The mechanics rely on two parts of the DNS message: the query name going out and the record data coming back.

The Outbound Channel: Encoded Subdomains

A domain name can be up to 253 characters, made of labels of up to 63 characters each. A tunneling client takes a chunk of data, encodes it in a DNS-safe alphabet (commonly Base32 or hex, since DNS names are case-insensitive), and prepends it as labels to a domain the attacker controls. Conceptually, a query looks like this:

mzxw6ytboi4dcmrrgu3tsmzqgq2dk.nbswy3dpeb3w64tmmq.t1.attacker-example.net.  IN  TXT

Your resolver has never seen that name before, so it cannot answer from cache. It follows the delegation to the authoritative name servers for attacker-example.net, which the attacker runs. Their server decodes the labels and now has the data. The uniqueness of each name is deliberate: it defeats DNS caching and guarantees each query reaches the attacker.

The Inbound Channel: Record Data

To send data back, the attacker's server answers with record types that can hold arbitrary content. TXT records are the most common because they can carry long free-form strings. CNAME, MX, and NULL records are also used, and even A and AAAA records can carry a few bytes each by encoding data into the address itself.

Why It Gets Past Firewalls

The client never talks to the attacker directly. It talks to your internal resolver on port 53, which is allowed. Your resolver then talks to the attacker's authoritative server, which is also allowed, because resolving external names is its job. From the firewall's point of view, every packet is legitimate DNS between approved hosts.

Why DNS Tunneling Is a Serious Security Risk

It is easy to dismiss DNS tunneling as slow and noisy. Throughput is low, often a few kilobytes per second at best. But attackers rarely need speed:

  • Credentials and keys are small. A set of passwords, an API key, or a private key fits in a handful of queries.
  • Slow and steady wins. Exfiltrating a few megabytes over days at a rate of a few queries per minute blends into the background noise of a busy network.
  • C2 needs almost no bandwidth. A beacon that checks in every few minutes and receives a one-line command is enough to run an intrusion.
  • DNS is often unmonitored. Many organizations log web proxy traffic in detail but treat DNS as plumbing and keep no query logs at all.
  • It defeats network segmentation. A server with no internet access at all can often still resolve names through an internal resolver, which quietly gives it an outbound channel.

DNS tunneling has been documented in real intrusions, including targeted campaigns by state-linked groups and commodity malware families that use DNS for C2. It is also a known compliance gap: data loss prevention tools that only inspect HTTP, email, and file transfers will miss it entirely.

Legitimate Uses That Look Like Tunneling

Not every strange-looking DNS query is malicious, which is part of what makes detection tricky. Some legitimate products deliberately encode data in DNS lookups:

  • Antivirus and reputation services look up file hashes or URLs as subdomains of a vendor domain to get a fast verdict.
  • Email anti-spam blocklists (DNSBLs) encode IP addresses in query names, for example a reversed IP prepended to the blocklist zone.
  • Telemetry and licensing checks from some security and endpoint agents.
  • CDN and load-balancer health tokens that embed identifiers in hostnames.

Your detection approach needs an allowlist for these, or you will drown in false positives.

How to Detect DNS Tunneling

Detection depends on having DNS query logs in the first place. If your resolvers do not log queries, start there. BIND, Unbound, Windows DNS Server, and cloud resolvers all support query logging, and network sensors such as Zeek can produce a dns.log from mirrored traffic.

Indicators to Look For

IndicatorNormal trafficTunneling traffic
Query name lengthMostly short, readable namesLong names, often close to label and name limits
Character entropyLow, dictionary-like wordsHigh, random-looking Base32 or hex strings
Unique subdomains per domainA few to a few hundredThousands of never-repeated subdomains
Record typesMostly A, AAAA, HTTPS, CNAMEUnusually high share of TXT, NULL, or CNAME
Query volume to one domainSpiky, tied to user activitySteady beaconing, including off-hours
Response sizeSmallConsistently large TXT responses

No single indicator is conclusive. The strongest signal is a combination: one registered domain receiving a high volume of unique, high-entropy, long subdomains, frequently with TXT queries.

Finding Top Talkers in a Zeek DNS Log

If you run Zeek, this pipeline counts queries per registered domain (approximated as the last two labels) and shows the domains receiving the most traffic:

zeek-cut query < dns.log \
  | awk -F. 'NF>=2 {print $(NF-1)"."$NF}' \
  | sort | uniq -c | sort -rn | head -20

zeek-cut extracts the query field, awk trims each name to its last two labels, and the sort | uniq -c combination counts them. A domain you do not recognize near the top of that list deserves a closer look. For domains under multi-part suffixes like co.uk, a proper public-suffix-aware parser is more accurate.

Scoring Queries by Length and Entropy

The script below reads one query name per line (for example, exported from your resolver logs) and flags names whose leftmost labels are long and random-looking. It uses only the Python standard library.

import math
import sys
from collections import Counter, defaultdict

def shannon_entropy(text: str) -> float:
    if not text:
        return 0.0
    counts = Counter(text)
    length = len(text)
    return -sum((n / length) * math.log2(n / length) for n in counts.values())

MIN_LEN = 40        # characters in the subdomain part
MIN_ENTROPY = 3.5   # bits per character

suspicious = defaultdict(int)
unique_subs = defaultdict(set)

for line in sys.stdin:
    name = line.strip().rstrip(".").lower()
    labels = name.split(".")
    if len(labels) < 3:
        continue
    base = ".".join(labels[-2:])
    sub = "".join(labels[:-2])
    unique_subs[base].add(sub)
    if len(sub) >= MIN_LEN and shannon_entropy(sub) >= MIN_ENTROPY:
        suspicious[base] += 1

for base, hits in sorted(suspicious.items(), key=lambda kv: kv[1], reverse=True):
    print(f"{base}\tflagged={hits}\tunique_subdomains={len(unique_subs[base])}")

Run it with python3 dns_entropy.py < queries.txt. It prints each base domain with the number of flagged queries and the total number of unique subdomains seen, sorted by the worst offenders. Tune MIN_LEN and MIN_ENTROPY against your own baseline, and add known-good vendor domains to an allowlist before alerting on the output. Commercial DNS security platforms apply the same ideas with machine learning models and domain reputation data layered on top.

How to Prevent and Block DNS Tunneling

Detection tells you it is happening. These controls make it hard to do in the first place.

  1. Force all DNS through your own resolvers. Block outbound port 53 (UDP and TCP) and DNS over TLS on port 853 from every host except your designated resolvers. Otherwise malware can simply query an external resolver directly and bypass your logging.
  2. Control encrypted DNS. Browsers and malware can use DNS over HTTPS to hide queries inside ordinary HTTPS. Use managed browser policies to point DoH at your own resolver or disable it, and block known public DoH endpoints at the proxy or firewall.
  3. Use a DNS firewall. Response Policy Zones and similar resolver-level policies let you block known tunneling and C2 domains, newly registered domains, and domains with poor reputation. See what a DNS firewall is for how to deploy one.
  4. Remove internet resolution from servers that do not need it. Internal servers that only talk to internal systems can use a resolver that answers only internal zones, which removes the outbound channel entirely. Split-horizon DNS is a common way to structure this.
  5. Rate-limit and alert on anomalies. Unusually high query rates from a single client to a single domain are a strong signal worth alerting on even if you do not block them.
  6. Retain DNS logs. Keep query logs long enough to investigate incidents after the fact. Tunneling is often discovered weeks later.

Here is an example nftables ruleset for a Linux gateway that only allows the internal resolver at 192.0.2.53 to send DNS to the internet:

#!/usr/sbin/nft -f
table inet dns_egress {
    chain forward {
        type filter hook forward priority 0; policy accept;

        # The internal resolver may query the internet
        ip saddr 192.0.2.53 udp dport 53 accept
        ip saddr 192.0.2.53 tcp dport 53 accept

        # Everyone else must use the internal resolver
        udp dport 53 drop
        tcp dport 53 drop
        tcp dport 853 drop
        udp dport 853 drop
    }
}

Load it with sudo nft -f dns-egress.nft. Clients on the LAN can still reach 192.0.2.53 directly because that traffic is not forwarded through the gateway, but any attempt to query an outside resolver is dropped. Blocking 853 covers DNS over TLS and DNS over QUIC. DoH runs over 443 and needs to be handled at the proxy or with browser policy, as described above.

This does not stop tunneling through your own resolver, since the resolver will still recurse to the attacker's domain. That is why egress control has to be paired with logging, anomaly detection, and a DNS firewall.


DNS Tunneling FAQ

The technique itself is not illegal, and security teams use tunneling tools in authorized tests. Using it to exfiltrate data, control malware, or bypass network controls you are not authorized to bypass is illegal in most jurisdictions and a violation of almost every acceptable use policy.

It is slow compared with normal connections, typically kilobytes per second, because each query carries only a couple of hundred bytes and responses are limited in size. That is still plenty for stealing credentials or running command and control.

No. DNSSEC authenticates that DNS answers came from the legitimate zone owner. In a tunneling scenario the attacker is the legitimate owner of their own domain, so DNSSEC has nothing to object to.

Yes, if clients can use an external DoH resolver. The queries are hidden inside HTTPS, so your network sensors and internal resolver never see them. Controlling which DoH resolvers are allowed is an important part of preventing tunneling.

TXT is the most common because it can carry long strings. NULL, CNAME, MX, and even A and AAAA records are also used. A sudden rise in TXT or NULL queries from workstations is worth investigating.

A traditional port-based firewall cannot, because the traffic is valid DNS on an allowed port. You need DNS-aware tooling such as resolver logs, a DNS firewall, an IDS like Zeek or Suricata, or a DNS security service that inspects query content.

DNS tunneling abuses DNS as a covert data channel without changing any answers. DNS hijacking changes how names resolve so that users are sent to the wrong servers. They are different attacks with different defenses.

In an authorized test, run a known tunneling tool from an internal host against a domain you control and see whether your logs, alerts, and DNS firewall catch it. If the session works and nothing alerts, you have a gap.

Conclusion

DNS tunneling works because DNS is trusted, ubiquitous, and rarely inspected. It turns your own resolvers into a relay for data you never meant to let out, and it does so without breaking any protocol rule. The good news is that the defenses are well understood: force all DNS through resolvers you control, keep encrypted DNS on a short leash, log every query, look for long, high-entropy, never-repeating subdomains, and put a policy layer in front of your resolvers that can block known-bad and suspicious domains.

None of these controls is exotic, and most organizations already have the pieces. The key shift is treating DNS as a security-relevant channel worth monitoring rather than invisible plumbing. For a broader checklist of protections, see how to secure DNS against attacks.

Here are some useful references for going deeper on DNS tunneling and its defenses:

  1. Cloudflare Blog: Using the power of Cloudflare's global network to detect malicious domains using machine learning — how DNS tunneling works and how anomalous query patterns are detected at scale.
  2. RFC 1035: Domain Names - Implementation and Specification — defines label and name length limits and the TXT and NULL record types abused by tunnels.
  3. Zeek Documentation: Zeek Network Security Monitor — documentation for the network monitor whose dns.log is widely used for DNS threat hunting.
  4. MITRE ATT&CK: Application Layer Protocol: DNS (T1071.004) — documents real-world adversary use of DNS for command and control.
  5. ISC BIND 9 Documentation: BIND 9 Administrator Reference Manual — covers query logging and Response Policy Zones for blocking malicious domains.
Tags :
Share :

Related Posts

What Is the Difference Between Authoritative and Recursive DNS Servers?

What Is the Difference Between Authoritative and Recursive DNS Servers?

When someone says "the DNS server," they could mean two completely different machines doing two completely different jobs. One kind of server holds t

Continue Reading
Can DNS settings affect website speed?

Can DNS settings affect website speed?

Yes, DNS settings can significantly affect the speed at which a website loads for its users. DNS, or Domain Name System, is often likened to the inte

Continue Reading
Can You Use a CNAME Record on the Root Domain?

Can You Use a CNAME Record on the Root Domain?

It is one of the most common DNS questions there is. Your hosting platform says "add a CNAME pointing to myapp.example-cdn.net," it works perfectly

Continue Reading