Skip to content
RESEARCH INDEX BREACHROAD / INTELLIGENCE NOTE
Threat Detection

DNS tunneling detection: identify DNS C2 and exfiltration

Detect DNS tunneling and C2 beaconing through label entropy, query length, NXDOMAIN ratios, record types, timing and endpoint-to-resolver correlation.

PUBLIC RESEARCH
AUTHOR
/ Pentester (OSCP, PNPT)
PUBLISHED
1 May 2026
READING TIME
20 min read
TOPIC
Threat Detection
DNS tunneling detection: identify DNS C2 and exfiltration

DNS tunneling uses Domain Name System queries and responses to carry data or command-and-control communication. MITRE ATT&CK maps DNS use to T1071.004 and notes that commands and results may be embedded in queries or response records. Reliable detection is not a single threshold such as “a long domain means malware”. It requires resolver telemetry, endpoint context, a baseline for legitimate traffic and correlation across several individually weak signals.

This guide explains how to engineer DNS tunnel detection from source data and statistical features through alert triage and controlled validation. It focuses on defensive analytics and synthetic testing; it does not explain how to build an exfiltration channel.

Why DNS can conceal command traffic and data movement

DNS is essential to almost every enterprise network. Outbound name resolution is commonly permitted, and traffic to a resolver is often treated as trusted infrastructure. A domain name contains multiple labels, allowing a client to generate many unique subdomains beneath a zone controlled by an operator. Responses can use A, AAAA, CNAME or TXT records depending on the implementation and communication direction.

RFC 1035 defines the message, name and resource-record formats. An unusual record is not attack proof. TXT supports legitimate mail and ownership validation, while long unique names occur in CDNs, tracking, anti-fraud systems and service discovery. Detection must therefore answer more than “what did the query look like?” It should establish which device and process sent it, to which registered domain, at what cadence, with which response and in what organisational context.

MITRE distinguishes two practical patterns:

  • beaconing, in which a client periodically checks for commands over DNS;
  • tunnelling, in which query or response fields encode transferred information.

The boundary is not always clear. Low-throughput C2 may transmit only a host identifier and short instructions, while exfiltration tends to create more labels, greater uniqueness and a larger byte volume.

DNS visibility architecture

A managed organisational resolver is usually the best observation point because it sees logical client queries and upstream responses. Network sensors such as Zeek add transport context. For unencrypted DNS, Zeek dns.log can record source and destination, query, type, response code, answers, TTL and round-trip time.

A minimum analytics record should include:

FieldDetection purpose
timestampcadence, bursts and process correlation
client or device IDattribution, including remote endpoints
resolverdetecting bypass of the approved resolution path
query and registered domainlabel features and campaign aggregation
qtypeA, AAAA, TXT, CNAME and less common types
rcodeproportions of NXDOMAIN, SERVFAIL and NOERROR
answers and TTLresponse shape, stability and variation
inbound/outbound bytesasymmetry and estimated throughput
process and userseparating browsers, managed agents and unknown binaries

A perimeter firewall may show many UDP/53 packets to one resolver but lose individual client identity behind NAT and provide no process lineage. Endpoint telemetry without DNS responses creates a different gap. Join these layers through a durable device identifier and synchronised clocks.

High-value DNS tunnelling features

No single feature is decisive. Mature analytics aggregate them per device and registered domain over multiple time windows.

Label length and count

A data-carrying channel often uses longer subdomains or more labels. Measure complete QNAME length, longest-label length, label count and the proportion of names approaching protocol limits. Do not select one universal threshold before establishing a baseline. A legitimate telemetry endpoint can produce similar values.

Entropy and character set

Encoded or encrypted content is often more random than human-readable words. Calculate label entropy, digit ratio, vowel ratio, unique-character count and resemblance to Base32, Base64url or hexadecimal alphabets. Treat these as features rather than an attempt to decode the payload. A CDN object hash can have equally high entropy.

Subdomain uniqueness

Count unique subdomains below a registered domain and calculate repetition ratio. A tunnel transferring successive chunks may issue almost exclusively new names. Cache busting, tracking and DNS-based service discovery can create the same signal, so process ownership and fleet-wide prevalence are essential context.

NXDOMAIN and other response codes

A high NXDOMAIN proportion can arise from a domain-generation algorithm, typographical errors, broken applications or a channel where the authoritative server only needs to observe the query. Measure NXDOMAIN by device, registered domain and process, but keep DGA and tunnelling hypotheses distinct. A tunnel can return NOERROR for every request.

