What is DNS Tunneling?

DNS tunneling is a technique that encodes arbitrary data inside DNS queries and responses, effectively turning the Domain Name System into a covert communication channel. Because DNS traffic is almost universally allowed through firewalls and network security controls, attackers exploit it to exfiltrate data, establish command-and-control (C2) channels, and bypass captive portals — all hidden inside what looks like ordinary name resolution.

DNS was designed to translate domain names into IP addresses, not to carry payloads. But the protocol's structure — hierarchical labels, multiple record types, and the guarantee that queries will be forwarded by recursive resolvers — makes it a surprisingly effective transport layer for smuggling data past network defenses.

How DNS Tunneling Works

At its core, DNS tunneling encodes data into the parts of a DNS message that the protocol allows to vary: the query name (subdomain labels) and the response records. The attacker controls an authoritative nameserver for a domain they own — say t.evil.example. The client on the victim network encodes data as subdomain labels and sends DNS queries for those names. The recursive resolver on the victim's network dutifully forwards these queries up the DNS hierarchy until they reach the attacker's authoritative server, which decodes the data from the query, processes it, and sends a response with encoded data in the answer section.

Compromised Client Recursive Resolver FIREWALL Attacker's Nameserver DNS query DNS response Encoded query: dGhlIHNlY3JldCBkYXRh.t.evil.example Encoded response (TXT record): "Y21kOiBzbGVlcCA1OyB3aG9hbWk=" DNS Tunneling Data Flow Data encoded in subdomains (upstream) and DNS records (downstream) Internet Upstream (data exfil) Downstream (C2 commands)

The key insight is that the victim's recursive resolver acts as an unwitting relay. It sees what appears to be a normal DNS lookup and forwards it through the firewall. The attacker never needs a direct connection to the compromised machine.

Encoding Data in DNS Queries (Upstream)

The upstream channel — data flowing from the compromised client to the attacker — uses the query name itself. DNS labels (the parts between dots) can contain up to 63 bytes each, and a full domain name can be 253 bytes total. The client takes whatever data it wants to send, encodes it using Base32 or Base64, splits it into label-sized chunks, and appends the attacker's domain as the suffix:

dGhlIHNlY3JldCBkYXRh.chunk2.t.evil.example

Here dGhlIHNlY3JldCBkYXRh is Base64-encoded payload data, and t.evil.example is the attacker's tunnel domain. The recursive resolver resolves this by querying the authoritative server for evil.example, which the attacker controls. Base32 encoding is often preferred over Base64 because DNS names are case-insensitive in practice, and Base32 uses only uppercase letters and digits.

The upstream bandwidth is inherently limited. With 253 bytes per query and encoding overhead, each DNS query carries roughly 150-180 bytes of actual data. But by sending many queries per second, throughput of tens of kilobytes per second is achievable — more than enough for exfiltrating credentials, documents, and database dumps.

Encoding Data in DNS Responses (Downstream)

The downstream channel — data flowing from the attacker back to the client — uses the DNS response records. Different record types offer different capacities:

TXT Records

TXT records are the most commonly abused type because they are designed to hold arbitrary text data. A single TXT record can contain up to 65,535 bytes (though practical limits are lower due to UDP message size constraints, typically around 4,000 bytes with EDNS0). TXT records legitimately contain SPF policies, DKIM keys, domain verification tokens, and other text — so TXT queries don't immediately look suspicious. Tools like iodine and dnscat2 favor TXT records for their downstream channel.

CNAME Records

A CNAME record points one domain name to another. The attacker can encode data in the target domain name, similar to the upstream encoding. CNAME responses have lower capacity than TXT (limited to 253 bytes of encoded data) but are less conspicuous because CNAME lookups are extremely common in normal DNS traffic — every CDN and cloud service uses them.

NULL Records

NULL records (type 10) can carry arbitrary binary data up to 65,535 bytes. They are rarely used in legitimate DNS, which makes them effective for tunneling but potentially easier to detect. The iodine tool uses NULL records by default when available because they offer the highest raw bandwidth.

MX and SRV Records

Some tunneling implementations use MX records (which contain a domain name as the mail exchange) or SRV records (which contain a target domain and port numbers) to encode downstream data. These offer less capacity but add variety to the record types being queried, making statistical detection harder.

A and AAAA Records

Even A records (4 bytes) and AAAA records (16 bytes) can carry encoded data, though at very low bandwidth. An A record response of 10.83.69.67 could encode four bytes of payload. Some tunneling tools fall back to A/AAAA records when other types are blocked, accepting the severe throughput penalty in exchange for maximum stealth.

DNS Tunneling Tools

Several mature tools implement DNS tunneling with varying levels of sophistication:

iodine

