High entropy
Shannon entropy of DNS subdomain names above 3.5 bits per character is a primary DNS tunneling indicator: legitimate domain names have low entropy (readable words), while tunneled data uses base32/base64 encoded payloads with near-maximum entropy
Query length
DNS queries with subdomain labels exceeding 50 characters are highly suspicious: legitimate hostnames rarely exceed 20-25 characters; Iodine and dnscat2 generate labels near the 63-character DNS label maximum to maximize throughput
TXT records
DNS TXT record queries to non-mail domains are a strong exfiltration indicator: legitimate TXT use is for SPF, DKIM, and domain verification; C2 tools use TXT records for response data because they can carry up to 255 bytes per string
Zeek dns.log
Zeek's dns.log captures query name, record type, response TTL, response data, and querying host for every DNS transaction: the primary data source for DNS tunneling detection without deploying additional sensors

SponsoredRetool

Retool's new app builder is where AI-generated code ships safely

Building apps with AI is easy. Getting them to production safely is another story.

Start building for free today

DNS tunneling encodes data in DNS query strings and record responses, allowing attackers to exfiltrate data and maintain C2 communication through firewalls that permit DNS traffic. Tools like Iodine create full IP-over-DNS tunnels; dnscat2 and Cobalt Strike's DNS beacon use lower-volume periodic queries for C2. Detection requires behavioral analysis rather than signature matching: tunnel traffic looks like DNS but has statistical patterns (high entropy subdomains, unusual query frequency, abnormal record types) that distinguish it from legitimate resolution. This guide covers building detection capability from network packet data through SIEM alerting.

Understand the DNS Tunneling Signatures

DNS tunneling tools leave distinctive statistical signatures. High-bandwidth tunnels (Iodine, dns2tcp): generate extremely high query volume to a single domain (hundreds per second), use long subdomain labels near the 63-character DNS limit filled with base32-encoded data, query NULL and TXT record types more than A records, and use domains registered recently with short TTLs. Low-bandwidth C2 beaconing (Cobalt Strike DNS, dnscat2): regular periodic queries to a single domain at fixed intervals (every 30-300 seconds), subdomain names change each query but follow a pattern (sequential counter encoded in the name), response TTLs are unusually short (1-5 seconds), and the queried domain has no legitimate web presence. Both leave a common indicator: the NXDOMAIN-to-resolution ratio. Legitimate domains resolve with low NXDOMAIN rates. Tunneling queries often generate many NXDOMAIN responses as the C2 server processes queries in batches. A single host generating 90%+ NXDOMAIN responses to a specific parent domain is tunneling.

Set Up Zeek for DNS Capture

Zeek (formerly Bro) is the standard open-source network security monitor for DNS analysis. Install on a span port or tap capturing all DNS traffic:

# Ubuntu/Debian
apt install zeek
# Configure interface in /etc/zeek/node.cfg
[zeek]
type=standalone
host=localhost
interface=ens3
# Start
zeekctl deploy

Zeek generates dns.log with fields: ts, uid, id.orig_h, id.resp_h, proto, trans_id, rtt, query, qclass, qtype, rcode, answers, TTLs, rejected. Key fields for tunneling detection: query (full domain name queried), qtype (record type: A=1, AAAA=28, TXT=16, NULL=10, MX=15), answers (response data for exfil via responses), TTLs. Feed dns.log into your SIEM via Filebeat or Logstash. Critical: capture at a network tap or span port, not from a single host's local resolver: you need visibility into all hosts' DNS queries, not just what the recursive resolver serves.

Free daily briefing

Briefings like this, every morning before 9am.

Threat intel, active CVEs, and campaign alerts, distilled for practitioners. 50,000+ subscribers. No noise.

Calculate Shannon Entropy for Subdomain Detection

Shannon entropy measures the randomness of a string. High entropy (close to log2(alphabet_size)) indicates encoded data. Calculate for DNS detection in Python:

import math
from collections import Counter

def entropy(s):
    p, lns = Counter(s), float(len(s))
    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())

# Extract subdomain from FQDN
def get_subdomain(fqdn, domain):
    if fqdn.endswith('.' + domain):
        return fqdn[:-(len(domain) + 1)]
    return fqdn