Record types and data direction

A series of unusually long TXT responses deserves investigation, but TXT-only analytics miss channels using A, AAAA or CNAME. Track the qtype mix, response length, answer count and byte asymmetry. For exfiltration, most information may travel in queries; for download or C2, more may be carried in responses.

Timing and regularity

A beacon may query at a near-constant interval with optional jitter. Analyse interval distribution, autocorrelation, activity outside normal hours and persistence when the user is inactive. Scheduled jobs, monitoring tools and update agents are also regular, but normally have a known owner, signer and deployment pattern.

TTL and domain infrastructure

An unusually low or fixed TTL can strengthen a hypothesis, but CDNs also use short TTLs. Add domain age, first-seen time in the organisation, name-server changes and relationships to other indicators. Reputation should inform behaviour, not replace it. A new supplier domain can be legitimate, while an old domain can be compromised.

Use multi-feature scoring instead of one threshold

A practical detector assigns weight to independent signals. The following is a conceptual starting point that must be calibrated with local data:

SignalIllustrative weight
high entropy in the longest label2
high unique-subdomain ratio3
regular cadence over an extended period2
domain first seen recently across the organisation1
process rarely associated with DNS3
direct DNS outside the managed resolver4
anomalous bytes for the device-domain pair3

These values are not a deployable policy. Determine percentiles by device class, then measure precision and recall against labelled benign and synthetic samples. A developer workstation, recursive resolver, domain controller and kiosk have fundamentally different distributions.

The score also needs evidence that reduces suspicion: an approved executable, a documented EDR mechanism, a domain belonging to an in-use service and a consistent fleet-wide pattern. Allowlisting should be precise—registered domain plus owner and process—and reviewed periodically. Excluding an entire cloud provider creates a large blind spot.

Vendor-neutral defensive analytics logic

The following pseudocode describes a safe analytical pipeline rather than a SIEM-specific query:

GROUP DNS events BY device_id, registered_domain IN 15 minutes
CALCULATE query_count, unique_subdomain_ratio,
          p95_label_length, mean_label_entropy,
          nxdomain_ratio, qtype_distribution,
          interval_regularity, total_query_bytes
JOIN endpoint process telemetry ON device_id AND time_window
ALERT WHEN multi_feature_score >= environment_threshold
  AND NOT approved_domain_process_pair

Repeat aggregation over a 24-hour window. A low-throughput tunnel may never cross a short burst threshold yet sustain an unusual feature combination for hours. Conversely, an extreme one-minute spike may be a failed agent rather than command-and-control.

DNS over HTTPS and DNS over TLS change visibility

RFC 8484 defines DNS over HTTPS. Correctly encrypted DoH prevents a passive network sensor from seeing QNAMEs inside HTTPS. The answer is not to block all web encryption. The organisation needs a resolution policy: managed devices use an approved resolver or client, while unauthorised resolvers are identified through destination domains and addresses, TLS metadata where available, browser configuration and endpoint events.

A modern design can preserve privacy and security visibility through an organisational encrypted resolver with policy-governed logging. DNS history reveals user behaviour, so retention, access and field collection require explicit data-minimisation decisions.

Applications can implement their own DoH stack independently of the operating system. Restricting outbound port 53 will not stop a query carried in HTTPS. EDR, application control and egress proxies provide the process context a traditional firewall lacks.

Detect resolver bypass before complex tunnelling

One of the strongest and simplest detections is architectural: an ordinary endpoint sends UDP/TCP 53 directly to the Internet or connects to an unapproved DoH service. If policy requires all devices to use internal resolvers, this activity is both a high-quality signal and an egress-control failure.

Permit external DNS only from resolvers. Record endpoint DNS configuration changes and the process opening a connection. Extend the same policy to remote users through a secure web gateway, VPN or resolver agent. Test captive-portal and emergency workflows before enforcement so that the defensive control does not create an operational outage.

This design aligns with Zero Trust architecture and internal network segmentation testing: an endpoint should not receive arbitrary egress merely because it is inside the corporate network.

Correlate the resolver with endpoint identity

The most important triage question is often: which process caused the requests? A browser using a business application, an approved security agent and an unsigned executable launched from a temporary directory require different priorities.

Correlate DNS with:

  • process trees and code-signing identity;
  • user and session type;
  • first execution or installation time;
  • network connections from the same process;
  • persistence or scheduled-task creation;
  • related e-mail, identity and cloud alerts;
  • domain prevalence across the fleet.