iodine creates a full IP-over-DNS tunnel, establishing a virtual network interface (TUN device) on both the client and server. It negotiates the best available encoding and record type, supports downstream via NULL, TXT, CNAME, and MX records, and achieves throughput up to 680 kbit/s under optimal conditions. iodine works at the network layer, meaning any IP-based application can use the tunnel transparently — SSH, HTTP, anything. It can also use raw UDP on port 53 directly when the client has network access to the server, bypassing the DNS protocol entirely for higher performance.

dnscat2

dnscat2 is designed specifically for command-and-control. Rather than creating a network tunnel, it provides an encrypted, authenticated session layer over DNS. It supports interactive shells, file transfers, and port forwarding. dnscat2 operates entirely within DNS protocol constraints and requires no special network privileges on the client — a standard user process can run it. The server component provides a console interface for managing multiple active sessions simultaneously.

dns2tcp

dns2tcp provides TCP-over-DNS tunneling. It runs as a daemon on both ends and forwards TCP connections through DNS queries. Its design is simpler than iodine's — it doesn't create a virtual network interface but instead proxies individual TCP connections. dns2tcp supports TXT and KEY records for downstream data and is commonly used to tunnel SSH connections through restrictive networks.

DNSExfiltrator

DNSExfiltrator is focused purely on data exfiltration rather than bidirectional tunneling. It chunks files into DNS queries, supports multiple encoding schemes, and can use DNS over HTTPS (DoH) as a transport — which adds TLS encryption on top of the DNS encoding, making interception by network security tools significantly harder.

Use Cases: Data Exfiltration

DNS tunneling is a favored technique for data exfiltration — stealing data from a compromised network. The scenario typically unfolds like this:

  1. An attacker compromises a machine inside a corporate network (via phishing, supply chain attack, or other initial access vector).
  2. The compromised machine has no direct internet access — outbound HTTP, HTTPS, and other protocols are blocked by the firewall. But DNS queries are allowed, because blocking DNS would break all name resolution.
  3. The attacker registers a domain and sets up a DNS tunneling server as the authoritative nameserver.
  4. Malware on the compromised machine encodes stolen data (credentials, database records, intellectual property) into DNS queries for the attacker's domain.
  5. The internal recursive resolver forwards these queries to the attacker's server, passing through the firewall as normal DNS traffic.

Even in environments with DNS security controls, exfiltration often succeeds because the volume of legitimate DNS traffic provides cover. A large enterprise network generates millions of DNS queries per hour; a few hundred anomalous queries can easily go unnoticed without purpose-built detection.

Use Cases: Command and Control (C2)

DNS tunneling provides a resilient C2 channel — a communication path between an attacker and malware deployed inside a target network. The C2 use case is bidirectional: commands flow downstream from the attacker to the malware, and results flow upstream.

C2 over DNS: Beacon Pattern Malware C2 Server (NS) beacon.t.evil.example (TXT?) TXT "d2hvYW1p" (cmd: whoami) cm9vdA==.r.t.evil.example (result: root) TXT "NOP" (no new command) sleep beacon.t.evil.example (TXT?) TXT "Y2F0IC9ldGMvcGFzc3dk" (cmd: cat /etc/passwd) t = 0s t = 1s t = 30s t = 60s

A typical DNS-based C2 loop works as a polling mechanism. The malware periodically sends a "beacon" query to the C2 domain. If the attacker has issued a new command, the DNS response contains the encoded command. The malware executes it, encodes the output into subsequent DNS queries, and then sleeps before beaconing again. The sleep interval can be randomized (a technique called jitter) to avoid creating detectable periodic patterns in DNS logs.

DNS C2 is valued by sophisticated attackers for its resilience. Blocking it requires blocking DNS entirely or implementing deep inspection of DNS content — something many organizations still do not do. Even if the primary C2 channel (say, HTTPS to a compromised server) is detected and blocked, a DNS-based backup channel may persist unnoticed.

Bypassing Captive Portals

A more benign use of DNS tunneling is bypassing captive portals — the login pages you encounter at hotels, airports, and coffee shops. Many captive portals block HTTP/HTTPS traffic until you authenticate, but allow DNS queries to pass through so that the portal page itself can load. Tools like iodine exploit this gap: you tunnel your internet traffic through DNS to a server you control, bypassing the portal entirely.

This works because the portal's network allows DNS resolution to arbitrary domains. Your DNS tunnel queries reach your own authoritative server, which proxies your traffic to the open internet. The portal never sees any HTTP traffic to intercept.

Real-World APT Usage

DNS tunneling is not a theoretical concern — it has been used by some of the most sophisticated threat actors in documented campaigns:

The SolarWinds case is particularly instructive. The SUNBURST backdoor generated subdomain labels that encoded the victim organization's domain name and a unique machine identifier. The C2 server at avsvmcloud.com would respond with a CNAME record pointing to a second-stage C2 domain only for targets of interest. This initial DNS-based triage allowed the attackers to remain selective and avoid exposing their operational infrastructure to non-target victims.

