DEV Community

Cover image for What Is DNS Tunneling? How Can Hackers Hide Data Inside DNS Queries?
Aditya Sharma
Aditya Sharma

Posted on

What Is DNS Tunneling? How Can Hackers Hide Data Inside DNS Queries?

Every time a browser visits a website, a DNS query leaves the machine. The query contains a domain name. That name resolves to an address. The connection proceeds. Nothing interesting happened.

But the name in that query is arbitrary text. It is structured, subject to protocol constraints, and travels through the internet's resolution infrastructure. And it can carry information that has nothing to do with looking up an address.

That is the premise of DNS tunneling: using DNS queries and responses as a relay channel for information that has nothing to do with name resolution.


What DNS Normally Does

Before exploring how the protocol can be abused, it helps to have a clear picture of how it actually works.

When a client wants to resolve a hostname, it sends a query to a recursive resolver, typically provided by an ISP, a corporate network, or a service like 1.1.1.1 or 8.8.8.8. The recursive resolver does the work of finding the answer. If the resolver does not already have the answer cached, it works through the DNS hierarchy.

The resolution process starts at the root. Root name servers know which authoritative servers are responsible for each top-level domain. Those TLD servers know which authoritative servers are responsible for specific domains. The authoritative server for a domain knows the actual records: the IP addresses, mail exchangers, text records, and other data associated with names in that zone.

In practice, caching shortcuts this process constantly. If the recursive resolver already has a cached answer, the query never reaches root or TLD servers. The same applies at every level. What matters for understanding tunneling is the endpoint: a query under a specific domain ultimately reaches the authoritative server for that domain, and the operator of that authoritative server can see every query for every subdomain.

A DNS query contains a name and a record type. The response contains one or more resource records with the requested data. The response travels back through the same path it came from, returning to the client.


The Insight: A DNS Name Can Carry Data

A DNS domain name is divided into labels separated by dots. The name mail.example.com has three labels: mail, example, and com. Each label can be up to 63 octets long. The full wire-format domain name, including the label-length prefix bytes and the terminating zero-length root label, cannot exceed 255 octets.

These constraints are meaningful but not severe. They leave room for labels that contain encoded information rather than readable hostname identifiers.

Consider a query like:

Y2F0YWxvZzEy.session-id-8a2f.attacker-controlled.example
Enter fullscreen mode Exit fullscreen mode

The first label looks like Base64-encoded text. It might be a fragment of a file, a short command, or a sequence number identifying part of a larger dataset. The second label might identify a session or client. The final two labels reach the authoritative server for attacker-controlled.example.

This is not a special DNS record type. It is not a protocol extension. It is a normal-looking DNS query carrying information encoded into the structure of the name being queried. Any resolver that processes the query and forwards it toward the authoritative server is, without knowing it, relaying that information toward an attacker-controlled endpoint.


The Communication Channel

The channel works in both directions.

Sending data out: A compromised endpoint encodes information into subdomain labels and sends DNS queries. The queries travel to the configured recursive resolver, which performs normal resolution. Eventually, the query reaches the authoritative server for the domain the attacker controls. The server sees the query and decodes whatever information the labels contain.

Compromised host
    → recursive resolver (performs normal resolution)
    → attacker's authoritative DNS server (receives and interprets the query)
Enter fullscreen mode Exit fullscreen mode

Receiving data back: The authoritative server returns a response. The response can carry data in resource records. TXT records accept arbitrary text content and are a common choice because they do not imply a specific structured meaning. The response travels back through the recursive resolver to the client, which decodes the record content.

The recursive resolver is not complicit in this. It resolves names and returns responses, which is its job. It does not interpret attacker-defined application payloads; it forwards DNS traffic. The authoritative endpoint, controlled by the operator of the tunnel, is where the protocol data is actually interpreted and acted upon.

Different implementations make different design choices. Some use TXT records for responses, some use CNAME or NULL records, some use other types. The query name carries outbound data; the response carries inbound data. The channel is bidirectional but asymmetric. Queries have more consistent universal support than some response record types, and caching behavior can affect how frequently unique queries are needed.


Why It Can Survive Network Controls

Organizations that block direct outbound TCP and UDP connections often still permit DNS. Applications need to resolve names. Servers need to respond to queries. DNS traffic flows constantly and its presence is expected.

This is the environment DNS tunneling exploits. Traffic that uses DNS looks like DNS traffic. At a superficial level, a query to encoded-data.subdomain.example.com resembles a query to mail.example.com. Both are standard DNS queries to a valid-seeming domain.