Do not trust a process name or reverse-DNS value by itself. Names are easy to imitate, and many legitimate applications use a shared host process. Preserve hash, signer, path, parent and installation metadata.

DNS tunnelling alert triage

An analyst should follow a repeatable sequence:

  1. verify log completeness and quality, including packet loss and NAT effects;
  2. identify the first and last device-domain occurrence;
  3. compare the pattern with devices in the same class;
  4. establish process, user, parent and file reputation;
  5. inspect qtype, rcode, answers, TTL, timing and byte volume;
  6. determine domain ownership and legitimate service use without blindly trusting reputation;
  7. search the organisation for related labels and domains;
  8. if confidence and impact are high, isolate the device under the incident playbook and preserve evidence.

Do not actively query a suspicious domain from an analyst workstation. Use controlled research infrastructure, passive sources or a designated resolver. Direct contact can notify an operator and contaminate evidence.

Validate the analytic without exfiltrating data

Detection testing does not require real business data or public attacker infrastructure. In a controlled segment, generate synthetic queries with tunnel-like statistical properties to a domain owned by the test team. Change one feature at a time: label length, entropy, qtype, NXDOMAIN behaviour, cadence or process identity. Confirm ingestion, aggregation, alert context and playbook routing.

Then run benign regression cases for CDNs, software updates, EDR telemetry and developer tools. Measure:

  • precision, the proportion of alerts that represent the intended suspicious behaviour;
  • recall across a controlled variant set;
  • time from query to actionable alert;
  • percentage of events enriched with a process identity;
  • exception count and age;
  • SIEM query and storage cost.

An analytic that cannot be maintained or triaged is not complete. Move it into a governed detection engineering and Sigma lifecycle, version it and rerun tests whenever the schema, parser or baseline changes.

Common implementation failures

One query-length threshold

It alerts on legitimate services and misses channels using short fragments. Aggregate behaviour and combine independent features.

Inspecting only TXT records

It ignores other record types. Keep the core detector qtype-independent and add type-specific evidence as a confidence booster.

A global domain allowlist

It can conceal a compromised subdomain or an unexpected process. Bind an exception to domain, process, owner and expected pattern.

No DoH visibility

Port 53 appears clean while an application uses its own HTTPS resolver. Govern resolver endpoints and collect process telemetry.

One baseline for every device

Resolvers and laptops do not share a distribution. Segment the population and update models carefully so that malicious behaviour does not become the new baseline.

Deployment checklist

  • Route managed devices through approved resolvers.
  • Block direct external DNS except from authorised resolvers.
  • Collect query, qtype, rcode, answer, TTL, size and client identity.
  • Join resolver events with EDR process and user/device identity.
  • Aggregate by registered domain and device over several windows.
  • Combine entropy, length, uniqueness, timing, NXDOMAIN and volume.
  • Separate DGA, beaconing and tunnelling hypotheses while correlating their results.
  • Govern DoH/DoT and applications with embedded resolution.
  • Version rules, thresholds and exceptions under an accountable owner.
  • Test with synthetic queries and no production data.
  • Apply privacy limits, retention and access control to DNS logs.
  • Measure triage quality rather than alert volume alone.

Frequently asked questions

Does high domain entropy prove DNS tunnelling?

No. CDN hashes, tracking identifiers and telemetry can look similar. Entropy is one feature that needs process, cadence, uniqueness and volume context.

Does DNSSEC stop DNS tunnelling?

No. DNSSEC provides authenticity and integrity for selected DNS data. It does not prevent a domain owner from creating records or a client from submitting queries, so it is not an anti-tunnelling control.

Is blocking TXT a solution?

No. It breaks legitimate uses and does not stop channels using other record types. Resolver governance, egress control and behaviour analytics are more durable.

How can a SOC detect tunnelling over DoH?

Use an approved encrypted resolver, enforce permitted DoH destinations, and correlate endpoint process data with egress-proxy telemetry. A passive sensor cannot read a properly encrypted HTTPS payload without an authorised control point.

DNS detection needs both network and endpoint evidence

Breachroad designs and validates analytics through purple-team exercises, segmentation reviews and security monitoring programmes. The deliverable is not a static “long domain” rule. It is a measurable pipeline containing source data, scoring, process context, triage, an owner and regression tests.

Primary sources and documentation

SHARE / COPY