# Flag high-entropy subdomains
threshold = 3.5  # bits per character
fqdn = 'aGVsbG93b3JsZA.example.com'
sub = get_subdomain(fqdn, 'example.com')
if entropy(sub) > threshold:
    print(f'ALERT: High entropy subdomain: {sub} (entropy: {entropy(sub):.2f})')

Run this against Zeek dns.log in batch or stream. In Splunk, calculate entropy inline:

index=zeek sourcetype=dns
| rex field=query "^(?P<subdomain>[^.]+)"
| eval char_count=len(subdomain), unique_chars=len(mvdedup(split(subdomain, "")))
| eval entropy_approx=log(unique_chars)/log(2)
| where entropy_approx > 3.5 AND char_count > 20
| stats count by query, src_ip

This approximation is fast but less accurate than the full Shannon formula: use the Python calculation for high-fidelity scoring.

Detect Unusual Query Volume and Frequency

Volume-based detection catches high-bandwidth tunnels. KQL for Microsoft Sentinel using Zeek DNS logs:

dns_CL
| where TimeGenerated > ago(1h)
| extend ParentDomain = strcat(split(query_s, ".")[-2], ".", split(query_s, ".")[-1])
| summarize QueryCount=count(), UniqueSubdomains=dcount(query_s), AvgQueryLen=avg(strlen(query_s))
    by SrcIP=id_orig_h_s, ParentDomain, bin(TimeGenerated, 5m)
| where QueryCount > 100 or UniqueSubdomains > 50 or AvgQueryLen > 40
| order by QueryCount desc

For C2 beaconing detection (low and slow), detect periodic query patterns:

dns_CL
| where TimeGenerated > ago(24h)
| extend ParentDomain = strcat(split(query_s, ".")[-2], ".", split(query_s, ".")[-1])
| summarize QueryTimes=make_list(TimeGenerated) by SrcIP=id_orig_h_s, ParentDomain
| where array_length(QueryTimes) between (20 .. 200)  // Consistent beaconing, not a spike
| mvexpand QueryTimes
| extend QueryTime=todatetime(QueryTimes)
| serialize
| extend TimeDiff=datetime_diff('second', QueryTime, prev(QueryTime))
| summarize AvgInterval=avg(TimeDiff), StdDev=stdev(TimeDiff) by SrcIP, ParentDomain
| where AvgInterval between (25 .. 600) and StdDev < 30  // Regular 30-600 second intervals

Low standard deviation of inter-query time is the beaconing signature: legitimate DNS patterns are irregular, C2 beaconing is clock-regular.

Detect Suspicious Record Types and Response Data

Flag unusual DNS record types that indicate exfiltration channels:

index=zeek sourcetype=dns
| where qtype IN ("TXT", "NULL", "MX", "CNAME") AND NOT (query="*.google.com" OR query="*.microsoft.com")
| where NOT match(query, "_dmarc|_domainkey|_spf|_acme-challenge")
| eval answer_len=len(mvjoin(answers, ""))
| where answer_len > 100
| stats count, avg(answer_len) as avg_response_size by query, qtype, id.orig_h
| where count > 5
| sort - avg_response_size

The exclusion for _dmarc, _domainkey, and _spf removes legitimate TXT record queries for email security. _acme-challenge is the ACME DNS validation for Let's Encrypt certificate issuance. Review remaining TXT queries with large response sizes manually: response data longer than 100 characters that isn't from a known email/certificate service is highly suspicious. For NULL record detection specifically: legitimate applications almost never query NULL (type 10) records: any NULL query volume warrants immediate investigation.

Block with Response Policy Zones

Response Policy Zones (RPZ) allow your recursive DNS resolver to override responses for malicious domains. Deploy with BIND9:

# In named.conf, add RPZ zone:
zone 'rpz.internal' {
  type master;
  file '/etc/bind/rpz.internal';
};

# In options block:
response-policy { zone 'rpz.internal'; };
# /etc/bind/rpz.internal zone file:
$TTL 60
@ IN SOA rpz.internal. admin.rpz.internal. 2024010101 3600 900 604800 60
@ IN NS rpz.internal.
# Block known tunnel domains:
bad-tunnel-domain.com IN CNAME .
tunnel-c2.net IN CNAME .