But there are important distinctions to make here. The fact that DNS traffic is permitted does not mean it is trusted in any deep sense, and it does not mean it is uninspected. These are different properties:

  • Permitted means the firewall allows the protocol to pass.
  • Trusted means the contents are accepted as safe or unexamined.
  • Inspectable means the traffic can be decoded and analyzed by monitoring systems. Many organizations monitor DNS queries and can detect anomalies. What varies is whether that monitoring actually happens, how deep it goes, and whether anything is tuned to catch tunnel-like patterns.

The visibility situation changes with encrypted DNS. DNS over HTTPS (DoH) and DNS over TLS (DoT) encrypt the query content, which prevents passive interception by on-path network monitoring. An organization that routes all DNS through a monitored recursive resolver retains visibility. One that allows endpoints to send DoH directly to external resolvers may lose it. But encrypted DNS is not itself tunneling, and not all use of DoH or DoT is malicious. The point is that encryption affects where and whether monitoring is possible.


What the Tunnel Actually Carries

The most common malicious applications fall into two categories.

Command-and-control: A compromised machine needs to receive instructions from an operator. It periodically queries a domain the operator controls, and the responses encode instructions. This is attractive because it uses infrastructure that is often permitted and may not immediately raise alarms.

Data exfiltration: A machine that has accessed sensitive information encodes and sends it out in fragments over many queries. Large amounts of data require many queries, and the encoding overhead reduces efficiency significantly. DNS is not a high-throughput protocol. A tunnel carrying DNS traffic as its substrate faces inherent constraints: query latency, encoding overhead, label-length limits, resolver behavior, and the risk of detection from high query volume.

This is not a channel designed for bulk transfers. It is better suited to low-bandwidth communication: small commands, status signals, short credentials, session tokens, or slow incremental exfiltration of modest amounts of data. Implementations that need to send larger payloads fragment the data across many queries and reassemble at the receiving end, accepting the latency and overhead that implies.


Protocol Constraints and What They Mean

The constraints on DNS names shape what tunneling can practically carry.

A single label is limited to 63 octets. In a name encoded using a URL-safe Base64 variant, that is roughly 47 bytes of original data per label before encoding overhead. A domain name can have multiple labels before reaching the fixed portion, and the full wire-format name cannot exceed 255 octets.

These limits mean every query carries a small and bounded amount of data. Encoding schemes like Base32, Base64 variants, or hexadecimal are common choices, not because the protocol requires them, but because they produce characters that are compatible with DNS label character restrictions. Different tunneling implementations make different choices. No encoding method is universal.

Caching complicates repeated queries. If a recursive resolver caches the response to a query, a subsequent identical query may be served from cache rather than forwarded to the authoritative server. This means the authoritative endpoint may not see the repeated query. Tunneling implementations that need to send unique data per query often use unique labels to prevent cache hits, accepting that each query generates a new lookup and network traffic.

Query and response sizes matter. Large DNS responses may trigger UDP truncation and fallback to TCP, which affects timing and may be more visible to monitoring systems. Implementations designed to stay under truncation thresholds are more likely to use common query types and keep responses small.


A Concrete Conceptual Example

Consider what a normal DNS lookup looks like:

Query:  www.example.com  (type A)
Answer: 93.184.216.34
Enter fullscreen mode Exit fullscreen mode

Now contrast that with a tunneling query:

Query:  bWVzc2FnZQ.client42.attacker-controlled.example  (type TXT)
Answer: "cmVzcG9uc2U=" (TXT record content)
Enter fullscreen mode Exit fullscreen mode

The first label, bWVzc2FnZQ, is an illustrative encoded-looking value. It might represent a fragment of a command, a file chunk identifier, or a short message. The label client42 might identify the client or session. The authoritative server for attacker-controlled.example receives this query, extracts the relevant labels, decodes them, and returns an encoded response in the TXT record.

The client receives the TXT record, decodes the content, and processes the instruction or data.

These are hypothetical labels. They demonstrate the mechanism. A real implementation would add session management, fragmentation logic, error handling, and likely encryption of the payload itself. But the DNS infrastructure underneath is doing exactly what it is designed to do: resolving names and returning records.


How Defenders Detect DNS Tunneling

Detection focuses on behavioral signals that distinguish tunnel traffic from normal resolution activity. No single signal is reliable in isolation.

Label entropy and length: Legitimate subdomain labels are usually human-readable or follow consistent patterns. Labels that look like Base64, hexadecimal, or random character sequences stand out, especially when they appear in high volume or under a single domain. High label entropy is a meaningful signal but not proof of malicious intent. Generated hostnames in CDN and cloud services can produce similar patterns.