Detection Methods

Detecting DNS tunneling requires analyzing DNS traffic for patterns that deviate from normal name resolution. No single indicator is definitive, but combining multiple signals yields reliable detection:

Query Length Analysis

Normal DNS queries are short. Most legitimate domain names are under 30 characters. DNS tunneling queries are long — often close to the 253-byte maximum, with subdomain labels packed with encoded data. A query like dGhlIHNlY3JldCBkYXRhIHRoYXQgd2Ugd2FudA.chunk2.t.evil.example is immediately suspicious by length alone. Monitoring for queries with unusually long subdomain labels (above 50 characters) or many labels (more than 5 dots) catches many tunneling implementations.

Entropy Analysis

Legitimate domain names consist of recognizable words and patterns — mail.google.com, cdn.shopify.com, api.github.com. Base32 and Base64 encoded data has high Shannon entropy — it looks random. Computing the entropy of subdomain labels and flagging queries above a threshold (typically 3.5-4.0 bits per character) is one of the most effective detection techniques.

Entropy Comparison: Normal vs Tunneling Shannon Entropy (bits per character) Frequency 1.0 2.0 3.0 4.0 5.0 Normal DNS mail.google.com DNS Tunnel dGhlIHNlY3JldA.t.evil.example Detection threshold

Query Volume and Frequency

A normal client might query a given domain a few times per session. DNS tunneling generates a high volume of queries to the same domain or set of domains in a short period. Tracking the number of unique subdomains queried per parent domain per client is a strong signal — if a single client queries 500 unique subdomains under t.evil.example within an hour, that is almost certainly tunneling.

Record Type Distribution

Legitimate DNS traffic is dominated by A, AAAA, and HTTPS records, with occasional MX, TXT, and CNAME queries. A client that generates a disproportionate number of TXT or NULL record queries is suspicious. Some detection systems flag any NULL record queries at all, since they have virtually no legitimate use.

Response Size Analysis

Normal DNS responses are small — typically under 512 bytes. DNS tunnel responses, especially those using TXT records with EDNS0, are often significantly larger. Monitoring for consistently large DNS responses (above 1000 bytes) to the same domain can indicate tunneling.

NXDOMAIN Ratios

Some tunneling implementations generate queries for domains that don't exist in the normal sense — the "domain" is just encoded data. Depending on the implementation, this can cause elevated NXDOMAIN (non-existent domain) response rates from the perspective of intermediate resolvers. Monitoring NXDOMAIN ratios per client can surface tunneling activity.

Timing Analysis

DNS C2 beacons often exhibit periodic patterns — even with jitter, the underlying periodicity can be detected using frequency analysis techniques like Fast Fourier Transform (FFT) on the inter-query intervals. A client making DNS queries to the same domain at roughly 30-second intervals, with small random variations, stands out from the bursty, event-driven pattern of normal DNS lookups.

Defense Strategies

Defending against DNS tunneling requires a layered approach because no single control is sufficient:

DNS Monitoring and Logging

The foundation of any DNS defense is comprehensive logging. Log all DNS queries and responses at the recursive resolver level, including the full query name, record type, response size, and client IP. Feed these logs into a SIEM or dedicated DNS analytics platform. Without visibility into DNS traffic, detection is impossible.

DNS Firewalling and RPZ

Deploy Response Policy Zones (RPZ) or DNS firewalls that block queries to known malicious domains. Threat intelligence feeds provide lists of domains associated with DNS tunneling tools and C2 infrastructure. This blocks known threats but does not detect novel tunneling domains.

Restrict DNS Egress

Configure your firewall to allow DNS queries (UDP/TCP port 53) only to your designated internal recursive resolvers. Block direct DNS queries from endpoints to external resolvers. This forces all DNS traffic through your monitored resolvers, preventing attackers from using direct DNS communication to bypass your logging infrastructure. Pay particular attention to blocking DNS over HTTPS (DoH) and DNS over TLS (DoT) to external resolvers like 1.1.1.1 or 8.8.8.8, as these encrypted protocols can carry tunneled data invisible to network inspection.

Query Length and Entropy Policies

Implement rules at the resolver or DNS firewall to block or alert on queries exceeding certain length thresholds or entropy scores. A policy that blocks any query where a single label exceeds 50 characters, or where the total query name exceeds 150 characters, will break most tunneling tools while affecting virtually zero legitimate traffic.

Rate Limiting

Apply per-client rate limits on DNS queries at the resolver level. Normal clients rarely exceed 100 queries per minute. DNS tunneling at any useful throughput requires hundreds or thousands of queries per minute. Rate limiting throttles tunneling to impractical speeds while being invisible to normal users.

