DNS-Based Threat Hunting

DNS-Based Threat Hunting - article cover image Tools & Defense
Time it takes to read this article 7 minutes.

Disclaimer: This article is provided strictly for educational purposes and authorized security testing. Only run these techniques against systems you own or have explicit written permission to assess. Unauthorized access to computer systems is illegal in virtually every jurisdiction and can carry severe penalties.

Introduction

DNS is one of the highest-yield hunting data sources precisely because it is nearly unavoidable: command-and-control frameworks, exfiltration channels, and phishing infrastructure almost always resolve a domain name at some point, and DNS logging can be centralized at the resolver level independent of which specific endpoint or process made the request. Unlike process telemetry, which requires an agent on every host, resolver-level DNS logs give visibility into every device that uses the corporate resolver, including unmanaged and IoT devices that will never run an EDR agent.

The value is proportional to how much of an intrusion’s lifecycle touches DNS: initial C2 check-in, DNS tunneling as a covert channel when other egress is blocked, domain-generation-algorithm (DGA) malware probing for a live controller, and fast-flux infrastructure hiding a backend behind rotating IPs all leave a DNS footprint even when the payload itself is otherwise well-hidden. The rise of DNS-over-HTTPS complicates this by moving resolution off the visible resolver entirely, which shifts part of the hunt from the network layer to the endpoint.

Attack Prerequisites

Effective DNS hunting depends on having the right logs and context, not just raw query volume:

  • Centralized DNS query logs — resolver query logs (Windows DNS analytical/debug logging, BIND query logs) or endpoint-level DNS telemetry (Sysmon Event ID 22) that ties a query to the requesting process.
  • Enrichment sources — passive DNS history, WHOIS/domain registration age, and threat-intel domain reputation feeds to distinguish a newly registered domain from an established one.
  • A statistical baseline — normal query volume, top destinations, and record-type distribution per host/segment, so anomalies are recognizable against something concrete.
  • Basic text-analysis tooling — the ability to compute label length, Shannon entropy, and n-gram “wordiness” of subdomains at scale (a notebook or a few lines of Python/KQL is sufficient).
  • Visibility into DoH/DoT usage — proxy or TLS SNI logging that can spot endpoints resolving via a DNS-over-HTTPS provider instead of the managed resolver, since that traffic bypasses resolver-level logging entirely.

How It Works

DNS tunneling encodes arbitrary data into DNS queries and responses — typically TXT or NULL record types, or long, high-entropy subdomain labels approaching the 63-character label limit — to smuggle a command-and-control or exfiltration channel through DNS when other egress is firewalled. Tools like dnscat2 and iodine are the common public implementations. The telltale signs are unusually high query volume to a single domain, non-standard record types relative to normal traffic, and subdomain labels that look nothing like real hostnames.

Domain generation algorithms (DGAs) let malware compute a large set of candidate C2 domains algorithmically (often date-seeded) instead of hardcoding one, so that registering or sinkholing a handful of domains doesn’t disable the malware — the operator only needs to register the specific domain the algorithm will compute on a given day. This produces a very recognizable pattern: a host issuing large numbers of queries that resolve to NXDOMAIN, occasionally punctuated by one that succeeds. Conficker (2008) remains the canonical, well-documented example of DGA malware at scale. Statistically, DGA-generated names tend to have improbable consonant/vowel ratios and n-gram frequencies compared to real dictionary-based hostnames, which is what entropy- and language-model-based DGA classifiers key on.

Fast-flux and beaconing are visible in DNS response patterns rather than the query itself: fast-flux infrastructure returns many different A records with very low TTLs for the same domain, rotating rapidly to resist IP-based blocking, while beaconing C2 produces queries to the same domain at a regular interval (often with deliberate jitter to evade naive periodicity detection). DNS-over-HTTPS (DoH) used by malware to evade resolver-level visibility shows up not in DNS logs at all but as direct TLS 443 connections with an SNI matching a known public DoH provider — which means DoH abuse detection has to move to the endpoint or the TLS layer rather than the DNS log.

Practical Example / Configuration

KQL hunting for DNS tunneling / DGA indicators, combining subdomain length, NXDOMAIN ratio, and query volume per host (schema similar to Microsoft Defender’s DeviceEvents / Sysmon DNS-query table):

let LookbackWindow = 1d;
DeviceEvents
| where ActionType == "DnsQuery" and Timestamp > ago(LookbackWindow)
| extend QueryName = tostring(AdditionalFields.QueryName)
| extend Label = tostring(split(QueryName, ".")[0])
| extend LabelLen = strlen(Label)
| extend ResponseCode = tostring(AdditionalFields.QueryStatus)
| summarize
    TotalQueries = count(),
    NxDomainCount = countif(ResponseCode == "NXDOMAIN"),
    DistinctLongLabels = dcountif(Label, LabelLen > 40),
    AvgLabelLen = avg(LabelLen)
    by DeviceId, InitiatingProcessFileName, bin(Timestamp, 1h)