Query volume and domain concentration: A compromised host sending many queries to a single domain stands out if that domain is not one the host normally contacts. Similarly, a domain that receives a disproportionate share of queries from a single endpoint warrants investigation.

Unique subdomain ratio: Legitimate domains typically resolve a manageable set of hostnames. A domain that receives thousands of queries each with a different first label is behaving unlike a normal web service.

TXT record frequency: TXT records are less commonly queried in most environments than A or AAAA records. An endpoint that makes heavy use of TXT queries to unusual destinations is worth examining, though TXT records have many legitimate uses and this signal requires context.

Periodic beacon-like patterns: Queries at regular intervals, consistent with a client checking in for instructions, can be detected by frequency analysis. But periodic queries are also normal for many legitimate services.

Response size anomalies: TXT records returning unusual amounts of data, or responses that are consistently near truncation limits, may indicate non-standard usage.

Behavioral correlation: DNS anomalies are most meaningful when correlated with other endpoint behavior. A process generating unusual DNS queries alongside other suspicious activity is far more significant than DNS patterns in isolation.

Effective detection means combining these signals, establishing baselines for each environment, and having the process and network context to investigate alerts. A high-entropy subdomain label sent by a software update service checking for a new version is not a threat. The same pattern from an unknown process on an endpoint that should not be making external DNS queries is.


How Organizations Defend Against It

Detection without response is incomplete. Practical defenses involve controlling the DNS infrastructure itself as well as monitoring its traffic.

Route all endpoint DNS through monitored recursive resolvers. This is the single most effective control. If DNS queries pass through a resolver that logs them, behavioral analysis is possible. If endpoints can send DNS directly to arbitrary external resolvers, visibility is lost.

Restrict direct outbound DNS access. Many organizations allow port 53 outbound from all endpoints. Restricting this to specific resolvers, and blocking direct access to external DNS infrastructure, removes a significant degree of freedom from an attacker.

Monitor and alert on anomalous query patterns. This requires establishing what normal looks like. Anomaly detection without a baseline produces too many false positives to act on. With a baseline, deviations stand out.

Use response-policy zones or DNS filtering where appropriate. Blocking queries to known-malicious domains prevents contact with existing attacker-controlled infrastructure. This does not help with newly registered or unknown domains, but it addresses a meaningful subset of threats.

Investigate suspicious endpoints. DNS patterns are one piece of evidence. Correlating with process telemetry, network connections, and filesystem activity gives a full picture of what is happening on an endpoint.

Consider the implications of encrypted DNS. If endpoints use DoH to external resolvers directly, the organization loses DNS visibility unless it can inspect that traffic at the application layer or enforce routing through an internal DoH resolver that it controls.

Blocking specific record types or refusing TXT queries is a tempting but fragile defense. Tunneling implementations can adapt. The underlying capability exists as long as the endpoint can reach an authoritative server it or its operator controls.


The Lesson DNS Tunneling Teaches

DNS tunneling demonstrates something general about protocol trust.

A firewall rule that permits DNS traffic makes a decision about protocols and ports. It does not make a decision about what the traffic is carrying. A policy that allows DNS does not imply that DNS traffic will only ever be used for name resolution. The protocol's design allows it to carry arbitrary text in names and in response records. Attackers who understand this can use it.

The same principle applies elsewhere. Protocols that are permitted because they are necessary can carry data they were not designed to transport. HTTP, HTTPS, ICMP, and DNS all have examples. The common thread is that allowing a protocol does not constrain what applications can build on top of it.

Effective network security eventually requires not just asking "what protocol is this?" but also "what is this traffic actually doing?" DNS is essential infrastructure. But treating it as uniformly trustworthy because it uses port 53 is treating the container as a guarantee about the contents.

The channel into a domain's authoritative server was always there. DNS tunneling just found a use for it.

Top comments (2)

Collapse
 
furqan_ashraf profile image
Furqan Ashraf •

Clear explanation. One thing worth adding: the same DNS logs you watch for tunneling are also where lookups to known phishing and malware domains show up. A common setup is loading a daily domain blocklist into the resolver as an RPZ zone, so those queries are refused before a connection ever opens. The WhoisFreaks feed docs show what that kind of list looks like (whoisfreaks.com/documentation/threat-intelligence-feed): domain, threat type, confidence, and first/last seen dates.

Collapse
 
aditya_d_sharma profile image
Aditya Sharma •

Thanks!!!