Populate the RPZ zone from threat intelligence feeds: Cisco Umbrella, CISA's DNS sinkhole lists, and commercial feeds from security vendors. Automate zone updates: a cron job that pulls threat feed IOCs and generates BIND zone records, then runs rndc reload rpz.internal to apply without service restart. For Windows DNS (Active Directory environments), Response Policy Zones are supported natively in Windows Server DNS since 2016: configure via Add-DnsServerResponsePolicyZone PowerShell cmdlet.

Implement DNS Security Platform Controls

Commercial DNS security platforms provide turnkey DNS tunneling detection that eliminates the need to build custom analytics. Cisco Umbrella (formerly OpenDNS) operates as a cloud recursive resolver that blocks known malicious domains and applies ML-based tunneling detection before queries reach internal resolvers. Deploy by pointing clients to Umbrella's resolvers (208.67.222.222) and enforcing via DHCP. Infoblox BloxOne Threat Defense integrates with existing DNS infrastructure as an overlay, applying behavioral analytics and threat intelligence to DNS traffic. Palo Alto Networks DNS Security subscription adds DNS tunneling detection to existing NGFW deployments without infrastructure changes. Evaluation criteria: detection rate for Iodine and dnscat2 (test with a lab environment before purchasing), false positive rate on legitimate traffic in your industry (pharmaceutical companies query unusual domains for clinical trial data, financial firms have proprietary resolution patterns), and integration with your SIEM for alert context enrichment.

The bottom line

DNS tunneling detection requires three complementary approaches: entropy analysis (subdomain randomness above 3.5 bits/char indicates encoded data), volume analysis (more than 100 queries per 5 minutes to a single parent domain), and behavioral analysis (regular inter-query intervals under 30-second standard deviation indicate C2 beaconing). Deploy Zeek for passive DNS logging, build SIEM correlation rules for each indicator class, and use RPZ to block confirmed tunnel domains. Commercial DNS security platforms provide higher-fidelity detection for organizations that can't build custom analytics.

Frequently asked questions

How do I detect DNS tunneling without specialized tools?

Detect DNS tunneling using three statistical signals in your existing DNS logs: subdomain entropy above 3.5 bits per character (encoded data is highly random), query volume above 100 queries per 5 minutes to a single parent domain (high-bandwidth tunnels), and unusually long subdomain labels above 50 characters (tunnels maximize payload per query). For C2 beaconing, detect regular inter-query intervals with low standard deviation to the same domain over 24 hours. Most SIEM platforms can compute these metrics from DNS logs collected via Zeek or Windows DNS debug logging.

What DNS record types do attackers use for data exfiltration?

Attackers most commonly use TXT records for exfiltration because they can carry up to 255 bytes per string and are universally permitted through DNS firewalls. NULL records (type 10) carry arbitrary binary data and are rarely queried by legitimate applications, making any NULL query volume immediately suspicious. CNAME records are used for C2 redirection (fast-flux). High-bandwidth tunnels use A and AAAA records for bidirectional data encoding when other types are blocked. Alert on TXT queries to non-email domains with response sizes over 100 characters and any NULL record queries.

What tools do attackers use for DNS tunneling and C2?

Common attacker DNS tunneling tools: DNScat2 establishes a full command shell over DNS using TXT and CNAME records, supporting encrypted channels. Iodine tunnels IPv4 traffic over DNS, enabling full network connectivity through restrictive firewalls that allow DNS. DNSExfiltrator is purpose-built for data exfiltration using DNS queries. For C2 beaconing: Cobalt Strike uses DNS beaconing as an alternative channel (slower than HTTPS but bypasses many proxy filters), and popular C2 frameworks like Sliver also support DNS communication channels. Detection focus: the tools above share common characteristics (high query volume, long subdomains, TXT response size) regardless of the specific tool — detection should be statistical, not signature-based.

How do I collect DNS logs for threat detection in an enterprise environment?