DNSSEC Validation

While DNSSEC does not directly prevent DNS tunneling, enforcing DNSSEC validation at your resolvers increases the overhead for attackers. They must properly sign their tunnel domains, and the additional response size from DNSSEC records makes their traffic more anomalous. More importantly, DNSSEC prevents DNS spoofing attacks that could be used in conjunction with tunneling.

Managed DNS Services

Enterprise DNS security services (Cisco Umbrella, Palo Alto DNS Security, Zscaler, Infoblox BloxOne Threat Defense) apply machine learning models to DNS traffic in real time, detecting tunneling based on combinations of the signals described above. These services see DNS traffic across thousands of organizations, giving them broad visibility into emerging tunneling domains.

Defense-in-Depth: DNS Tunneling Controls Endpoint Controls Block direct DoH/DoT to external resolvers | EDR monitoring | Application allowlisting Network Controls Restrict DNS egress to internal resolvers | Firewall port 53/853/443 | Rate limiting Resolver Controls RPZ / DNS firewall | Query length limits | Entropy scoring | DNSSEC validation Analytics & Detection SIEM integration | ML-based anomaly detection | Timing analysis | Threat intel feeds Incident Response Automated blocking | SOC alerting | Forensic DNS log retention | Domain takedown

DNS Tunneling vs DNS over HTTPS

It is important to distinguish DNS tunneling from DNS over HTTPS (DoH). DoH encrypts legitimate DNS queries to protect user privacy — the queries are still standard name resolution requests, just wrapped in TLS. DNS tunneling uses the DNS protocol as a data transport, encoding non-DNS data inside the query and response structure. However, the two can be combined: tunneling tools like DNSExfiltrator can use DoH as the transport, gaining TLS encryption on top of the DNS encoding. This makes detection particularly challenging because network security tools cannot inspect the contents of DoH traffic without breaking the TLS connection.

Protocol Limitations and Throughput

DNS tunneling has inherent performance limitations that distinguish it from purpose-built tunneling protocols like VPNs:

These limitations mean DNS tunneling is not suitable for high-bandwidth activities like streaming or large file transfers. But for exfiltrating text files, credentials, and database dumps — or for low-bandwidth C2 communication — the throughput is more than sufficient.

DNS Tunneling and the Network Layer

DNS queries traverse the internet like any other traffic — they are carried in IP packets routed by BGP. When you look up the route to a DNS resolver like 8.8.8.8 or 1.1.1.1, you can see the autonomous systems and AS paths involved in carrying that DNS traffic. DNS tunneling exploits the application-layer semantics of the DNS protocol, but the underlying transport is standard IP routing — the same infrastructure visible in a BGP looking glass.

This is why network-layer controls alone cannot stop DNS tunneling. Blocking traffic to suspicious IP addresses or AS numbers does not help when the tunnel traffic flows through the organization's own legitimate recursive resolver. Detection must happen at the DNS protocol layer, analyzing the content and patterns of queries rather than just their network-layer routing.

Building Detection: A Practical Checklist

If you are responsible for network security, here is a prioritized checklist for DNS tunneling defense:

  1. Log everything — Enable full query logging on all internal recursive resolvers. Retain logs for at least 90 days.
  2. Restrict DNS egress — Firewall all DNS traffic except to your designated resolvers. Block external DoH (port 443 to known DoH providers) and DoT (port 853).
  3. Deploy RPZ — Subscribe to threat intelligence feeds and block known tunneling domains.
  4. Monitor query length — Alert on queries with labels exceeding 50 characters or total length exceeding 150 characters.
  5. Monitor entropy — Compute Shannon entropy on subdomain labels and alert on values above 3.5 bits per character.
  6. Track query volume — Alert when a single client queries more than 200 unique subdomains under a single parent domain within an hour.
  7. Analyze record types — Alert on NULL record queries and unusual volumes of TXT queries from non-mail-server clients.
  8. Review periodically — Regularly audit DNS logs for newly registered domains receiving high query volumes from internal clients.

Further Reading

DNS tunneling exploits the fundamental design of the Domain Name System. To understand the protocol being abused, read our guides on how DNS works, DNS over HTTPS, and how DNSSEC secures DNS responses. To see the network layer that carries DNS traffic, try looking up the routes to major DNS resolvers:

See BGP routing data in real time

Open Looking Glass
More Articles
How TLS/HTTPS Works: Securing the Internet's Traffic
Certificate Transparency: How CT Logs Secure the Web's PKI
How Firewalls Work: Packet Filtering, Stateful Inspection, and Beyond
What is Cross-Site Scripting (XSS)?
What is Cross-Site Request Forgery (CSRF)?
What is Server-Side Request Forgery (SSRF)?