Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-SkillsFramework mappings
MITRE ATT&CK
T1046 on the official MITRE ATT&CK siteT1048 on the official MITRE ATT&CK siteT1048.003 on the official MITRE ATT&CK siteT1057 on the official MITRE ATT&CK siteT1071.004 on the official MITRE ATT&CK siteT1082 on the official MITRE ATT&CK siteT1083 on the official MITRE ATT&CK siteT1132.001 on the official MITRE ATT&CK siteT1568.002 on the official MITRE ATT&CK siteT1572 on the official MITRE ATT&CK site
NIST CSF 2.0
MITRE D3FEND
When to Use
- When hunting for data exfiltration over DNS covert channels
- After threat intelligence indicates DNS-based C2 frameworks targeting your industry
- When dns.log shows unusually high query volumes to specific domains
- During investigation of suspected data theft where no HTTP/S exfiltration is found
- When monitoring for tools like iodine, dnscat2, DNSExfiltrator, or DNS-over-HTTPS tunneling
Prerequisites
- Zeek deployed on network tap or SPAN port capturing DNS traffic
- Zeek dns.log with full query and response fields
- SIEM platform for dns.log analysis (Splunk, Elastic)
- RITA (Real Intelligence Threat Analytics) for automated DNS analysis
- Passive DNS data for historical domain resolution context
Workflow
- Analyze Query Length Distribution: DNS tunneling encodes data in subdomain labels, producing queries significantly longer than normal. Normal DNS queries average 20-30 characters; tunneling queries often exceed 50+ characters. Calculate mean and standard deviation of query lengths per domain.
- Calculate Subdomain Entropy: Tunneling encodes data using Base32/Base64, producing high-entropy subdomain strings. Calculate Shannon entropy of subdomain labels -- values above 3.5 bits/character strongly suggest encoded data.
- Count Unique Subdomains Per Domain: Legitimate domains have relatively few unique subdomains. DNS tunneling generates hundreds or thousands of unique subdomains under a single parent domain.
- Monitor DNS Record Type Distribution: TXT, NULL, CNAME, and MX records can carry more data than A records. Excessive TXT queries to a single domain indicate data transfer via DNS.
- Detect High Query Volume: Flag domains receiving more than 100 queries per hour from a single source, especially when combined with high subdomain uniqueness.
- Analyze Query Timing: DNS tunneling tools produce regular query patterns (beaconing) or burst patterns (data transfer). Apply frequency analysis to DNS query timestamps.
- Cross-Reference with conn.log: Correlate DNS queries with connection metadata to identify the process or endpoint generating suspicious queries.
- Validate with Domain Intelligence: Check suspicious domains against WHOIS data, certificate transparency, and threat intelligence feeds.
Key Concepts
| Concept | Description |
|---|---|
| T1071.004 | Application Layer Protocol: DNS |
| T1048.003 | Exfiltration Over Alternative Protocol: DNS |
| T1572 | Protocol Tunneling |
| Shannon Entropy | Measure of randomness in subdomain strings |
| Zeek dns.log | DNS query/response metadata |
| RITA | Automated DNS tunneling detection from Zeek logs |
| iodine | IPv4-over-DNS tunneling tool |
| dnscat2 | DNS-based command-and-control tool |
| DNSExfiltrator | Data exfiltration tool using DNS requests |
Detection Queries
Zeek Script -- DNS Tunnel Detection
@load base/protocols/dns
module DNSTunnel;
export {
redef enum Notice::Type += { DNSTunnel::Long_DNS_Query };
const query_length_threshold = 50 &redef;
const query_count_threshold = 100 &redef;
}
event dns_request(c: connection, msg: dns_msg, query: string, qtype: count, qclass: count) {
if ( |query| > query_length_threshold ) {
NOTICE([$note=DNSTunnel::Long_DNS_Query,
$msg=fmt("Long DNS query detected: %s (%d chars)", query, |query|),
$conn=c]);
}
}Splunk -- DNS Tunneling Indicators from Zeek
index=zeek sourcetype=bro_dns
| rex field=query "(?<subdomain>[^.]+)\.(?<basedomain>[^.]+\.[^.]+)$"
| stats count dc(subdomain) as unique_subs avg(len(query)) as avg_len max(len(query)) as max_len by src basedomain
| where count > 100 AND (unique_subs > 50 OR avg_len > 40)
| sort -unique_subsSplunk -- High Entropy Subdomain Detection
index=zeek sourcetype=bro_dns
| rex field=query "^(?<subdomain>[^.]+)"
| where len(subdomain) > 20
| eval char_count=len(subdomain)
| stats count dc(query) as unique_queries avg(char_count) as avg_sub_len by src query_type_name basedomain
| where unique_queries > 30 AND avg_sub_len > 25
| sort -unique_queriesRITA Analysis
rita import /path/to/zeek/logs dataset_name
rita show-dns-fqdn-ips-long dataset_name
rita show-exploded-dns dataset_name
rita show-dns-tunneling dataset_name --csv > dns_tunnel_results.csvCommon Scenarios
- dnscat2 C2: Encodes command-and-control traffic in DNS CNAME/TXT queries with Base64-encoded subdomain labels. Produces high query volumes with long, high-entropy subdomains.
- iodine IPv4 Tunnel: Creates a virtual network interface tunneling all IP traffic through DNS. Generates massive DNS query volumes with NULL record types.
- Data Exfiltration via DNS: Sensitive data encoded in subdomain labels (e.g.,
aGVsbG8gd29ybGQ.exfil.attacker.com), sent as A or TXT queries. Each query carries ~63 bytes of data. - DNS-over-HTTPS Tunneling: Bypasses traditional DNS monitoring by sending DNS queries over HTTPS to public resolvers (8.8.8.8, 1.1.1.1), requiring TLS inspection for detection.
- Cobalt Strike DNS Beacon: Uses DNS A/TXT records for C2 communication with configurable subdomain encoding schemes.
Output Format
Hunt ID: TH-DNSTUNNEL-[DATE]-[SEQ]
Source IP: [Internal IP]
Source Host: [Hostname]
Target Domain: [Base domain]
Query Count: [Total queries in window]
Unique Subdomains: [Count]
Avg Query Length: [Characters]
Max Query Length: [Characters]
Subdomain Entropy: [Bits per character]
Primary Record Type: [A/TXT/CNAME/NULL]
Data Volume Estimate: [Bytes exfiltrated]
Risk Level: [Critical/High/Medium/Low]Source materials
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.5 KB
API Reference: DNS Tunneling Detection with Zeek
Detection Heuristics
| Indicator | Threshold | Score |
|---|---|---|
| Shannon entropy | > 3.5 | +40 |
| Avg subdomain length | > 30 chars | +30 |
| Tunnel query type ratio | > 50% TXT/NULL/CNAME | +20 |
| High query volume | > 500 queries | +10 |
Zeek dns.log Fields
| Index | Field | Description |
|---|---|---|
| 0 | ts |
Timestamp |
| 2 | id.orig_h |
Source IP |
| 4 | id.resp_h |
DNS server |
| 9 | query |
Query name |
| 13 | qtype_name |
Query type (A, TXT, etc.) |
| 21 | answers |
Response answers |
DNS Tunneling Tools (for detection reference)
| Tool | Encoding | Query Type |
|---|---|---|
| iodine | Base128 | NULL, TXT |
| dnscat2 | Hex/Base64 | CNAME, TXT, MX |
| dns2tcp | Base64 | TXT |
| Cobalt Strike | Hex | A, AAAA, TXT |
Shannon Entropy Reference
| Data Type | Entropy |
|---|---|
| Normal hostnames | 2.0 - 3.0 |
| Base32 encoded | 3.5 - 4.0 |
| Base64 encoded | 4.0 - 5.0 |
| Hex encoded | 3.5 - 4.0 |
Python Libraries
| Library | Use |
|---|---|
math |
Entropy calculation |
csv |
TSV log parsing |
collections.defaultdict |
Domain aggregation |
dpkt |
PCAP DNS parsing |
dnslib |
DNS packet construction |
Zeek Scripts for DNS Analysis
@load base/protocols/dns
redef DNS::max_pending_queries = 1000;
event dns_request(c: connection, msg: dns_msg, query: string, qtype: count) {
if (|query| > 50) print fmt("Long query: %s", query);
}standards.md2.2 KB
Standards and References - DNS Tunneling Detection
MITRE ATT&CK References
| Technique | Name | Description |
|---|---|---|
| T1071.004 | Application Layer Protocol: DNS | DNS-based C2 communication |
| T1048.003 | Exfiltration Over Unencrypted Non-C2 Protocol | Data theft via DNS |
| T1572 | Protocol Tunneling | IP-over-DNS tunneling |
| T1568.002 | Domain Generation Algorithms | Algorithmically generated domains |
| T1132.001 | Data Encoding: Standard Encoding | Base32/64 in DNS queries |
DNS Tunneling Detection Thresholds
| Indicator | Threshold | Rationale |
|---|---|---|
| Query length | > 50 characters | Normal queries average 20-30 chars |
| Subdomain label length | > 30 characters | Max label is 63; tunneling uses near-max |
| Subdomain entropy | > 3.5 bits/char | Base32/64 encoding produces high entropy |
| Unique subdomains per domain | > 100/hour | Legitimate domains have few unique subs |
| Query volume to single domain | > 100/hour | Sustained high volume indicates tunneling |
| TXT record query ratio | > 50% to domain | TXT queries carry more data |
| NULL record queries | Any volume | Rarely used legitimately |
DNS Tunneling Tools
| Tool | Protocol | Record Types | Data Rate | Detection Difficulty |
|---|---|---|---|---|
| iodine | IP-over-DNS | NULL, TXT, CNAME, A | ~100 Kbps | Medium |
| dnscat2 | C2 over DNS | TXT, CNAME, MX | ~10 Kbps | Medium |
| DNSExfiltrator | Exfil over DNS | TXT, A | ~5 Kbps | Medium-Hard |
| Cobalt Strike DNS | C2 | A, TXT | Variable | Hard |
| dns2tcp | TCP-over-DNS | TXT, KEY | ~50 Kbps | Medium |
| Heyoka | DNS exfiltration | All types | Variable | Hard |
Zeek Log Fields for DNS Analysis
| Field | Description | Tunnel Relevance |
|---|---|---|
| query | Full DNS query name | Length and entropy analysis |
| qtype_name | Query record type | TXT/NULL/CNAME anomalies |
| answers | Response content | Response size analysis |
| rcode_name | Response code | NXDOMAIN patterns |
| id.orig_h | Source IP | Source identification |
| AA | Authoritative answer | Non-authoritative responses |
| rejected | Query rejected | Filtering effectiveness |
workflows.md2.4 KB
Detailed Hunting Workflow - DNS Tunneling with Zeek
Phase 1: Query Length and Volume Analysis
Step 1.1 - Identify Domains with Long Queries
index=zeek sourcetype=bro_dns
| eval query_len=len(query)
| where query_len > 50
| rex field=query "\.(?<basedomain>[^.]+\.[^.]+)$"
| stats count avg(query_len) as avg_len max(query_len) as max_len dc(query) as unique_queries by id.orig_h basedomain
| where count > 50
| sort -avg_lenStep 1.2 - High Volume DNS to Single Domain
index=zeek sourcetype=bro_dns
| rex field=query "\.(?<basedomain>[^.]+\.[^.]+)$"
| bin _time span=1h
| stats count by id.orig_h basedomain _time
| where count > 100
| sort -countPhase 2: Entropy Analysis
Step 2.1 - Shannon Entropy Calculation
import math
from collections import Counter
def shannon_entropy(text):
if not text:
return 0.0
counts = Counter(text)
length = len(text)
return -sum((c/length) * math.log2(c/length) for c in counts.values())
# Flag subdomains with entropy > 3.5Step 2.2 - Splunk Entropy Approximation
index=zeek sourcetype=bro_dns
| rex field=query "^(?<subdomain>[^.]+)"
| where len(subdomain) > 20
| eval has_numbers=if(match(subdomain, "[0-9]"), 1, 0)
| eval has_mixed_case=if(match(subdomain, "[A-Z]") AND match(subdomain, "[a-z]"), 1, 0)
| stats count avg(len(subdomain)) as avg_sub_len sum(has_numbers) as numeric_count by id.orig_h basedomain
| eval numeric_ratio=numeric_count/count
| where avg_sub_len > 25 AND numeric_ratio > 0.3Phase 3: Record Type Analysis
Step 3.1 - Unusual Record Types
index=zeek sourcetype=bro_dns
| where qtype_name IN ("TXT", "NULL", "CNAME", "MX", "KEY", "SRV")
| rex field=query "\.(?<basedomain>[^.]+\.[^.]+)$"
| stats count dc(query) as unique by id.orig_h basedomain qtype_name
| where count > 50
| sort -countPhase 4: RITA Automated Analysis
# Full Zeek log import and DNS analysis
rita import /opt/zeek/logs/current dns_hunt
rita show-dns-tunneling dns_hunt
rita show-exploded-dns dns_hunt | sort -k2 -n -r | head -20Phase 5: Correlation and Response
Step 5.1 - Map DNS Source to Endpoint
Correlate dns.log source IPs with DHCP logs or endpoint inventory to identify affected hosts and processes.
Step 5.2 - Response Actions
- DNS sinkhole the identified tunneling domain
- Block at DNS resolver and firewall
- Isolate source endpoint
- Capture memory and disk forensics
- Assess scope of data exfiltration
Scripts 2
agent.py5.5 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for detecting DNS tunneling using Zeek log analysis."""
import argparse
import json
import math
import sys
from collections import defaultdict
from datetime import datetime, timezone
ENTROPY_THRESHOLD = 3.5
MIN_QUERIES_PER_DOMAIN = 20
MAX_NORMAL_SUBDOMAIN_LEN = 30
TUNNEL_QUERY_TYPES = {"TXT", "NULL", "CNAME", "MX"}
def shannon_entropy(data):
"""Calculate Shannon entropy of a string."""
if not data:
return 0.0
freq = defaultdict(int)
for c in data:
freq[c] += 1
n = len(data)
return -sum((cnt/n) * math.log2(cnt/n) for cnt in freq.values())
def load_dns_log(filepath):
"""Load Zeek dns.log (TSV format)."""
entries = []
try:
with open(filepath, "r") as f:
for line in f:
if line.startswith("#"):
continue
parts = line.strip().split("\t")
if len(parts) >= 10:
entries.append({
"ts": parts[0],
"uid": parts[1],
"src": parts[2],
"src_port": parts[3],
"dst": parts[4],
"dst_port": parts[5],
"query": parts[9] if len(parts) > 9 else "",
"qtype": parts[13] if len(parts) > 13 else "",
"answers": parts[21] if len(parts) > 21 else "",
})
except (OSError, IndexError) as e:
print(f"[!] Error loading DNS log: {e}")
return entries
def analyze_domain_statistics(entries):
"""Compute per-domain statistics for tunneling detection."""
domain_data = defaultdict(lambda: {
"queries": [], "subdomains": [], "qtypes": defaultdict(int),
"sources": set(), "total_subdomain_len": 0,
})
for entry in entries:
query = entry.get("query", "")
if not query or query == "-":
continue
parts = query.rstrip(".").split(".")
if len(parts) < 2:
continue
domain = ".".join(parts[-2:])
subdomain = ".".join(parts[:-2])
d = domain_data[domain]
d["queries"].append(query)
d["subdomains"].append(subdomain)
d["qtypes"][entry.get("qtype", "")] += 1
d["sources"].add(entry.get("src", ""))
d["total_subdomain_len"] += len(subdomain)
return domain_data
def detect_tunneling(domain_data):
"""Apply tunneling detection heuristics."""
findings = []
for domain, data in domain_data.items():
query_count = len(data["queries"])
if query_count < MIN_QUERIES_PER_DOMAIN:
continue
avg_subdomain_len = data["total_subdomain_len"] / query_count
all_subdomain_text = "".join(data["subdomains"])
entropy = shannon_entropy(all_subdomain_text)
tunnel_qtype_count = sum(
data["qtypes"].get(qt, 0) for qt in TUNNEL_QUERY_TYPES
)
tunnel_qtype_ratio = tunnel_qtype_count / query_count if query_count else 0
score = 0
if entropy > ENTROPY_THRESHOLD:
score += 40
if avg_subdomain_len > MAX_NORMAL_SUBDOMAIN_LEN:
score += 30
if tunnel_qtype_ratio > 0.5:
score += 20
if query_count > 500:
score += 10
if score >= 40:
findings.append({
"domain": domain,
"query_count": query_count,
"avg_subdomain_length": round(avg_subdomain_len, 1),
"entropy": round(entropy, 3),
"tunnel_qtype_ratio": round(tunnel_qtype_ratio, 3),
"unique_sources": len(data["sources"]),
"tunnel_score": score,
"severity": "CRITICAL" if score >= 70 else "HIGH" if score >= 50 else "MEDIUM",
})
findings.sort(key=lambda f: f["tunnel_score"], reverse=True)
return findings
def main():
parser = argparse.ArgumentParser(
description="DNS tunneling detection agent using Zeek logs"
)
parser.add_argument("dns_log", help="Path to Zeek dns.log")
parser.add_argument("--min-queries", type=int, default=20)
parser.add_argument("--entropy-threshold", type=float, default=3.5)
parser.add_argument("--output", "-o", help="Output JSON report")
parser.add_argument("--verbose", "-v", action="store_true")
args = parser.parse_args()
global MIN_QUERIES_PER_DOMAIN, ENTROPY_THRESHOLD
MIN_QUERIES_PER_DOMAIN = args.min_queries
ENTROPY_THRESHOLD = args.entropy_threshold
print("[*] DNS Tunneling Detection Agent (Zeek)")
entries = load_dns_log(args.dns_log)
if not entries:
print("[!] No DNS entries loaded")
sys.exit(1)
print(f"[*] Loaded {len(entries)} DNS queries")
report = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"source_file": args.dns_log,
"total_queries": len(entries),
"findings": [],
}
domain_data = analyze_domain_statistics(entries)
findings = detect_tunneling(domain_data)
report["findings"] = findings
report["risk_level"] = (
"CRITICAL" if any(f["severity"] == "CRITICAL" for f in findings)
else "HIGH" if findings else "LOW"
)
print(f"[*] Detected {len(findings)} suspected DNS tunnels")
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
process.py5.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
DNS Tunneling Detection Script for Zeek Logs
Analyzes dns.log for tunneling indicators: query length, entropy,
unique subdomains, record types, and query volume.
"""
import json
import csv
import argparse
import datetime
import math
from collections import defaultdict, Counter
from pathlib import Path
ENTROPY_THRESHOLD = 3.5
QUERY_LENGTH_THRESHOLD = 50
SUBDOMAIN_LENGTH_THRESHOLD = 25
UNIQUE_SUBDOMAIN_THRESHOLD = 50
QUERY_COUNT_THRESHOLD = 100
SUSPICIOUS_RECORD_TYPES = {"TXT", "NULL", "CNAME", "MX", "KEY", "SRV"}
def calculate_entropy(text: str) -> float:
if not text:
return 0.0
counts = Counter(text)
length = len(text)
return -sum((c / length) * math.log2(c / length) for c in counts.values())
def parse_zeek_dns(input_path: str) -> list[dict]:
path = Path(input_path)
events = []
if path.suffix == ".json":
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
events = data if isinstance(data, list) else data.get("events", [])
elif path.suffix == ".csv":
with open(path, "r", encoding="utf-8-sig") as f:
events = [dict(row) for row in csv.DictReader(f)]
elif path.suffix == ".log":
with open(path, "r", encoding="utf-8") as f:
headers = None
for line in f:
if line.startswith("#fields"):
headers = line.strip().split("\t")[1:]
elif line.startswith("#"):
continue
elif headers:
values = line.strip().split("\t")
if len(values) == len(headers):
events.append(dict(zip(headers, values)))
return events
def detect_dns_tunneling(queries: list[dict]) -> list[dict]:
domain_stats = defaultdict(lambda: {
"queries": 0, "unique_subdomains": set(), "total_length": 0,
"max_length": 0, "record_types": Counter(), "sources": set(),
"subdomain_entropy_samples": [],
})
for q in queries:
query = q.get("query", "")
src = q.get("id.orig_h", q.get("src_ip", q.get("source_ip", "")))
qtype = q.get("qtype_name", q.get("query_type", "A"))
if not query or len(query.split(".")) < 3:
continue
parts = query.rstrip(".").split(".")
base_domain = ".".join(parts[-2:])
subdomain = ".".join(parts[:-2])
stats = domain_stats[(src, base_domain)]
stats["queries"] += 1
stats["unique_subdomains"].add(subdomain)
stats["total_length"] += len(query)
stats["max_length"] = max(stats["max_length"], len(query))
stats["record_types"][qtype] += 1
stats["sources"].add(src)
if len(stats["subdomain_entropy_samples"]) < 100:
stats["subdomain_entropy_samples"].append(subdomain)
findings = []
for (src, base_domain), stats in domain_stats.items():
if stats["queries"] < 20:
continue
avg_len = stats["total_length"] / stats["queries"]
unique_subs = len(stats["unique_subdomains"])
avg_entropy = 0.0
if stats["subdomain_entropy_samples"]:
entropies = [calculate_entropy(s) for s in stats["subdomain_entropy_samples"]]
avg_entropy = sum(entropies) / len(entropies)
risk = 0
indicators = []
if avg_len > QUERY_LENGTH_THRESHOLD:
risk += 25
indicators.append(f"High avg query length: {avg_len:.1f}")
if unique_subs > UNIQUE_SUBDOMAIN_THRESHOLD:
risk += 25
indicators.append(f"High unique subdomains: {unique_subs}")
if avg_entropy > ENTROPY_THRESHOLD:
risk += 25
indicators.append(f"High subdomain entropy: {avg_entropy:.2f}")
if stats["queries"] > QUERY_COUNT_THRESHOLD:
risk += 10
indicators.append(f"High query volume: {stats['queries']}")
suspicious_types = sum(stats["record_types"].get(rt, 0) for rt in SUSPICIOUS_RECORD_TYPES)
if suspicious_types > stats["queries"] * 0.5:
risk += 15
indicators.append(f"Unusual record types: {dict(stats['record_types'])}")
if risk < 30:
continue
risk_level = "CRITICAL" if risk >= 70 else "HIGH" if risk >= 50 else "MEDIUM"
findings.append({
"source_ip": src,
"base_domain": base_domain,
"query_count": stats["queries"],
"unique_subdomains": unique_subs,
"avg_query_length": round(avg_len, 1),
"max_query_length": stats["max_length"],
"avg_subdomain_entropy": round(avg_entropy, 3),
"record_types": dict(stats["record_types"]),
"risk_score": risk,
"risk_level": risk_level,
"indicators": indicators,
})
return sorted(findings, key=lambda x: x["risk_score"], reverse=True)
def run_hunt(input_path: str, output_dir: str) -> None:
print(f"[*] DNS Tunneling Hunt - {datetime.datetime.now().isoformat()}")
queries = parse_zeek_dns(input_path)
print(f"[*] Loaded {len(queries)} DNS queries")
findings = detect_dns_tunneling(queries)
print(f"[!] DNS tunneling detections: {len(findings)}")
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
with open(output_path / "dns_tunnel_findings.json", "w", encoding="utf-8") as f:
json.dump({"hunt_id": f"TH-DNSTUNNEL-{datetime.date.today().isoformat()}",
"total_queries": len(queries), "findings": findings}, f, indent=2)
print(f"[+] Results written to {output_dir}")
def main():
parser = argparse.ArgumentParser(description="DNS Tunneling Detection")
parser.add_argument("--input", "-i", required=True)
parser.add_argument("--output", "-o", default="./dns_tunnel_hunt_output")
args = parser.parse_args()
run_hunt(args.input, args.output)
if __name__ == "__main__":
main()
Assets 1
template.mdtext/markdown · 1.0 KBKeep exploring