Three DNS log collection approaches: (1) Windows DNS Server: enable DNS debug logging (dnscmd /config /logLevel 0x8100FFFE) which writes all queries to a text log, then collect with your SIEM agent. Microsoft DNS Analytical/Audit event logs (Microsoft-Windows-DNS-Server/Audit in Event Viewer) capture administrative changes. (2) Network-based collection: deploy Zeek at network egress to passively capture all DNS traffic — Zeek's dns.log provides structured per-query records including query name, type, response code, and TTL without any DNS server configuration changes. (3) Recursive resolver logging: if using a centralized resolver (Unbound, BIND, Cisco Umbrella), configure query logging at the resolver level to capture all queries from all clients. Zeek at the network tap is the most comprehensive: it captures DNS over any port, not just port 53.

How do I block DNS tunneling without breaking legitimate DNS traffic?

DNS tunneling blocking without disrupting legitimate traffic: (1) Block known tunneling tool domains at your DNS resolver using RPZ feeds from threat intelligence providers. (2) Rate-limit DNS queries per internal host: configure your recursive resolver to limit each client to 100-200 queries per minute, enough for normal browsing (browser DNS prefetch, app lookups) but too slow for data exfiltration via tunneling. (3) Block DNS queries to domains with high NXDOMAIN rates: tunneling tools generate many failed queries when probing for available subdomains. (4) Block newly registered domains (under 30 days old): DNS tunneling C2 infrastructure typically uses freshly registered domains — block access to these via RPZ without affecting established legitimate domains. None of these blocks break legitimate DNS for normal users.

How do I tune DNS anomaly detection thresholds to minimize false positives in a large enterprise environment?

Start by establishing a per-domain baseline using 30 days of historical DNS logs before applying any thresholds. Calculate the 99th percentile query rate, subdomain label length, and entropy per domain in your environment: this baseline reflects your legitimate traffic patterns, including monitoring tools, CDN health checks, and automation that generate high query volumes. Use baseline-relative thresholds rather than absolute values -- flag a host when its query rate to a given domain exceeds 5x its own 30-day baseline, rather than applying a fixed threshold like 100 queries per 5 minutes that may be normal for some workloads. Suppress known-good high-volume resolvers: DNS forwarders, proxy servers, and load balancers pass through queries for all downstream clients and will appear as high-volume sources -- exclude these by IP from entropy and volume checks and apply the analysis at the upstream query source instead. Create an exception workflow where teams can register high-entropy or high-volume domains used by legitimate internal tooling: DevOps pipelines often query infrastructure domains with generated subdomains (Kubernetes service discovery, HashiCorp Consul) that trigger entropy detection. Review the exception list quarterly and remove entries for tools that have been decommissioned.

Sources & references

  1. SANS Institute: Detecting DNS Tunneling
  2. CISA: DNS Security for Enterprise Networks
  3. Zeek Network Security Monitor Documentation

Free resources

25
Free download

Critical CVE Reference Card 2025–2026

25 actively exploited vulnerabilities with CVSS scores, exploit status, and patch availability. Print it, pin it, share it with your SOC team.

No spam. Unsubscribe anytime.

Free download

Ransomware Incident Response Playbook

Step-by-step 24-hour IR checklist covering detection, containment, eradication, and recovery. Built for SOC teams, IR leads, and CISOs.

No spam. Unsubscribe anytime.

Free newsletter

Get threat intel before your inbox does.

50,000+ security professionals read Decryption Digest for early warnings on zero-days, ransomware, and nation-state campaigns. Free, daily, no spam.

Unsubscribe anytime. We never sell your data.

Eric Bang
Author

Founder & Cybersecurity Evangelist, Decryption Digest

Cybersecurity professional with expertise in threat intelligence, vulnerability research, and enterprise security. Covers zero-days, ransomware, and nation-state operations for 50,000+ security professionals every morning.

Black Hat Giveaway

Win a $2,495 Black Hat pass.

Full-access to Black Hat USA 2026 in Las Vegas. Subscribe free to enter.

Joins Decryption Digest daily briefing. Unsubscribe anytime.

Giveaway: Black Hat USA 2026 Full-Access Pass ($2,495 value)

Details →
Daily Briefing

Subscribe to enter the giveaway

Every subscriber is automatically entered. You also get daily threat intel every morning: zero-days, ransomware, and nation-state campaigns. Free. No spam.

Already subscribed? You're already entered.

Giveaway

Win a $2,495 Black Hat USA 2026 pass.