| extend NxRatio = round(1.0 * NxDomainCount / TotalQueries, 2)
| where (NxRatio > 0.5 and TotalQueries > 50) or DistinctLongLabels > 20
| order by TotalQueries desc
KUSTO

A complementary Sigma-style detection for the network layer, flagging TXT-record-heavy tunneling patterns from Zeek’s dns.log:

title: Possible DNS Tunneling via High-Volume TXT Queries
id: 3c7e2b90-1a44-4f0e-9b2a-7e5f6c8d9a10
status: test
logsource:
    category: dns
    product: zeek
detection:
    selection:
        qtype_name: 'TXT'
    timeframe: 5m
    condition: selection | count(query) by id.orig_h > 100
falsepositives:
    - Legitimate SPF/DKIM bulk lookups from mail infrastructure
level: medium
tags:
    - attack.command_and_control
    - attack.t1071.004
YAML

Walkthrough / Exploitation

Running a DNS hunt from raw logs to actionable findings:

1. Establish per-host baselines: top talkers, average query volume/hour,
   and normal record-type mix over a representative period.
2. Run entropy/label-length scoring across the current window; sort
   descending and manually review the top 20-30 outliers rather than
   alerting on every statistical anomaly (CDNs and cloud services
   legitimately use long, random-looking subdomains).
3. Cross-reference surviving candidates against passive DNS / domain-age
   feeds: a domain registered in the last 7-30 days is materially higher
   risk than one that has existed for years.
4. Pivot to the process: Sysmon Event 22 carries Image/ProcessGuid, so a
   suspicious query can be tied directly to the issuing binary and its
   parent process.
5. Compute NXDOMAIN ratio per host over the window; a host with a high
   ratio and low overall success rate is consistent with DGA malware
   probing for a live controller.
6. Separately hunt for DoH usage: flag TLS connections on 443 with SNI
   matching known public DoH endpoints from processes other than approved
   browsers, since that traffic never appears in resolver logs at all.
7. Document and, for any confirmed pattern, convert the query into a
   standing Sigma rule and add the technique to the ATT&CK coverage map
   under T1071.004 (DNS) and T1568 (Dynamic Resolution) as applicable.
TEXT

Note: Entropy-based scoring alone produces significant false positives from legitimate infrastructure — CDN edge nodes, cloud storage buckets, and some SaaS session identifiers all use long, high-entropy subdomains routinely. Always pair entropy with a second signal (volume, NXDOMAIN ratio, domain age) before treating a hit as suspicious.

Opsec: Encrypted DNS (DoH/DoT) genuinely reduces resolver-side visibility, not just for attackers — legitimate browser defaults increasingly resolve via DoH too. Decide deliberately whether to block non-approved DoH resolvers at the network edge or accept the visibility loss and shift detection to the endpoint.

Detection and Defense

Concrete controls that make DNS hunting durable rather than a one-off exercise:

  • Centralize DNS logging fleet-wide (Windows DNS analytical logs, resolver query logs, or Sysmon Event 22 rollout) rather than relying on sampling.
  • Control DoH — block or restrict DNS-over-HTTPS to approved resolvers via TLS SNI/IP allow-listing so encrypted DNS doesn’t become a blind spot by default.
  • RPZ sinkholing — use Response Policy Zones to sinkhole known DGA/C2 domains fed from threat-intel, converting a static blocklist into an active detection trigger when something tries to resolve one.
  • Alert on NXDOMAIN rate anomalies per host as a standing detection, not just a periodic hunt, since it is one of the cheapest, highest-signal DGA indicators available.
  • Deploy passive network DNS analytics (Zeek dns.log, Suricata) for record-type and TTL-anomaly detection independent of host-based logging gaps.

Real-World Impact

Conficker’s DGA-based C2 remains one of the most widely documented real-world examples of domain-generation malware driving large-scale sinkholing and takedown efforts in the security community. DNS tunneling tools such as dnscat2 and iodine are commonly used both in authorized red-team engagements to test egress controls and, historically, in real intrusions to move data through networks that otherwise restrict outbound traffic. DNS-based command-and-control and data staging has also been noted publicly in analyses of the SolarWinds/SUNBURST supply-chain compromise, where DNS requests were used as part of victim identification and staged communication before further activity.

Conclusion

DNS’s near-universality makes it one of the most cost-effective hunting data sources available, but raw volume and entropy scoring alone produce too many false positives to act on directly — durable DNS hunting combines statistical outliers with domain-age enrichment and process-level correlation, and treats the growing use of encrypted DNS as a deliberate architectural decision about where visibility should live rather than an afterthought discovered during an incident.

You Might Also Like

If you found this useful, these related deep-dives cover adjacent techniques and their defenses:

Comments

Copied title and URL