Detecting Command and Control Over DNS
When to Use
- Investigating suspected DNS tunneling used for C2 communication or data exfiltration
- Analyzing DNS query logs for signs of encoded payloads in subdomain strings
- Classifying domains as DGA-generated vs. legitimate using statistical or ML methods
- Detecting DNS beaconing patterns (regular intervals, consistent query sizes)
- Hunting for Iodine, dnscat2, dns2tcp, Cobalt Strike DNS, or Sliver DNS traffic
- Monitoring TXT record abuse for command delivery or staged payload download
- Building DNS anomaly detection rules for SOC/SIEM deployment
Do not use for general DNS performance monitoring or DNS configuration auditing; use DNS health monitoring tools for those. For HTTP/HTTPS-based C2 detection, use network traffic analysis skills focused on web protocols.
DISCLAIMER: DNS tunneling tools referenced in this skill (Iodine, dnscat2, dns2tcp) are dual-use. They have legitimate uses (bypassing captive portals, security research) and malicious uses (C2 channels, exfiltration). Only deploy detection in networks you are authorized to monitor. Testing tunneling tools requires explicit authorization.
Prerequisites
- DNS query logs from recursive resolver, Zeek/Bro, Suricata, or passive DNS tap
- Python 3.9+ with
numpy, scikit-learn, pandas, tldextract, and dnspython
- Zeek (formerly Bro) with dns.log output or Suricata with DNS EVE JSON logging
- SIEM access (Splunk, Elastic, Microsoft Sentinel) for log correlation
- Passive DNS database access (CIRCL pDNS, Farsight DNSDB, or internal) for enrichment
- Wireshark/tshark for packet-level DNS inspection
- Known-good domain whitelist (Alexa/Tranco top 1M or Majestic Million)
Workflow
Step 1: Collect and Parse DNS Query Logs
Ingest DNS traffic from network sensors and parse into analyzable format:
# Zeek - extract dns.log fields
# Default Zeek dns.log columns:
# ts uid id.orig_h id.orig_p id.resp_h id.resp_p proto trans_id rtt query
# qclass qclass_name qtype qtype_name rcode rcode_name AA TC RD RA Z
# answers TTLs rejected
# Filter for potentially suspicious record types
cat dns.log | zeek-cut ts id.orig_h query qtype_name answers rcode_name | \
grep -E "TXT|NULL|CNAME|MX" > suspicious_qtypes.log
# Extract unique queried domains
cat dns.log | zeek-cut query | sort -u > unique_domains.txt
# Suricata EVE JSON - extract DNS events
cat eve.json | jq -r 'select(.event_type=="dns") |
[.timestamp, .src_ip, .dns.rrname, .dns.rrtype, .dns.rcode] |
@tsv' > dns_events.tsv
# tshark - extract DNS queries from pcap
tshark -r capture.pcap -T fields \
-e frame.time -e ip.src -e ip.dst \
-e dns.qry.name -e dns.qry.type \
-e dns.resp.type -e dns.txt \
-Y "dns" > dns_queries.tsv
# Count queries per domain (find high-volume destinations)
cat dns.log | zeek-cut query | \
awk -F. '{print $(NF-1)"."$NF}' | \
sort | uniq -c | sort -rn | head -50
Step 2: Shannon Entropy Analysis of DNS Queries
Calculate entropy of subdomain strings to identify encoded/encrypted data:
#!/usr/bin/env python3
"""Shannon entropy analysis for DNS query subdomains."""
import math
import csv
import sys
from collections import Counter
try:
import tldextract
HAS_TLDEXTRACT = True
except ImportError:
HAS_TLDEXTRACT = False
def shannon_entropy(data):
"""Calculate Shannon entropy of a string (bits per character)."""
if not data:
return 0.0
counter = Counter(data)
length = len(data)
entropy = -sum(
(count / length) * math.log2(count / length)
for count in counter.values()
)
return entropy
def extract_subdomain(fqdn):
"""Extract the subdomain portion from a fully qualified domain name."""
if HAS_TLDEXTRACT:
ext = tldextract.extract(fqdn)
if ext.subdomain:
return ext.subdomain, f"{ext.domain}.{ext.suffix}"
return "", f"{ext.domain}.{ext.suffix}"
else:
# Fallback: assume last two labels are domain + TLD
parts = fqdn.rstrip(".").split(".")
if len(parts) > 2:
return ".".join(parts[:-2]), ".".join(parts[-2:])
return "", fqdn
def analyze_dns_entropy(queries, entropy_threshold=3.5, length_threshold=30):
"""
Analyze DNS queries for tunneling indicators using entropy.
Thresholds (tunable per environment):
- entropy_threshold: Shannon entropy above this flags as suspicious (3.5-4.0 typical)
- length_threshold: Subdomain length above this flags as suspicious (30-50 chars)
Returns list of flagged queries with scores.
"""
results = []
for query_record in queries:
fqdn = query_record.get("query", "").lower().rstrip(".")
if not fqdn:
continue
subdomain, base_domain = extract_subdomain(fqdn)
if not subdomain:
continue
# Remove dots from subdomain for entropy calculation
subdomain_flat = subdomain.replace(".", "")
if not subdomain_flat:
continue
entropy = shannon_entropy(subdomain_flat)
length = len(subdomain_flat)
label_count = subdomain.count(".") + 1
# Scoring: higher = more suspicious
score = 0.0
flags = []
if entropy > entropy_threshold:
score += (entropy - entropy_threshold) * 25
flags.append(f"high_entropy:{entropy:.2f}")
if length > length_threshold:
score += (length - length_threshold) * 0.5
flags.append(f"long_subdomain:{length}")
if label_count > 4:
score += label_count * 2
flags.append(f"many_labels:{label_count}")
# Check for hex/base32/base64 encoding patterns
hex_ratio = sum(1 for c in subdomain_flat if c in "0123456789abcdef") / max(len(subdomain_flat), 1)
if hex_ratio > 0.85 and length > 20:
score += 20
flags.append("hex_encoded")
b32_chars = set("abcdefghijklmnopqrstuvwxyz234567")
b32_ratio = sum(1 for c in subdomain_flat if c in b32_chars) / max(len(subdomain_flat), 1)
if b32_ratio > 0.95 and length > 20:
score += 15
flags.append("base32_encoded")
# Only report if at least one flag triggered
if flags:
results.append({
"fqdn": fqdn,
"subdomain": subdomain,
"base_domain": base_domain,
"entropy": round(entropy, 4),
"subdomain_length": length,
"label_count": label_count,
"score": round(score, 2),
"flags": flags,
"src_ip": query_record.get("src_ip", ""),
"timestamp": query_record.get("timestamp", ""),
"qtype": query_record.get("qtype", ""),
})
# Sort by score descending
results.sort(key=lambda x: x["score"], reverse=True)
return results
# Thresholds for known tunneling tools
TOOL_SIGNATURES = {
"iodine": {
"subdomain_pattern": r"^[a-z0-9]{50,}$", # Long hex-like subdomains
"common_qtypes": ["NULL", "TXT", "CNAME", "MX", "A"],
"typical_entropy": (3.8, 4.2),
"description": "Iodine DNS tunnel - IPv4 over DNS, uses NULL/TXT records",
},
"dnscat2": {
"subdomain_pattern": r"^dnscat\.|^[a-f0-9]{16,}",
"common_qtypes": ["TXT", "CNAME", "MX", "A"],
"typical_entropy": (3.5, 4.5),
"description": "dnscat2 encrypted C2 channel over DNS",
},
"dns2tcp": {
"subdomain_pattern": r"^[a-z2-7]{20,}", # Base32 encoding
"common_qtypes": ["TXT", "KEY"],
"typical_entropy": (3.6, 4.0),
"description": "dns2tcp tunnel - TCP over DNS using TXT/KEY records",
},
"cobalt_strike_dns": {
"subdomain_pattern": r"^[a-f0-9]{12,}\.",
"common_qtypes": ["A", "AAAA", "TXT"],
"typical_entropy": (3.2, 4.0),
"description": "Cobalt Strike DNS beacon - encoded commands in A/TXT records",
},
}
def print_entropy_report(results, top_n=25):
"""Print formatted entropy analysis report."""
print("=" * 80)
print(" DNS ENTROPY ANALYSIS - TUNNELING DETECTION")
print("=" * 80)
print(f" Suspicious queries found: {len(results)}")
print()
if not results:
print(" No suspicious queries detected.")
return
# Group by base domain
domain_groups = {}
for r in results:
bd = r["base_domain"]
if bd not in domain_groups:
domain_groups[bd] = {"count": 0, "max_entropy": 0, "max_score": 0, "queries": []}
domain_groups[bd]["count"] += 1
domain_groups[bd]["max_entropy"] = max(domain_groups[bd]["max_entropy"], r["entropy"])
domain_groups[bd]["max_score"] = max(domain_groups[bd]["max_score"], r["score"])
domain_groups[bd]["queries"].append(r)
# Sort domains by total suspicious query count
sorted_domains = sorted(domain_groups.items(), key=lambda x: x[1]["count"], reverse=True)
print(" TOP SUSPICIOUS BASE DOMAINS")
print(" " + "-" * 76)
print(f" {'Domain':<35} {'Queries':>8} {'Max Ent':>8} {'Max Score':>10}")
print(" " + "-" * 76)
for domain, data in sorted_domains[:20]:
print(f" {domain:<35} {data['count']:>8} {data['max_entropy']:>8.3f} {data['max_score']:>10.1f}")
print()
print(f" TOP {top_n} HIGHEST-SCORING QUERIES")
print(" " + "-" * 76)
for r in results[:top_n]:
print(f" Score: {r['score']:.1f} Entropy: {r['entropy']:.3f} Len: {r['subdomain_length']}")
print(f" FQDN: {r['fqdn'][:75]}")
print(f" Flags: {', '.join(r['flags'])}")
print(f" Source: {r['src_ip']} Type: {r['qtype']}")
print()
Step 3: TXT Record Payload Detection
Identify C2 commands or staged payloads delivered via DNS TXT records:
#!/usr/bin/env python3
"""DNS TXT record payload detection for C2 command delivery."""
import base64
import re
import math
from collections import Counter
def shannon_entropy(data):
"""Calculate Shannon entropy."""
if not data:
return 0.0
counter = Counter(data)
length = len(data)
return -sum((c / length) * math.log2(c / length) for c in counter.values())
def analyze_txt_record(txt_data, domain=""):
"""
Analyze a DNS TXT record response for C2 payload indicators.
Indicators:
- High entropy content (encoded/encrypted payloads)
- Base64-encoded executable content
- PowerShell stager patterns
- Unusually large TXT records (>255 bytes per string, multiple strings)
- Known C2 framework patterns
"""
findings = {
"domain": domain,
"txt_length": len(txt_data),
"entropy": shannon_entropy(txt_data),
"suspicious": False,
"indicators": [],
"decoded_preview": None,
}
# Length check - legitimate TXT records are typically short (SPF, DKIM, verification)
if len(txt_data) > 500:
findings["indicators"].append({
"type": "oversized_txt",
"detail": f"TXT record length {len(txt_data)} exceeds normal threshold (500)",
"severity": "medium",
})
# High entropy - suggests encoded/encrypted payload
if findings["entropy"] > 4.5 and len(txt_data) > 100:
findings["indicators"].append({
"type": "high_entropy_payload",
"detail": f"Entropy {findings['entropy']:.3f} suggests encoded data",
"severity": "high",
})
# Base64 detection
b64_pattern = re.compile(r'^[A-Za-z0-9+/]{40,}={0,2}$')
if b64_pattern.match(txt_data.strip()):
findings["indicators"].append({
"type": "base64_encoded",
"detail": "Content matches base64 pattern",
"severity": "high",
})
try:
decoded = base64.b64decode(txt_data.strip())
preview = decoded[:200]
# Check for PE header (MZ)
if preview[:2] == b'MZ':
findings["indicators"].append({
"type": "pe_executable",
"detail": "Decoded base64 contains PE executable (MZ header)",
"severity": "critical",
})
# Check for ELF header
if preview[:4] == b'\x7fELF':
findings["indicators"].append({
"type": "elf_executable",
"detail": "Decoded base64 contains ELF executable",
"severity": "critical",
})
# Check for PowerShell patterns
decoded_str = decoded.decode("utf-8", errors="ignore")
ps_patterns = [
r"Invoke-Expression",
r"IEX\s*\(",
r"New-Object\s+System\.Net",
r"DownloadString",
r"FromBase64String",
r"Start-Process",
r"\-enc\s",
r"powershell\s.*\-e\s",
]
for pattern in ps_patterns:
if re.search(pattern, decoded_str, re.IGNORECASE):
findings["indicators"].append({
"type": "powershell_stager",
"detail": f"Decoded content contains PowerShell pattern: {pattern}",
"severity": "critical",
})
break
findings["decoded_preview"] = repr(preview[:100])
except Exception:
pass
# Known C2 TXT patterns
cobalt_pattern = re.compile(r'^[a-f0-9]{32,}$', re.IGNORECASE)
if cobalt_pattern.match(txt_data.strip()):
findings["indicators"].append({
"type": "hex_encoded_payload",
"detail": "Pure hex string in TXT record - possible Cobalt Strike beacon config",
"severity": "high",
})
# Multiple concatenated base64 blocks (common in staged delivery)
b64_blocks = re.findall(r'[A-Za-z0-9+/]{50,}={0,2}', txt_data)
if len(b64_blocks) > 3:
findings["indicators"].append({
"type": "multi_block_payload",
"detail": f"{len(b64_blocks)} base64 blocks found - possible staged payload",
"severity": "high",
})
# Check for known legitimate TXT patterns to reduce false positives
legitimate_patterns = [
r'^v=spf1\s', # SPF record
r'^v=DKIM1', # DKIM record
r'^v=DMARC1', # DMARC record
r'^google-site-verification=',
r'^MS=', # Microsoft domain verification
r'^docusign=',
r'^apple-domain-verification=',
r'^facebook-domain-verification=',
r'^_globalsign-domain-verification=',
]
for pattern in legitimate_patterns:
if re.match(pattern, txt_data, re.IGNORECASE):
findings["indicators"] = []
findings["legitimate"] = True
return findings
findings["suspicious"] = len(findings["indicators"]) > 0
return findings
def analyze_txt_records_bulk(records):
"""Analyze a batch of DNS TXT records."""
results = []
for record in records:
domain = record.get("domain", record.get("query", ""))
txt_data = record.get("txt", record.get("answer", ""))
if txt_data:
finding = analyze_txt_record(txt_data, domain)
if finding["suspicious"]:
results.append(finding)
results.sort(
key=lambda x: max((i.get("severity_score", 0) for i in x["indicators"]),
default=0),
reverse=True,
)
return results
Step 4: DGA Domain Classification with Machine Learning
Train a classifier to distinguish DGA-generated domains from legitimate ones:
#!/usr/bin/env python3
"""
DGA domain classification using character-level feature extraction and ML.
Features extracted per domain:
- Shannon entropy of the domain string
- Domain length
- Digit ratio, consonant ratio, vowel ratio
- Longest consecutive consonant sequence
- N-gram frequency deviation from English
- Number of distinct characters
- Presence of dictionary words
"""
import math
import re
import string
from collections import Counter
import numpy as np
try:
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import StandardScaler
HAS_SKLEARN = True
except ImportError:
HAS_SKLEARN = False
# English language character bigram frequencies (normalized, top bigrams)
# Source: Peter Norvig's English letter frequency analysis
ENGLISH_BIGRAMS = {
"th": 0.0356, "he": 0.0307, "in": 0.0243, "er": 0.0205,
"an": 0.0199, "re": 0.0185, "on": 0.0176, "at": 0.0149,
"en": 0.0145, "nd": 0.0135, "ti": 0.0134, "es": 0.0134,
"or": 0.0128, "te": 0.0120, "of": 0.0117, "ed": 0.0117,
"is": 0.0113, "it": 0.0112, "al": 0.0109, "ar": 0.0107,
"st": 0.0105, "to": 0.0104, "nt": 0.0104, "ng": 0.0095,
"se": 0.0093, "ha": 0.0093, "as": 0.0087, "ou": 0.0087,
"io": 0.0083, "le": 0.0083, "ve": 0.0083, "co": 0.0079,
"me": 0.0079, "de": 0.0076, "hi": 0.0076, "ri": 0.0073,
"ro": 0.0073, "ic": 0.0070, "ne": 0.0069, "ea": 0.0069,
}
VOWELS = set("aeiou")
CONSONANTS = set("bcdfghjklmnpqrstvwxyz")
def extract_domain_features(domain):
"""Extract numerical features from a domain name for ML classification."""
domain = domain.lower().strip(".")
# Remove TLD for analysis (focus on SLD + subdomain)
parts = domain.split(".")
if len(parts) > 1:
analysis_str = ".".join(parts[:-1]) # Drop TLD
else:
analysis_str = domain
# Remove dots for character analysis
flat = analysis_str.replace(".", "")
length = len(flat)
if length == 0:
return None
# 1. Shannon entropy
entropy = 0.0
counter = Counter(flat)
for count in counter.values():
p = count / length
entropy -= p * math.log2(p)
# 2. Character ratios
digit_count = sum(1 for c in flat if c.isdigit())
vowel_count = sum(1 for c in flat if c in VOWELS)
consonant_count = sum(1 for c in flat if c in CONSONANTS)
special_count = sum(1 for c in flat if c == '-')
digit_ratio = digit_count / length
vowel_ratio = vowel_count / length
consonant_ratio = consonant_count / length
# 3. Longest consecutive consonant run
max_consonant_run = 0
current_run = 0
for c in flat:
if c in CONSONANTS:
current_run += 1
max_consonant_run = max(max_consonant_run, current_run)
else:
current_run = 0
# 4. Distinct character count and ratio
distinct_chars = len(set(flat))
distinct_ratio = distinct_chars / length
# 5. Bigram frequency deviation from English
bigrams = [flat[i:i+2] for i in range(len(flat) - 1)]
if bigrams:
english_score = sum(
ENGLISH_BIGRAMS.get(bg, 0) for bg in bigrams
) / len(bigrams)
else:
english_score = 0
# 6. Number of labels (dots + 1)
label_count = len(parts)
# 7. Hex character ratio (common in DGA)
hex_chars = set("0123456789abcdef")
hex_ratio = sum(1 for c in flat if c in hex_chars) / length
# 8. Digit-letter transitions (DGA domains mix digits and letters)
transitions = 0
for i in range(1, len(flat)):
if (flat[i].isdigit() != flat[i-1].isdigit()):
transitions += 1
transition_ratio = transitions / max(length - 1, 1)
# 9. Repeated character ratio
if length > 1:
repeats = sum(1 for i in range(1, len(flat)) if flat[i] == flat[i-1])
repeat_ratio = repeats / (length - 1)
else:
repeat_ratio = 0
return {
"domain": domain,
"length": length,
"entropy": round(entropy, 4),
"digit_ratio": round(digit_ratio, 4),
"vowel_ratio": round(vowel_ratio, 4),
"consonant_ratio": round(consonant_ratio, 4),
"max_consonant_run": max_consonant_run,
"distinct_chars": distinct_chars,
"distinct_ratio": round(distinct_ratio, 4),
"english_bigram_score": round(english_score, 6),
"label_count": label_count,
"hex_ratio": round(hex_ratio, 4),
"transition_ratio": round(transition_ratio, 4),
"repeat_ratio": round(repeat_ratio, 4),
"special_count": special_count,
}
FEATURE_COLUMNS = [
"length", "entropy", "digit_ratio", "vowel_ratio", "consonant_ratio",
"max_consonant_run", "distinct_chars", "distinct_ratio",
"english_bigram_score", "label_count", "hex_ratio",
"transition_ratio", "repeat_ratio", "special_count",
]
def features_to_vector(features):
"""Convert feature dict to numpy array."""
return np.array([features[col] for col in FEATURE_COLUMNS])
def train_dga_classifier(legitimate_domains, dga_domains, model_type="random_forest"):
"""
Train a DGA classifier on labeled domain lists.
Args:
legitimate_domains: list of known-good domain strings
dga_domains: list of known DGA domain strings
model_type: 'random_forest' or 'gradient_boosting'
Returns:
trained model, scaler, and evaluation metrics
"""
if not HAS_SKLEARN:
print("[ERROR] scikit-learn required: pip install scikit-learn")
return None, None, None
# Extract features
X_legit = []
X_dga = []
for d in legitimate_domains:
feats = extract_domain_features(d)
if feats:
X_legit.append(features_to_vector(feats))
for d in dga_domains:
feats = extract_domain_features(d)
if feats:
X_dga.append(features_to_vector(feats))
if not X_legit or not X_dga:
print("[ERROR] Insufficient feature data")
return None, None, None
X = np.vstack([np.array(X_legit), np.array(X_dga)])
y = np.array([0] * len(X_legit) + [1] * len(X_dga))
# Scale features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Train/test split
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42, stratify=y
)
# Train model
if model_type == "gradient_boosting":
model = GradientBoostingClassifier(
n_estimators=200, max_depth=6, learning_rate=0.1,
min_samples_split=10, random_state=42,
)
else:
model = RandomForestClassifier(
n_estimators=200, max_depth=15, min_samples_split=5,
random_state=42, n_jobs=-1,
)
model.fit(X_train, y_train)
# Evaluate
y_pred = model.predict(X_test)
report = classification_report(y_test, y_pred, target_names=["legitimate", "dga"],
output_dict=True)
cm = confusion_matrix(y_test, y_pred)
# Cross-validation
cv_scores = cross_val_score(model, X_scaled, y, cv=5, scoring="f1")
metrics = {
"accuracy": report["accuracy"],
"precision_dga": report["dga"]["precision"],
"recall_dga": report["dga"]["recall"],
"f1_dga": report["dga"]["f1-score"],
"precision_legit": report["legitimate"]["precision"],
"recall_legit": report["legitimate"]["recall"],
"confusion_matrix": cm.tolist(),
"cv_f1_mean": cv_scores.mean(),
"cv_f1_std": cv_scores.std(),
"feature_importance": dict(zip(
FEATURE_COLUMNS,
[round(float(x), 4) for x in model.feature_importances_]
)),
}
print(f"[+] Model trained: {model_type}")
print(f" Accuracy: {metrics['accuracy']:.4f}")
print(f" DGA F1: {metrics['f1_dga']:.4f}")
print(f" DGA Recall: {metrics['recall_dga']:.4f}")
print(f" CV F1 (5-fold): {metrics['cv_f1_mean']:.4f} +/- {metrics['cv_f1_std']:.4f}")
print(f" Top features: ", end="")
top_feats = sorted(metrics["feature_importance"].items(), key=lambda x: x[1], reverse=True)[:5]
print(", ".join(f"{k}={v:.3f}" for k, v in top_feats))
return model, scaler, metrics
def classify_domains(domains, model, scaler):
"""Classify a list of domains as legitimate or DGA using a trained model."""
results = []
for domain in domains:
feats = extract_domain_features(domain)
if feats is None:
continue
vec = features_to_vector(feats).reshape(1, -1)
vec_scaled = scaler.transform(vec)
prediction = model.predict(vec_scaled)[0]
probability = model.predict_proba(vec_scaled)[0]
results.append({
"domain": domain,
"prediction": "dga" if prediction == 1 else "legitimate",
"confidence": round(float(max(probability)), 4),
"dga_probability": round(float(probability[1]), 4),
"features": feats,
})
return results
Step 5: DNS Beaconing Pattern Detection
Identify periodic DNS query patterns indicative of C2 check-ins:
#!/usr/bin/env python3
"""DNS beaconing detection - identifies periodic C2 check-in patterns."""
import math
from collections import defaultdict
from datetime import datetime, timedelta
import numpy as np
def parse_timestamp(ts_str):
"""Parse various timestamp formats to datetime."""
formats = [
"%Y-%m-%dT%H:%M:%S.%fZ",
"%Y-%m-%dT%H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%d %H:%M:%S",
]
for fmt in formats:
try:
return datetime.strptime(ts_str, fmt)
except ValueError:
continue
# Try epoch timestamp
try:
ts_float = float(ts_str)
return datetime.utcfromtimestamp(ts_float)
except (ValueError, OverflowError, OSError):
pass
return None
def detect_beaconing(dns_queries, min_queries=10, max_jitter_pct=25,
min_interval_sec=10, max_interval_sec=7200):
"""
Detect DNS beaconing by analyzing inter-query timing intervals.
Beaconing indicators:
- Regular inter-query intervals (low standard deviation)
- Consistent query sizes
- Single source IP to single domain over extended period
- Low jitter (variation in timing)
Args:
dns_queries: list of dicts with 'src_ip', 'query', 'timestamp'
min_queries: minimum queries to analyze (default 10)
max_jitter_pct: maximum coefficient of variation for beacon (default 25%)
min_interval_sec: minimum beacon interval to detect (default 10s)
max_interval_sec: maximum beacon interval to detect (default 7200s / 2hr)
Returns:
list of detected beacon patterns with confidence scores
"""
# Group queries by (source IP, base domain)
groups = defaultdict(list)
for q in dns_queries:
src_ip = q.get("src_ip", "")
fqdn = q.get("query", "").lower().rstrip(".")
ts_str = q.get("timestamp", "")
ts = parse_timestamp(ts_str)
if not ts or not src_ip or not fqdn:
continue
# Extract base domain (last 2 labels)
parts = fqdn.split(".")
if len(parts) >= 2:
base_domain = ".".join(parts[-2:])
else:
base_domain = fqdn
groups[(src_ip, base_domain)].append(ts)
beacons = []
for (src_ip, base_domain), timestamps in groups.items():
if len(timestamps) < min_queries:
continue
# Sort timestamps and compute intervals
timestamps.sort()
intervals = [
(timestamps[i+1] - timestamps[i]).total_seconds()
for i in range(len(timestamps) - 1)
]
if not intervals:
continue
intervals = np.array(intervals)
# Filter out zero intervals (duplicate timestamps)
intervals = intervals[intervals > 0]
if len(intervals) < min_queries - 1:
continue
mean_interval = np.mean(intervals)
std_interval = np.std(intervals)
median_interval = np.median(intervals)
# Skip if interval is outside detection range
if mean_interval < min_interval_sec or mean_interval > max_interval_sec:
continue
# Coefficient of variation (jitter)
cv = (std_interval / mean_interval * 100) if mean_interval > 0 else 100
# Time span of activity
time_span = (timestamps[-1] - timestamps[0]).total_seconds()
hours_active = time_span / 3600
# Beacon scoring
score = 0.0
flags = []
# Low jitter = strong beacon indicator
if cv < 5:
score += 40
flags.append(f"very_low_jitter:CV={cv:.1f}%")
elif cv < 15:
score += 30
flags.append(f"low_jitter:CV={cv:.1f}%")
elif cv < max_jitter_pct:
score += 15
flags.append(f"moderate_jitter:CV={cv:.1f}%")
else:
continue # Too much jitter, not a beacon
# Long duration increases confidence
if hours_active > 24:
score += 20
flags.append(f"persistent:{hours_active:.1f}h")
elif hours_active > 4:
score += 10
flags.append(f"sustained:{hours_active:.1f}h")
# High query count increases confidence
if len(timestamps) > 100:
score += 15
flags.append(f"high_volume:{len(timestamps)}")
elif len(timestamps) > 50:
score += 10
flags.append(f"moderate_volume:{len(timestamps)}")
# Common C2 intervals (60s, 120s, 300s, 600s, 900s, 1800s, 3600s)
common_intervals = [60, 120, 300, 600, 900, 1800, 3600]
for ci in common_intervals:
if abs(mean_interval - ci) < ci * 0.1: # Within 10% of common interval
score += 10
flags.append(f"common_c2_interval:~{ci}s")
break
beacons.append({
"src_ip": src_ip,
"base_domain": base_domain,
"query_count": len(timestamps),
"mean_interval_sec": round(mean_interval, 2),
"median_interval_sec": round(median_interval, 2),
"std_interval_sec": round(std_interval, 2),
"jitter_cv_pct": round(cv, 2),
"first_seen": timestamps[0].isoformat(),
"last_seen": timestamps[-1].isoformat(),
"duration_hours": round(hours_active, 2),
"score": round(score, 1),
"flags": flags,
})
beacons.sort(key=lambda x: x["score"], reverse=True)
return beacons
def print_beacon_report(beacons, top_n=20):
"""Print formatted beacon detection report."""
print("=" * 80)
print(" DNS BEACONING DETECTION REPORT")
print("=" * 80)
print(f" Beacon patterns detected: {len(beacons)}")
print()
if not beacons:
print(" No beaconing patterns detected.")
return
print(f" TOP {min(top_n, len(beacons))} BEACON CANDIDATES")
print(" " + "-" * 76)
for b in beacons[:top_n]:
print(f" Score: {b['score']:.1f} | {b['src_ip']} -> {b['base_domain']}")
print(f" Queries: {b['query_count']} "
f"Interval: {b['mean_interval_sec']:.1f}s +/- {b['std_interval_sec']:.1f}s "
f"Jitter: {b['jitter_cv_pct']:.1f}%")
print(f" Active: {b['duration_hours']:.1f}h "
f"({b['first_seen']} to {b['last_seen']})")
print(f" Flags: {', '.join(b['flags'])}")
print()
Step 6: Integrated DNS C2 Detection Pipeline
Combine all detection methods into a unified analysis:
DNS C2 Detection Pipeline Architecture:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
┌────────────────────────────────────────────────────────┐
│ DATA SOURCES │
│ Zeek dns.log | Suricata EVE | Recursive Resolver │
│ Passive DNS | PCAP capture | EDR DNS telemetry │
└───────────────────────┬────────────────────────────────┘
│
┌───────────────────────▼────────────────────────────────┐
│ PREPROCESSING │
│ Parse timestamps | Extract subdomains | Normalize │
│ FQDN | Resolve base domain | Lookup in whitelist │
└───────────────────────┬────────────────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
┌───────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ ENTROPY │ │ BEACONING │ │ DGA │
│ ANALYSIS │ │ DETECTION │ │ CLASSIFIER │
│ │ │ │ │ │
│ Shannon ent. │ │ Interval │ │ ML model │
│ Subdomain │ │ analysis │ │ Random │
│ length │ │ Jitter/CV │ │ Forest or │
│ Encoding │ │ Duration │ │ Gradient │
│ patterns │ │ Periodicity │ │ Boosting │
└───────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
┌───────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ TXT RECORD │ │ TOOL │ │ PASSIVE │
│ PAYLOAD │ │ SIGNATURE │ │ DNS │
│ ANALYSIS │ │ MATCHING │ │ ENRICHMENT │
│ │ │ │ │ │
│ Base64 decode│ │ Iodine │ │ First seen │
│ PE/ELF detect│ │ dnscat2 │ │ Registrar │
│ PS stager │ │ dns2tcp │ │ Age check │
│ Size anomaly │ │ Cobalt DNS │ │ Reputation │
└───────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
┌───────▼───────────────▼───────────────▼────────────────┐
│ CORRELATION ENGINE │
│ Combine scores from all detectors │
│ Weighted scoring: entropy(30%) + beacon(25%) + │
│ DGA(20%) + TXT payload(15%) + signature(10%) │
│ Threshold: score > 60 = alert, > 40 = investigate │
└───────────────────────┬────────────────────────────────┘
│
┌───────────────────────▼────────────────────────────────┐
│ ALERTING & RESPONSE │
│ Generate SIEM alert with all evidence │
│ Block domain in DNS firewall / RPZ │
│ Isolate endpoint via EDR │
│ Create incident ticket with IOCs │
└────────────────────────────────────────────────────────┘
Step 7: SIEM Detection Rules
Deploy detection queries in your SIEM platform:
Splunk SPL - DNS Tunneling Detection:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- High entropy subdomain queries
index=dns sourcetype="bro:dns:json" OR sourcetype="suricata:dns"
| eval subdomain=mvindex(split(query,"."),0)
| eval sub_len=len(subdomain)
| where sub_len > 30
| eval char_counts=mvmap(split(subdomain,""),1)
| lookup dns_entropy_lookup subdomain OUTPUT entropy
| where entropy > 3.5
| stats count as query_count dc(query) as unique_queries
avg(sub_len) as avg_sub_len values(query) as sample_queries
by src_ip, domain
| where query_count > 20
| sort -query_count
-- DNS TXT record abuse
index=dns (qtype="TXT" OR qtype_name="TXT")
NOT (query="*._domainkey.*" OR query="*._dmarc.*" OR query="*._spf.*")
| stats count as txt_queries dc(query) as unique_txt_queries
values(query) as domains
by src_ip
| where txt_queries > 50
| sort -txt_queries
-- DNS beaconing (regular interval queries)
index=dns sourcetype="bro:dns:json"
| bin _time span=60s
| stats count by src_ip, query, _time
| streamstats window=10 current=t avg(count) as avg_count stdev(count) as std_count by src_ip, query
| eval cv = if(avg_count>0, (std_count/avg_count)*100, 100)
| where cv < 20 AND avg_count > 0
| stats count as beacon_windows avg(cv) as avg_jitter
min(_time) as first_seen max(_time) as last_seen
by src_ip, query
| where beacon_windows > 10
| sort -beacon_windows
-- Unusual record type volume (NULL, KEY, SRV for tunneling)
index=dns (qtype_name="NULL" OR qtype_name="KEY" OR qtype_name="SRV"
OR qtype_name="CNAME" OR qtype_name="MX")
NOT qtype_name="A" NOT qtype_name="AAAA" NOT qtype_name="PTR"
| stats count by src_ip, qtype_name, query
| where count > 10
| sort -count
Elastic KQL - DNS C2 Detection:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Long subdomain queries (potential tunneling)
dns.question.name: * and not dns.question.name: *.in-addr.arpa
| where length(dns.question.subdomain) > 40
-- High volume DNS to single domain
event.dataset: "zeek.dns" or event.dataset: "suricata.dns"
| stats count by source.ip, dns.question.registered_domain
| where count > 500
-- TXT record queries to non-standard domains
dns.question.type: "TXT"
and not dns.question.name: (*._domainkey.* or *._dmarc.* or *._spf.*)
Zeek Script - DNS Tunneling Indicator:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# dns_tunnel_detect.zeek
@load base/protocols/dns
module DNSTunnel;
export {
redef enum Notice::Type += {
DNS_Tunneling_Suspected,
DNS_High_Entropy_Query,
DNS_Excessive_TXT_Queries,
};
const entropy_threshold = 3.5 &redef;
const subdomain_length_threshold = 40 &redef;
const txt_query_threshold = 50 &redef;
const tracking_interval = 5min &redef;
}
global txt_query_tracker: table[addr] of count &create_expire=5min &default=0;
global domain_query_tracker: table[addr, string] of count &create_expire=10min &default=0;
function shannon_entropy(s: string): double
{
local counts: table[string] of count;
local total = |s|;
if (total == 0) return 0.0;
for (i in s)
{
local c = s[i];
if (c !in counts) counts[c] = 0;
++counts[c];
}
local ent = 0.0;
for (ch, cnt in counts)
{
local p = cnt * 1.0 / total;
ent -= p * log2(p);
}
return ent;
}
event dns_request(c: connection, msg: dns_msg, query: string, qtype: count,
qclass: count)
{
if (|query| == 0) return;
# Track TXT queries
if (qtype == 16) # TXT
{
++txt_query_tracker[c$id$orig_h];
if (txt_query_tracker[c$id$orig_h] == txt_query_threshold)
{
NOTICE([
$note=DNS_Excessive_TXT_Queries,
$conn=c,
$msg=fmt("Host %s made %d TXT queries in tracking window",
c$id$orig_h, txt_query_threshold),
$identifier=cat(c$id$orig_h),
]);
}
}
# Extract subdomain and check entropy
local parts = split_string(query, /\./);
if (|parts| < 3) return;
# Subdomain = everything except last two labels
local subdomain = "";
local i = 0;
for (idx in parts)
{
if (i < |parts| - 2)
subdomain += parts[idx];
++i;
}
if (|subdomain| > subdomain_length_threshold)
{
local ent = shannon_entropy(subdomain);
if (ent > entropy_threshold)
{
NOTICE([
$note=DNS_High_Entropy_Query,
$conn=c,
$msg=fmt("High entropy DNS query: entropy=%.2f len=%d query=%s",
ent, |subdomain|, query),
$identifier=cat(c$id$orig_h, query),
]);
}
}
}
Step 8: Suricata Rules for Known DNS C2 Tools
# suricata-dns-c2.rules
# DNS Tunneling and C2 Detection Rules
# Iodine DNS tunnel detection
alert dns any any -> any any (msg:"ET TROJAN Iodine DNS Tunnel Activity - NULL Query"; \
dns.query; content:"."; pcre:"/^[a-z0-9]{50,}\.[a-z0-9.-]+$/i"; \
dns_query; content:"|00 0a|"; \
classtype:trojan-activity; sid:2030001; rev:1;)
# dnscat2 DNS tunnel detection
alert dns any any -> any any (msg:"ET TROJAN dnscat2 DNS Tunnel -
…(truncated)
1---
2name: detecting-command-and-control-over-dns
3description: 'Detects command-and-control (C2) communications tunneled through DNS
4 protocol including DNS tunneling tools (Iodine, dnscat2, dns2tcp, Cobalt Strike
5 DNS beacon), domain generation algorithms (DGA), encoded payload delivery via TXT/CNAME
6 records, and DNS beaconing patterns. Covers Shannon entropy analysis of query subdomains,
7 statistical anomaly detection, ML-based DGA classification, passive DNS correlation,
8 and Zeek/Suricata signature development. Activates for requests involving DNS-based
9 C2 detection, DNS tunnel identification, suspicious DNS traffic investigation, or
10 DGA domain classification.
11
12 '
13domain: cybersecurity
14subdomain: network-security
15tags:
16- dns
17- c2
18- tunneling
19- dga
20- network-forensics
21- threat-detection
22version: 1.0.0
23author: mukul975
24license: Apache-2.0
25nist_csf:
26- PR.IR-01
27- DE.CM-01
28- ID.AM-03
29- PR.DS-02
30mitre_attack:
31- T1046
32- T1040
33- T1557
34- T1071
35- T1095
36source: https://github.com/mukul975/Anthropic-Cybersecurity-Skills
37source_commit: 04450304b12645cb2b974ab96d28c0664758a88d
38note: "Vendored verbatim from an external Apache-2.0 security-skill library, pinned by commit. Exceeds the internal 300-line skill guideline (agent-code-constraints.md) -- kept as-is because this is vendored reference material (forensics/threat-intel procedure), not Yana AI-authored content, and trimming would damage technical accuracy."
39metadata:
40 source: https://skillmd.com/skills/yanacuti1121/detecting-command-and-control-over-dns
41---
42
43# Detecting Command and Control Over DNS
44
45## When to Use
46
47- Investigating suspected DNS tunneling used for C2 communication or data exfiltration
48- Analyzing DNS query logs for signs of encoded payloads in subdomain strings
49- Classifying domains as DGA-generated vs. legitimate using statistical or ML methods
50- Detecting DNS beaconing patterns (regular intervals, consistent query sizes)
51- Hunting for Iodine, dnscat2, dns2tcp, Cobalt Strike DNS, or Sliver DNS traffic
52- Monitoring TXT record abuse for command delivery or staged payload download
53- Building DNS anomaly detection rules for SOC/SIEM deployment
54
55**Do not use** for general DNS performance monitoring or DNS configuration auditing; use DNS health monitoring tools for those. For HTTP/HTTPS-based C2 detection, use network traffic analysis skills focused on web protocols.
56
57**DISCLAIMER**: DNS tunneling tools referenced in this skill (Iodine, dnscat2, dns2tcp) are dual-use. They have legitimate uses (bypassing captive portals, security research) and malicious uses (C2 channels, exfiltration). Only deploy detection in networks you are authorized to monitor. Testing tunneling tools requires explicit authorization.
58
59## Prerequisites
60
61- DNS query logs from recursive resolver, Zeek/Bro, Suricata, or passive DNS tap
62- Python 3.9+ with `numpy`, `scikit-learn`, `pandas`, `tldextract`, and `dnspython`
63- Zeek (formerly Bro) with dns.log output or Suricata with DNS EVE JSON logging
64- SIEM access (Splunk, Elastic, Microsoft Sentinel) for log correlation
65- Passive DNS database access (CIRCL pDNS, Farsight DNSDB, or internal) for enrichment
66- Wireshark/tshark for packet-level DNS inspection
67- Known-good domain whitelist (Alexa/Tranco top 1M or Majestic Million)
68
69## Workflow
70
71### Step 1: Collect and Parse DNS Query Logs
72
73Ingest DNS traffic from network sensors and parse into analyzable format:
74
75```bash
76# Zeek - extract dns.log fields
77# Default Zeek dns.log columns:
78# ts uid id.orig_h id.orig_p id.resp_h id.resp_p proto trans_id rtt query
79# qclass qclass_name qtype qtype_name rcode rcode_name AA TC RD RA Z
80# answers TTLs rejected
81
82# Filter for potentially suspicious record types
83cat dns.log | zeek-cut ts id.orig_h query qtype_name answers rcode_name | \
84 grep -E "TXT|NULL|CNAME|MX" > suspicious_qtypes.log
85
86# Extract unique queried domains
87cat dns.log | zeek-cut query | sort -u > unique_domains.txt
88
89# Suricata EVE JSON - extract DNS events
90cat eve.json | jq -r 'select(.event_type=="dns") |
91 [.timestamp, .src_ip, .dns.rrname, .dns.rrtype, .dns.rcode] |
92 @tsv' > dns_events.tsv
93
94# tshark - extract DNS queries from pcap
95tshark -r capture.pcap -T fields \
96 -e frame.time -e ip.src -e ip.dst \
97 -e dns.qry.name -e dns.qry.type \
98 -e dns.resp.type -e dns.txt \
99 -Y "dns" > dns_queries.tsv
100
101# Count queries per domain (find high-volume destinations)
102cat dns.log | zeek-cut query | \
103 awk -F. '{print $(NF-1)"."$NF}' | \
104 sort | uniq -c | sort -rn | head -50
105```
106
107### Step 2: Shannon Entropy Analysis of DNS Queries
108
109Calculate entropy of subdomain strings to identify encoded/encrypted data:
110
111```python
112#!/usr/bin/env python3
113"""Shannon entropy analysis for DNS query subdomains."""
114
115import math
116import csv
117import sys
118from collections import Counter
119
120try:
121 import tldextract
122 HAS_TLDEXTRACT = True
123except ImportError:
124 HAS_TLDEXTRACT = False
125
126
127def shannon_entropy(data):
128 """Calculate Shannon entropy of a string (bits per character)."""
129 if not data:
130 return 0.0
131 counter = Counter(data)
132 length = len(data)
133 entropy = -sum(
134 (count / length) * math.log2(count / length)
135 for count in counter.values()
136 )
137 return entropy
138
139
140def extract_subdomain(fqdn):
141 """Extract the subdomain portion from a fully qualified domain name."""
142 if HAS_TLDEXTRACT:
143 ext = tldextract.extract(fqdn)
144 if ext.subdomain:
145 return ext.subdomain, f"{ext.domain}.{ext.suffix}"
146 return "", f"{ext.domain}.{ext.suffix}"
147 else:
148 # Fallback: assume last two labels are domain + TLD
149 parts = fqdn.rstrip(".").split(".")
150 if len(parts) > 2:
151 return ".".join(parts[:-2]), ".".join(parts[-2:])
152 return "", fqdn
153
154
155def analyze_dns_entropy(queries, entropy_threshold=3.5, length_threshold=30):
156 """
157 Analyze DNS queries for tunneling indicators using entropy.
158
159 Thresholds (tunable per environment):
160 - entropy_threshold: Shannon entropy above this flags as suspicious (3.5-4.0 typical)
161 - length_threshold: Subdomain length above this flags as suspicious (30-50 chars)
162
163 Returns list of flagged queries with scores.
164 """
165 results = []
166
167 for query_record in queries:
168 fqdn = query_record.get("query", "").lower().rstrip(".")
169 if not fqdn:
170 continue
171
172 subdomain, base_domain = extract_subdomain(fqdn)
173 if not subdomain:
174 continue
175
176 # Remove dots from subdomain for entropy calculation
177 subdomain_flat = subdomain.replace(".", "")
178 if not subdomain_flat:
179 continue
180
181 entropy = shannon_entropy(subdomain_flat)
182 length = len(subdomain_flat)
183 label_count = subdomain.count(".") + 1
184
185 # Scoring: higher = more suspicious
186 score = 0.0
187 flags = []
188
189 if entropy > entropy_threshold:
190 score += (entropy - entropy_threshold) * 25
191 flags.append(f"high_entropy:{entropy:.2f}")
192
193 if length > length_threshold:
194 score += (length - length_threshold) * 0.5
195 flags.append(f"long_subdomain:{length}")
196
197 if label_count > 4:
198 score += label_count * 2
199 flags.append(f"many_labels:{label_count}")
200
201 # Check for hex/base32/base64 encoding patterns
202 hex_ratio = sum(1 for c in subdomain_flat if c in "0123456789abcdef") / max(len(subdomain_flat), 1)
203 if hex_ratio > 0.85 and length > 20:
204 score += 20
205 flags.append("hex_encoded")
206
207 b32_chars = set("abcdefghijklmnopqrstuvwxyz234567")
208 b32_ratio = sum(1 for c in subdomain_flat if c in b32_chars) / max(len(subdomain_flat), 1)
209 if b32_ratio > 0.95 and length > 20:
210 score += 15
211 flags.append("base32_encoded")
212
213 # Only report if at least one flag triggered
214 if flags:
215 results.append({
216 "fqdn": fqdn,
217 "subdomain": subdomain,
218 "base_domain": base_domain,
219 "entropy": round(entropy, 4),
220 "subdomain_length": length,
221 "label_count": label_count,
222 "score": round(score, 2),
223 "flags": flags,
224 "src_ip": query_record.get("src_ip", ""),
225 "timestamp": query_record.get("timestamp", ""),
226 "qtype": query_record.get("qtype", ""),
227 })
228
229 # Sort by score descending
230 results.sort(key=lambda x: x["score"], reverse=True)
231 return results
232
233
234# Thresholds for known tunneling tools
235TOOL_SIGNATURES = {
236 "iodine": {
237 "subdomain_pattern": r"^[a-z0-9]{50,}$", # Long hex-like subdomains
238 "common_qtypes": ["NULL", "TXT", "CNAME", "MX", "A"],
239 "typical_entropy": (3.8, 4.2),
240 "description": "Iodine DNS tunnel - IPv4 over DNS, uses NULL/TXT records",
241 },
242 "dnscat2": {
243 "subdomain_pattern": r"^dnscat\.|^[a-f0-9]{16,}",
244 "common_qtypes": ["TXT", "CNAME", "MX", "A"],
245 "typical_entropy": (3.5, 4.5),
246 "description": "dnscat2 encrypted C2 channel over DNS",
247 },
248 "dns2tcp": {
249 "subdomain_pattern": r"^[a-z2-7]{20,}", # Base32 encoding
250 "common_qtypes": ["TXT", "KEY"],
251 "typical_entropy": (3.6, 4.0),
252 "description": "dns2tcp tunnel - TCP over DNS using TXT/KEY records",
253 },
254 "cobalt_strike_dns": {
255 "subdomain_pattern": r"^[a-f0-9]{12,}\.",
256 "common_qtypes": ["A", "AAAA", "TXT"],
257 "typical_entropy": (3.2, 4.0),
258 "description": "Cobalt Strike DNS beacon - encoded commands in A/TXT records",
259 },
260}
261
262
263def print_entropy_report(results, top_n=25):
264 """Print formatted entropy analysis report."""
265 print("=" * 80)
266 print(" DNS ENTROPY ANALYSIS - TUNNELING DETECTION")
267 print("=" * 80)
268 print(f" Suspicious queries found: {len(results)}")
269 print()
270
271 if not results:
272 print(" No suspicious queries detected.")
273 return
274
275 # Group by base domain
276 domain_groups = {}
277 for r in results:
278 bd = r["base_domain"]
279 if bd not in domain_groups:
280 domain_groups[bd] = {"count": 0, "max_entropy": 0, "max_score": 0, "queries": []}
281 domain_groups[bd]["count"] += 1
282 domain_groups[bd]["max_entropy"] = max(domain_groups[bd]["max_entropy"], r["entropy"])
283 domain_groups[bd]["max_score"] = max(domain_groups[bd]["max_score"], r["score"])
284 domain_groups[bd]["queries"].append(r)
285
286 # Sort domains by total suspicious query count
287 sorted_domains = sorted(domain_groups.items(), key=lambda x: x[1]["count"], reverse=True)
288
289 print(" TOP SUSPICIOUS BASE DOMAINS")
290 print(" " + "-" * 76)
291 print(f" {'Domain':<35} {'Queries':>8} {'Max Ent':>8} {'Max Score':>10}")
292 print(" " + "-" * 76)
293 for domain, data in sorted_domains[:20]:
294 print(f" {domain:<35} {data['count']:>8} {data['max_entropy']:>8.3f} {data['max_score']:>10.1f}")
295 print()
296
297 print(f" TOP {top_n} HIGHEST-SCORING QUERIES")
298 print(" " + "-" * 76)
299 for r in results[:top_n]:
300 print(f" Score: {r['score']:.1f} Entropy: {r['entropy']:.3f} Len: {r['subdomain_length']}")
301 print(f" FQDN: {r['fqdn'][:75]}")
302 print(f" Flags: {', '.join(r['flags'])}")
303 print(f" Source: {r['src_ip']} Type: {r['qtype']}")
304 print()
305```
306
307### Step 3: TXT Record Payload Detection
308
309Identify C2 commands or staged payloads delivered via DNS TXT records:
310
311```python
312#!/usr/bin/env python3
313"""DNS TXT record payload detection for C2 command delivery."""
314
315import base64
316import re
317import math
318from collections import Counter
319
320
321def shannon_entropy(data):
322 """Calculate Shannon entropy."""
323 if not data:
324 return 0.0
325 counter = Counter(data)
326 length = len(data)
327 return -sum((c / length) * math.log2(c / length) for c in counter.values())
328
329
330def analyze_txt_record(txt_data, domain=""):
331 """
332 Analyze a DNS TXT record response for C2 payload indicators.
333
334 Indicators:
335 - High entropy content (encoded/encrypted payloads)
336 - Base64-encoded executable content
337 - PowerShell stager patterns
338 - Unusually large TXT records (>255 bytes per string, multiple strings)
339 - Known C2 framework patterns
340 """
341 findings = {
342 "domain": domain,
343 "txt_length": len(txt_data),
344 "entropy": shannon_entropy(txt_data),
345 "suspicious": False,
346 "indicators": [],
347 "decoded_preview": None,
348 }
349
350 # Length check - legitimate TXT records are typically short (SPF, DKIM, verification)
351 if len(txt_data) > 500:
352 findings["indicators"].append({
353 "type": "oversized_txt",
354 "detail": f"TXT record length {len(txt_data)} exceeds normal threshold (500)",
355 "severity": "medium",
356 })
357
358 # High entropy - suggests encoded/encrypted payload
359 if findings["entropy"] > 4.5 and len(txt_data) > 100:
360 findings["indicators"].append({
361 "type": "high_entropy_payload",
362 "detail": f"Entropy {findings['entropy']:.3f} suggests encoded data",
363 "severity": "high",
364 })
365
366 # Base64 detection
367 b64_pattern = re.compile(r'^[A-Za-z0-9+/]{40,}={0,2}$')
368 if b64_pattern.match(txt_data.strip()):
369 findings["indicators"].append({
370 "type": "base64_encoded",
371 "detail": "Content matches base64 pattern",
372 "severity": "high",
373 })
374 try:
375 decoded = base64.b64decode(txt_data.strip())
376 preview = decoded[:200]
377
378 # Check for PE header (MZ)
379 if preview[:2] == b'MZ':
380 findings["indicators"].append({
381 "type": "pe_executable",
382 "detail": "Decoded base64 contains PE executable (MZ header)",
383 "severity": "critical",
384 })
385
386 # Check for ELF header
387 if preview[:4] == b'\x7fELF':
388 findings["indicators"].append({
389 "type": "elf_executable",
390 "detail": "Decoded base64 contains ELF executable",
391 "severity": "critical",
392 })
393
394 # Check for PowerShell patterns
395 decoded_str = decoded.decode("utf-8", errors="ignore")
396 ps_patterns = [
397 r"Invoke-Expression",
398 r"IEX\s*\(",
399 r"New-Object\s+System\.Net",
400 r"DownloadString",
401 r"FromBase64String",
402 r"Start-Process",
403 r"\-enc\s",
404 r"powershell\s.*\-e\s",
405 ]
406 for pattern in ps_patterns:
407 if re.search(pattern, decoded_str, re.IGNORECASE):
408 findings["indicators"].append({
409 "type": "powershell_stager",
410 "detail": f"Decoded content contains PowerShell pattern: {pattern}",
411 "severity": "critical",
412 })
413 break
414
415 findings["decoded_preview"] = repr(preview[:100])
416
417 except Exception:
418 pass
419
420 # Known C2 TXT patterns
421 cobalt_pattern = re.compile(r'^[a-f0-9]{32,}$', re.IGNORECASE)
422 if cobalt_pattern.match(txt_data.strip()):
423 findings["indicators"].append({
424 "type": "hex_encoded_payload",
425 "detail": "Pure hex string in TXT record - possible Cobalt Strike beacon config",
426 "severity": "high",
427 })
428
429 # Multiple concatenated base64 blocks (common in staged delivery)
430 b64_blocks = re.findall(r'[A-Za-z0-9+/]{50,}={0,2}', txt_data)
431 if len(b64_blocks) > 3:
432 findings["indicators"].append({
433 "type": "multi_block_payload",
434 "detail": f"{len(b64_blocks)} base64 blocks found - possible staged payload",
435 "severity": "high",
436 })
437
438 # Check for known legitimate TXT patterns to reduce false positives
439 legitimate_patterns = [
440 r'^v=spf1\s', # SPF record
441 r'^v=DKIM1', # DKIM record
442 r'^v=DMARC1', # DMARC record
443 r'^google-site-verification=',
444 r'^MS=', # Microsoft domain verification
445 r'^docusign=',
446 r'^apple-domain-verification=',
447 r'^facebook-domain-verification=',
448 r'^_globalsign-domain-verification=',
449 ]
450 for pattern in legitimate_patterns:
451 if re.match(pattern, txt_data, re.IGNORECASE):
452 findings["indicators"] = []
453 findings["legitimate"] = True
454 return findings
455
456 findings["suspicious"] = len(findings["indicators"]) > 0
457 return findings
458
459
460def analyze_txt_records_bulk(records):
461 """Analyze a batch of DNS TXT records."""
462 results = []
463 for record in records:
464 domain = record.get("domain", record.get("query", ""))
465 txt_data = record.get("txt", record.get("answer", ""))
466 if txt_data:
467 finding = analyze_txt_record(txt_data, domain)
468 if finding["suspicious"]:
469 results.append(finding)
470
471 results.sort(
472 key=lambda x: max((i.get("severity_score", 0) for i in x["indicators"]),
473 default=0),
474 reverse=True,
475 )
476 return results
477```
478
479### Step 4: DGA Domain Classification with Machine Learning
480
481Train a classifier to distinguish DGA-generated domains from legitimate ones:
482
483```python
484#!/usr/bin/env python3
485"""
486DGA domain classification using character-level feature extraction and ML.
487
488Features extracted per domain:
489 - Shannon entropy of the domain string
490 - Domain length
491 - Digit ratio, consonant ratio, vowel ratio
492 - Longest consecutive consonant sequence
493 - N-gram frequency deviation from English
494 - Number of distinct characters
495 - Presence of dictionary words
496"""
497
498import math
499import re
500import string
501from collections import Counter
502
503import numpy as np
504
505try:
506 from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
507 from sklearn.model_selection import train_test_split, cross_val_score
508 from sklearn.metrics import classification_report, confusion_matrix
509 from sklearn.preprocessing import StandardScaler
510 HAS_SKLEARN = True
511except ImportError:
512 HAS_SKLEARN = False
513
514
515# English language character bigram frequencies (normalized, top bigrams)
516# Source: Peter Norvig's English letter frequency analysis
517ENGLISH_BIGRAMS = {
518 "th": 0.0356, "he": 0.0307, "in": 0.0243, "er": 0.0205,
519 "an": 0.0199, "re": 0.0185, "on": 0.0176, "at": 0.0149,
520 "en": 0.0145, "nd": 0.0135, "ti": 0.0134, "es": 0.0134,
521 "or": 0.0128, "te": 0.0120, "of": 0.0117, "ed": 0.0117,
522 "is": 0.0113, "it": 0.0112, "al": 0.0109, "ar": 0.0107,
523 "st": 0.0105, "to": 0.0104, "nt": 0.0104, "ng": 0.0095,
524 "se": 0.0093, "ha": 0.0093, "as": 0.0087, "ou": 0.0087,
525 "io": 0.0083, "le": 0.0083, "ve": 0.0083, "co": 0.0079,
526 "me": 0.0079, "de": 0.0076, "hi": 0.0076, "ri": 0.0073,
527 "ro": 0.0073, "ic": 0.0070, "ne": 0.0069, "ea": 0.0069,
528}
529
530VOWELS = set("aeiou")
531CONSONANTS = set("bcdfghjklmnpqrstvwxyz")
532
533
534def extract_domain_features(domain):
535 """Extract numerical features from a domain name for ML classification."""
536 domain = domain.lower().strip(".")
537
538 # Remove TLD for analysis (focus on SLD + subdomain)
539 parts = domain.split(".")
540 if len(parts) > 1:
541 analysis_str = ".".join(parts[:-1]) # Drop TLD
542 else:
543 analysis_str = domain
544
545 # Remove dots for character analysis
546 flat = analysis_str.replace(".", "")
547 length = len(flat)
548
549 if length == 0:
550 return None
551
552 # 1. Shannon entropy
553 entropy = 0.0
554 counter = Counter(flat)
555 for count in counter.values():
556 p = count / length
557 entropy -= p * math.log2(p)
558
559 # 2. Character ratios
560 digit_count = sum(1 for c in flat if c.isdigit())
561 vowel_count = sum(1 for c in flat if c in VOWELS)
562 consonant_count = sum(1 for c in flat if c in CONSONANTS)
563 special_count = sum(1 for c in flat if c == '-')
564
565 digit_ratio = digit_count / length
566 vowel_ratio = vowel_count / length
567 consonant_ratio = consonant_count / length
568
569 # 3. Longest consecutive consonant run
570 max_consonant_run = 0
571 current_run = 0
572 for c in flat:
573 if c in CONSONANTS:
574 current_run += 1
575 max_consonant_run = max(max_consonant_run, current_run)
576 else:
577 current_run = 0
578
579 # 4. Distinct character count and ratio
580 distinct_chars = len(set(flat))
581 distinct_ratio = distinct_chars / length
582
583 # 5. Bigram frequency deviation from English
584 bigrams = [flat[i:i+2] for i in range(len(flat) - 1)]
585 if bigrams:
586 english_score = sum(
587 ENGLISH_BIGRAMS.get(bg, 0) for bg in bigrams
588 ) / len(bigrams)
589 else:
590 english_score = 0
591
592 # 6. Number of labels (dots + 1)
593 label_count = len(parts)
594
595 # 7. Hex character ratio (common in DGA)
596 hex_chars = set("0123456789abcdef")
597 hex_ratio = sum(1 for c in flat if c in hex_chars) / length
598
599 # 8. Digit-letter transitions (DGA domains mix digits and letters)
600 transitions = 0
601 for i in range(1, len(flat)):
602 if (flat[i].isdigit() != flat[i-1].isdigit()):
603 transitions += 1
604 transition_ratio = transitions / max(length - 1, 1)
605
606 # 9. Repeated character ratio
607 if length > 1:
608 repeats = sum(1 for i in range(1, len(flat)) if flat[i] == flat[i-1])
609 repeat_ratio = repeats / (length - 1)
610 else:
611 repeat_ratio = 0
612
613 return {
614 "domain": domain,
615 "length": length,
616 "entropy": round(entropy, 4),
617 "digit_ratio": round(digit_ratio, 4),
618 "vowel_ratio": round(vowel_ratio, 4),
619 "consonant_ratio": round(consonant_ratio, 4),
620 "max_consonant_run": max_consonant_run,
621 "distinct_chars": distinct_chars,
622 "distinct_ratio": round(distinct_ratio, 4),
623 "english_bigram_score": round(english_score, 6),
624 "label_count": label_count,
625 "hex_ratio": round(hex_ratio, 4),
626 "transition_ratio": round(transition_ratio, 4),
627 "repeat_ratio": round(repeat_ratio, 4),
628 "special_count": special_count,
629 }
630
631
632FEATURE_COLUMNS = [
633 "length", "entropy", "digit_ratio", "vowel_ratio", "consonant_ratio",
634 "max_consonant_run", "distinct_chars", "distinct_ratio",
635 "english_bigram_score", "label_count", "hex_ratio",
636 "transition_ratio", "repeat_ratio", "special_count",
637]
638
639
640def features_to_vector(features):
641 """Convert feature dict to numpy array."""
642 return np.array([features[col] for col in FEATURE_COLUMNS])
643
644
645def train_dga_classifier(legitimate_domains, dga_domains, model_type="random_forest"):
646 """
647 Train a DGA classifier on labeled domain lists.
648
649 Args:
650 legitimate_domains: list of known-good domain strings
651 dga_domains: list of known DGA domain strings
652 model_type: 'random_forest' or 'gradient_boosting'
653
654 Returns:
655 trained model, scaler, and evaluation metrics
656 """
657 if not HAS_SKLEARN:
658 print("[ERROR] scikit-learn required: pip install scikit-learn")
659 return None, None, None
660
661 # Extract features
662 X_legit = []
663 X_dga = []
664
665 for d in legitimate_domains:
666 feats = extract_domain_features(d)
667 if feats:
668 X_legit.append(features_to_vector(feats))
669
670 for d in dga_domains:
671 feats = extract_domain_features(d)
672 if feats:
673 X_dga.append(features_to_vector(feats))
674
675 if not X_legit or not X_dga:
676 print("[ERROR] Insufficient feature data")
677 return None, None, None
678
679 X = np.vstack([np.array(X_legit), np.array(X_dga)])
680 y = np.array([0] * len(X_legit) + [1] * len(X_dga))
681
682 # Scale features
683 scaler = StandardScaler()
684 X_scaled = scaler.fit_transform(X)
685
686 # Train/test split
687 X_train, X_test, y_train, y_test = train_test_split(
688 X_scaled, y, test_size=0.2, random_state=42, stratify=y
689 )
690
691 # Train model
692 if model_type == "gradient_boosting":
693 model = GradientBoostingClassifier(
694 n_estimators=200, max_depth=6, learning_rate=0.1,
695 min_samples_split=10, random_state=42,
696 )
697 else:
698 model = RandomForestClassifier(
699 n_estimators=200, max_depth=15, min_samples_split=5,
700 random_state=42, n_jobs=-1,
701 )
702
703 model.fit(X_train, y_train)
704
705 # Evaluate
706 y_pred = model.predict(X_test)
707 report = classification_report(y_test, y_pred, target_names=["legitimate", "dga"],
708 output_dict=True)
709 cm = confusion_matrix(y_test, y_pred)
710
711 # Cross-validation
712 cv_scores = cross_val_score(model, X_scaled, y, cv=5, scoring="f1")
713
714 metrics = {
715 "accuracy": report["accuracy"],
716 "precision_dga": report["dga"]["precision"],
717 "recall_dga": report["dga"]["recall"],
718 "f1_dga": report["dga"]["f1-score"],
719 "precision_legit": report["legitimate"]["precision"],
720 "recall_legit": report["legitimate"]["recall"],
721 "confusion_matrix": cm.tolist(),
722 "cv_f1_mean": cv_scores.mean(),
723 "cv_f1_std": cv_scores.std(),
724 "feature_importance": dict(zip(
725 FEATURE_COLUMNS,
726 [round(float(x), 4) for x in model.feature_importances_]
727 )),
728 }
729
730 print(f"[+] Model trained: {model_type}")
731 print(f" Accuracy: {metrics['accuracy']:.4f}")
732 print(f" DGA F1: {metrics['f1_dga']:.4f}")
733 print(f" DGA Recall: {metrics['recall_dga']:.4f}")
734 print(f" CV F1 (5-fold): {metrics['cv_f1_mean']:.4f} +/- {metrics['cv_f1_std']:.4f}")
735 print(f" Top features: ", end="")
736 top_feats = sorted(metrics["feature_importance"].items(), key=lambda x: x[1], reverse=True)[:5]
737 print(", ".join(f"{k}={v:.3f}" for k, v in top_feats))
738
739 return model, scaler, metrics
740
741
742def classify_domains(domains, model, scaler):
743 """Classify a list of domains as legitimate or DGA using a trained model."""
744 results = []
745 for domain in domains:
746 feats = extract_domain_features(domain)
747 if feats is None:
748 continue
749
750 vec = features_to_vector(feats).reshape(1, -1)
751 vec_scaled = scaler.transform(vec)
752
753 prediction = model.predict(vec_scaled)[0]
754 probability = model.predict_proba(vec_scaled)[0]
755
756 results.append({
757 "domain": domain,
758 "prediction": "dga" if prediction == 1 else "legitimate",
759 "confidence": round(float(max(probability)), 4),
760 "dga_probability": round(float(probability[1]), 4),
761 "features": feats,
762 })
763
764 return results
765```
766
767### Step 5: DNS Beaconing Pattern Detection
768
769Identify periodic DNS query patterns indicative of C2 check-ins:
770
771```python
772#!/usr/bin/env python3
773"""DNS beaconing detection - identifies periodic C2 check-in patterns."""
774
775import math
776from collections import defaultdict
777from datetime import datetime, timedelta
778
779import numpy as np
780
781
782def parse_timestamp(ts_str):
783 """Parse various timestamp formats to datetime."""
784 formats = [
785 "%Y-%m-%dT%H:%M:%S.%fZ",
786 "%Y-%m-%dT%H:%M:%S.%f",
787 "%Y-%m-%dT%H:%M:%S",
788 "%Y-%m-%d %H:%M:%S.%f",
789 "%Y-%m-%d %H:%M:%S",
790 ]
791 for fmt in formats:
792 try:
793 return datetime.strptime(ts_str, fmt)
794 except ValueError:
795 continue
796
797 # Try epoch timestamp
798 try:
799 ts_float = float(ts_str)
800 return datetime.utcfromtimestamp(ts_float)
801 except (ValueError, OverflowError, OSError):
802 pass
803
804 return None
805
806
807def detect_beaconing(dns_queries, min_queries=10, max_jitter_pct=25,
808 min_interval_sec=10, max_interval_sec=7200):
809 """
810 Detect DNS beaconing by analyzing inter-query timing intervals.
811
812 Beaconing indicators:
813 - Regular inter-query intervals (low standard deviation)
814 - Consistent query sizes
815 - Single source IP to single domain over extended period
816 - Low jitter (variation in timing)
817
818 Args:
819 dns_queries: list of dicts with 'src_ip', 'query', 'timestamp'
820 min_queries: minimum queries to analyze (default 10)
821 max_jitter_pct: maximum coefficient of variation for beacon (default 25%)
822 min_interval_sec: minimum beacon interval to detect (default 10s)
823 max_interval_sec: maximum beacon interval to detect (default 7200s / 2hr)
824
825 Returns:
826 list of detected beacon patterns with confidence scores
827 """
828 # Group queries by (source IP, base domain)
829 groups = defaultdict(list)
830
831 for q in dns_queries:
832 src_ip = q.get("src_ip", "")
833 fqdn = q.get("query", "").lower().rstrip(".")
834 ts_str = q.get("timestamp", "")
835
836 ts = parse_timestamp(ts_str)
837 if not ts or not src_ip or not fqdn:
838 continue
839
840 # Extract base domain (last 2 labels)
841 parts = fqdn.split(".")
842 if len(parts) >= 2:
843 base_domain = ".".join(parts[-2:])
844 else:
845 base_domain = fqdn
846
847 groups[(src_ip, base_domain)].append(ts)
848
849 beacons = []
850
851 for (src_ip, base_domain), timestamps in groups.items():
852 if len(timestamps) < min_queries:
853 continue
854
855 # Sort timestamps and compute intervals
856 timestamps.sort()
857 intervals = [
858 (timestamps[i+1] - timestamps[i]).total_seconds()
859 for i in range(len(timestamps) - 1)
860 ]
861
862 if not intervals:
863 continue
864
865 intervals = np.array(intervals)
866
867 # Filter out zero intervals (duplicate timestamps)
868 intervals = intervals[intervals > 0]
869 if len(intervals) < min_queries - 1:
870 continue
871
872 mean_interval = np.mean(intervals)
873 std_interval = np.std(intervals)
874 median_interval = np.median(intervals)
875
876 # Skip if interval is outside detection range
877 if mean_interval < min_interval_sec or mean_interval > max_interval_sec:
878 continue
879
880 # Coefficient of variation (jitter)
881 cv = (std_interval / mean_interval * 100) if mean_interval > 0 else 100
882
883 # Time span of activity
884 time_span = (timestamps[-1] - timestamps[0]).total_seconds()
885 hours_active = time_span / 3600
886
887 # Beacon scoring
888 score = 0.0
889 flags = []
890
891 # Low jitter = strong beacon indicator
892 if cv < 5:
893 score += 40
894 flags.append(f"very_low_jitter:CV={cv:.1f}%")
895 elif cv < 15:
896 score += 30
897 flags.append(f"low_jitter:CV={cv:.1f}%")
898 elif cv < max_jitter_pct:
899 score += 15
900 flags.append(f"moderate_jitter:CV={cv:.1f}%")
901 else:
902 continue # Too much jitter, not a beacon
903
904 # Long duration increases confidence
905 if hours_active > 24:
906 score += 20
907 flags.append(f"persistent:{hours_active:.1f}h")
908 elif hours_active > 4:
909 score += 10
910 flags.append(f"sustained:{hours_active:.1f}h")
911
912 # High query count increases confidence
913 if len(timestamps) > 100:
914 score += 15
915 flags.append(f"high_volume:{len(timestamps)}")
916 elif len(timestamps) > 50:
917 score += 10
918 flags.append(f"moderate_volume:{len(timestamps)}")
919
920 # Common C2 intervals (60s, 120s, 300s, 600s, 900s, 1800s, 3600s)
921 common_intervals = [60, 120, 300, 600, 900, 1800, 3600]
922 for ci in common_intervals:
923 if abs(mean_interval - ci) < ci * 0.1: # Within 10% of common interval
924 score += 10
925 flags.append(f"common_c2_interval:~{ci}s")
926 break
927
928 beacons.append({
929 "src_ip": src_ip,
930 "base_domain": base_domain,
931 "query_count": len(timestamps),
932 "mean_interval_sec": round(mean_interval, 2),
933 "median_interval_sec": round(median_interval, 2),
934 "std_interval_sec": round(std_interval, 2),
935 "jitter_cv_pct": round(cv, 2),
936 "first_seen": timestamps[0].isoformat(),
937 "last_seen": timestamps[-1].isoformat(),
938 "duration_hours": round(hours_active, 2),
939 "score": round(score, 1),
940 "flags": flags,
941 })
942
943 beacons.sort(key=lambda x: x["score"], reverse=True)
944 return beacons
945
946
947def print_beacon_report(beacons, top_n=20):
948 """Print formatted beacon detection report."""
949 print("=" * 80)
950 print(" DNS BEACONING DETECTION REPORT")
951 print("=" * 80)
952 print(f" Beacon patterns detected: {len(beacons)}")
953 print()
954
955 if not beacons:
956 print(" No beaconing patterns detected.")
957 return
958
959 print(f" TOP {min(top_n, len(beacons))} BEACON CANDIDATES")
960 print(" " + "-" * 76)
961
962 for b in beacons[:top_n]:
963 print(f" Score: {b['score']:.1f} | {b['src_ip']} -> {b['base_domain']}")
964 print(f" Queries: {b['query_count']} "
965 f"Interval: {b['mean_interval_sec']:.1f}s +/- {b['std_interval_sec']:.1f}s "
966 f"Jitter: {b['jitter_cv_pct']:.1f}%")
967 print(f" Active: {b['duration_hours']:.1f}h "
968 f"({b['first_seen']} to {b['last_seen']})")
969 print(f" Flags: {', '.join(b['flags'])}")
970 print()
971```
972
973### Step 6: Integrated DNS C2 Detection Pipeline
974
975Combine all detection methods into a unified analysis:
976
977```
978DNS C2 Detection Pipeline Architecture:
979━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
980
981 ┌────────────────────────────────────────────────────────┐
982 │ DATA SOURCES │
983 │ Zeek dns.log | Suricata EVE | Recursive Resolver │
984 │ Passive DNS | PCAP capture | EDR DNS telemetry │
985 └───────────────────────┬────────────────────────────────┘
986 │
987 ┌───────────────────────▼────────────────────────────────┐
988 │ PREPROCESSING │
989 │ Parse timestamps | Extract subdomains | Normalize │
990 │ FQDN | Resolve base domain | Lookup in whitelist │
991 └───────────────────────┬────────────────────────────────┘
992 │
993 ┌───────────────┼───────────────┐
994 │ │ │
995 ┌───────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
996 │ ENTROPY │ │ BEACONING │ │ DGA │
997 │ ANALYSIS │ │ DETECTION │ │ CLASSIFIER │
998 │ │ │ │ │ │
999 │ Shannon ent. │ │ Interval │ │ ML model │
1000 │ Subdomain │ │ analysis │ │ Random │
1001 │ length │ │ Jitter/CV │ │ Forest or │
1002 │ Encoding │ │ Duration │ │ Gradient │
1003 │ patterns │ │ Periodicity │ │ Boosting │
1004 └───────┬──────┘ └──────┬──────┘ └──────┬──────┘
1005 │ │ │
1006 ┌───────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
1007 │ TXT RECORD │ │ TOOL │ │ PASSIVE │
1008 │ PAYLOAD │ │ SIGNATURE │ │ DNS │
1009 │ ANALYSIS │ │ MATCHING │ │ ENRICHMENT │
1010 │ │ │ │ │ │
1011 │ Base64 decode│ │ Iodine │ │ First seen │
1012 │ PE/ELF detect│ │ dnscat2 │ │ Registrar │
1013 │ PS stager │ │ dns2tcp │ │ Age check │
1014 │ Size anomaly │ │ Cobalt DNS │ │ Reputation │
1015 └───────┬──────┘ └──────┬──────┘ └──────┬──────┘
1016 │ │ │
1017 ┌───────▼───────────────▼───────────────▼────────────────┐
1018 │ CORRELATION ENGINE │
1019 │ Combine scores from all detectors │
1020 │ Weighted scoring: entropy(30%) + beacon(25%) + │
1021 │ DGA(20%) + TXT payload(15%) + signature(10%) │
1022 │ Threshold: score > 60 = alert, > 40 = investigate │
1023 └───────────────────────┬────────────────────────────────┘
1024 │
1025 ┌───────────────────────▼────────────────────────────────┐
1026 │ ALERTING & RESPONSE │
1027 │ Generate SIEM alert with all evidence │
1028 │ Block domain in DNS firewall / RPZ │
1029 │ Isolate endpoint via EDR │
1030 │ Create incident ticket with IOCs │
1031 └────────────────────────────────────────────────────────┘
1032```
1033
1034### Step 7: SIEM Detection Rules
1035
1036Deploy detection queries in your SIEM platform:
1037
1038```
1039Splunk SPL - DNS Tunneling Detection:
1040━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1041
1042-- High entropy subdomain queries
1043index=dns sourcetype="bro:dns:json" OR sourcetype="suricata:dns"
1044| eval subdomain=mvindex(split(query,"."),0)
1045| eval sub_len=len(subdomain)
1046| where sub_len > 30
1047| eval char_counts=mvmap(split(subdomain,""),1)
1048| lookup dns_entropy_lookup subdomain OUTPUT entropy
1049| where entropy > 3.5
1050| stats count as query_count dc(query) as unique_queries
1051 avg(sub_len) as avg_sub_len values(query) as sample_queries
1052 by src_ip, domain
1053| where query_count > 20
1054| sort -query_count
1055
1056-- DNS TXT record abuse
1057index=dns (qtype="TXT" OR qtype_name="TXT")
1058 NOT (query="*._domainkey.*" OR query="*._dmarc.*" OR query="*._spf.*")
1059| stats count as txt_queries dc(query) as unique_txt_queries
1060 values(query) as domains
1061 by src_ip
1062| where txt_queries > 50
1063| sort -txt_queries
1064
1065-- DNS beaconing (regular interval queries)
1066index=dns sourcetype="bro:dns:json"
1067| bin _time span=60s
1068| stats count by src_ip, query, _time
1069| streamstats window=10 current=t avg(count) as avg_count stdev(count) as std_count by src_ip, query
1070| eval cv = if(avg_count>0, (std_count/avg_count)*100, 100)
1071| where cv < 20 AND avg_count > 0
1072| stats count as beacon_windows avg(cv) as avg_jitter
1073 min(_time) as first_seen max(_time) as last_seen
1074 by src_ip, query
1075| where beacon_windows > 10
1076| sort -beacon_windows
1077
1078-- Unusual record type volume (NULL, KEY, SRV for tunneling)
1079index=dns (qtype_name="NULL" OR qtype_name="KEY" OR qtype_name="SRV"
1080 OR qtype_name="CNAME" OR qtype_name="MX")
1081 NOT qtype_name="A" NOT qtype_name="AAAA" NOT qtype_name="PTR"
1082| stats count by src_ip, qtype_name, query
1083| where count > 10
1084| sort -count
1085```
1086
1087```
1088Elastic KQL - DNS C2 Detection:
1089━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1090
1091-- Long subdomain queries (potential tunneling)
1092dns.question.name: * and not dns.question.name: *.in-addr.arpa
1093| where length(dns.question.subdomain) > 40
1094
1095-- High volume DNS to single domain
1096event.dataset: "zeek.dns" or event.dataset: "suricata.dns"
1097| stats count by source.ip, dns.question.registered_domain
1098| where count > 500
1099
1100-- TXT record queries to non-standard domains
1101dns.question.type: "TXT"
1102 and not dns.question.name: (*._domainkey.* or *._dmarc.* or *._spf.*)
1103```
1104
1105```
1106Zeek Script - DNS Tunneling Indicator:
1107━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1108
1109# dns_tunnel_detect.zeek
1110@load base/protocols/dns
1111
1112module DNSTunnel;
1113
1114export {
1115 redef enum Notice::Type += {
1116 DNS_Tunneling_Suspected,
1117 DNS_High_Entropy_Query,
1118 DNS_Excessive_TXT_Queries,
1119 };
1120
1121 const entropy_threshold = 3.5 &redef;
1122 const subdomain_length_threshold = 40 &redef;
1123 const txt_query_threshold = 50 &redef;
1124 const tracking_interval = 5min &redef;
1125}
1126
1127global txt_query_tracker: table[addr] of count &create_expire=5min &default=0;
1128global domain_query_tracker: table[addr, string] of count &create_expire=10min &default=0;
1129
1130function shannon_entropy(s: string): double
1131{
1132 local counts: table[string] of count;
1133 local total = |s|;
1134
1135 if (total == 0) return 0.0;
1136
1137 for (i in s)
1138 {
1139 local c = s[i];
1140 if (c !in counts) counts[c] = 0;
1141 ++counts[c];
1142 }
1143
1144 local ent = 0.0;
1145 for (ch, cnt in counts)
1146 {
1147 local p = cnt * 1.0 / total;
1148 ent -= p * log2(p);
1149 }
1150
1151 return ent;
1152}
1153
1154event dns_request(c: connection, msg: dns_msg, query: string, qtype: count,
1155 qclass: count)
1156{
1157 if (|query| == 0) return;
1158
1159 # Track TXT queries
1160 if (qtype == 16) # TXT
1161 {
1162 ++txt_query_tracker[c$id$orig_h];
1163 if (txt_query_tracker[c$id$orig_h] == txt_query_threshold)
1164 {
1165 NOTICE([
1166 $note=DNS_Excessive_TXT_Queries,
1167 $conn=c,
1168 $msg=fmt("Host %s made %d TXT queries in tracking window",
1169 c$id$orig_h, txt_query_threshold),
1170 $identifier=cat(c$id$orig_h),
1171 ]);
1172 }
1173 }
1174
1175 # Extract subdomain and check entropy
1176 local parts = split_string(query, /\./);
1177 if (|parts| < 3) return;
1178
1179 # Subdomain = everything except last two labels
1180 local subdomain = "";
1181 local i = 0;
1182 for (idx in parts)
1183 {
1184 if (i < |parts| - 2)
1185 subdomain += parts[idx];
1186 ++i;
1187 }
1188
1189 if (|subdomain| > subdomain_length_threshold)
1190 {
1191 local ent = shannon_entropy(subdomain);
1192 if (ent > entropy_threshold)
1193 {
1194 NOTICE([
1195 $note=DNS_High_Entropy_Query,
1196 $conn=c,
1197 $msg=fmt("High entropy DNS query: entropy=%.2f len=%d query=%s",
1198 ent, |subdomain|, query),
1199 $identifier=cat(c$id$orig_h, query),
1200 ]);
1201 }
1202 }
1203}
1204```
1205
1206### Step 8: Suricata Rules for Known DNS C2 Tools
1207
1208```
1209# suricata-dns-c2.rules
1210# DNS Tunneling and C2 Detection Rules
1211
1212# Iodine DNS tunnel detection
1213alert dns any any -> any any (msg:"ET TROJAN Iodine DNS Tunnel Activity - NULL Query"; \
1214 dns.query; content:"."; pcre:"/^[a-z0-9]{50,}\.[a-z0-9.-]+$/i"; \
1215 dns_query; content:"|00 0a|"; \
1216 classtype:trojan-activity; sid:2030001; rev:1;)
1217
1218# dnscat2 DNS tunnel detection
1219alert dns any any -> any any (msg:"ET TROJAN dnscat2 DNS Tunnel - Handshake"; \
1220 dns.query; content:"dnscat."; nocase; fast_pattern; \
1221 classtype:trojan-activity; sid:2030002; rev:1;)
1222
1223alert dns any any -> any any (msg:"ET TROJAN dnscat2 DNS Tunnel - Data Channel"; \
1224 dns.query; pcre:"/^[a-f0-9]{16,}\./i"; \
1225 dns_query; content:"|00 10|"; \
1226 classtype:trojan-activity; sid:2030003; rev:1;)
1227
1228# Cobalt Strike DNS beacon
1229alert dns any any -> any any (msg:"ET TROJAN Cobalt Strike DNS Beacon - A Record"; \
1230 dns.query; pcre:"/^[a-f0-9]{12,}\.[a-z0-9.-]+$/i"; \
1231 threshold:type both, track by_src, count 20, seconds 60; \
1232 classtype:trojan-activity; sid:2030004; rev:1;)
1233
1234# Generic DNS tunneling - high volume TXT queries to single domain
1235alert dns any any -> any any (msg:"ET POLICY Excessive TXT DNS Queries - Possible Tunneling"; \
1236 dns_query; content:"|00 10|"; \
1237 threshold:type threshold, track by_src, count 50, seconds 300; \
1238 classtype:policy-violation; sid:2030005; rev:1;)
1239
1240# Long subdomain query (generic tunneling indicator)
1241alert dns any any -> any any (msg:"ET POLICY Unusually Long DNS Subdomain - Possible Tunneling"; \
1242 dns.query; pcre:"/^[a-z0-9-]{52,}\./i"; \
1243 threshold:type limit, track by_src, count 1, seconds 60; \
1244 classtype:policy-violation; sid:2030006; rev:1;)
1245
1246# DNS query for known C2 TXT payload staging
1247alert dns any any -> any any (msg:"ET TROJAN DNS TXT Record Staged Payload Request"; \
1248 dns_query; content:"|00 10|"; \
1249 dns.query; pcre:"/^(stage|payload|cmd|exec|download|update|config)\d*\./i"; \
1250 classtype:trojan-activity; sid:2030007; rev:1;)
1251```
1252
1253## Key Concepts
1254
1255| Term | Definition |
1256|------|------------|
1257| **DNS Tunneling** | Technique of encoding data within DNS queries and responses to create a covert communication channel, bypassing firewalls that allow DNS traffic |
1258| **Shannon Entropy** | Information theory metric measuring randomness in a string; legitimate domains typically have entropy below 3.5, while encoded tunnel data exceeds 3.8-4.5 |
1259| **Domain Generation Algorithm (DGA)** | Malware technique that algorithmically generates thousands of pseudo-random domain names for C2 rendezvous, making domain-based blocking impractical |
1260| **DNS Beaconing** | Regular, periodic DNS queries from a compromised host to a C2 domain, identifiable by consistent inter-query intervals and low timing jitter |
1261| **TXT Record Abuse** | Using DNS TXT records to deliver encoded C2 commands or staged payloads, exploiting the large payload capacity (up to 65535 bytes across multiple strings) |
1262| **Iodine** | Open-source DNS tunneling tool that tunnels IPv4 traffic through DNS using NULL, TXT, or CNAME records, commonly used to bypass captive portals |
1263| **dnscat2** | Encrypted C2 tool that creates a command channel over DNS, supporting file transfer, port forwarding, and shell access through DNS queries |
1264| **Cobalt Strike DNS Beacon** | Commercial C2 framework's DNS communication mode that uses A, AAAA, and TXT records to receive tasks and return results via DNS resolution |
1265| **Passive DNS (pDNS)** | Database of historical DNS resolution data collected by monitoring DNS traffic; used to identify infrastructure reuse and domain history |
1266| **Response Policy Zone (RPZ)** | DNS firewall mechanism that allows real-time blocking of malicious domains by injecting override responses at the recursive resolver level |
1267| **Coefficient of Variation** | Standard deviation divided by mean, expressed as percentage; used to measure beacon jitter -- lower CV indicates more regular (suspicious) timing |
1268| **NXDOMAIN** | DNS response code indicating the queried domain does not exist; high NXDOMAIN rates from a host suggest DGA activity where most generated domains are unregistered |
1269
1270## Tools & Systems
1271
1272- **Zeek (Bro)**: Network security monitor that produces structured dns.log with query/response details for offline analysis
1273- **Suricata**: IDS/IPS with DNS protocol parsing and signature-based detection of tunneling patterns
1274- **tshark/Wireshark**: Packet capture and analysis tools for deep DNS protocol inspection
1275- **tldextract**: Python library for accurate domain/subdomain extraction using the Public Suffix List
1276- **dnspython**: Python DNS toolkit for programmatic query resolution and record parsing
1277- **scikit-learn**: ML library used to train DGA classifiers (Random Forest, Gradient Boosting)
1278- **Farsight DNSDB / CIRCL pDNS**: Passive DNS databases for historical domain resolution lookups
1279- **DNS Response Policy Zone (RPZ)**: Recursive resolver feature for real-time DNS blocking of identified C2 domains
1280- **Splunk / Elastic**: SIEM platforms for DNS log aggregation, entropy calculation, and beacon detection queries
1281
1282## Common Scenarios
1283
1284### Scenario: Investigating Suspected DNS Tunneling from an Internal Host
1285
1286**Context**: The SOC receives an alert from the DNS firewall showing a single internal host (10.1.5.42) making 15,000+ DNS queries to the domain `c8a3f1e2.tunnelsvc.example.com` in the past hour. All queries are TXT type with long, random-looking subdomains. Normal DNS volume for this host is ~200 queries/hour.
1287
1288**Approach**:
12891. Extract all DNS queries from 10.1.5.42 for the past 24 hours from Zeek dns.log
12902. Run entropy analysis on subdomain strings -- expect Shannon entropy > 4.0 for encoded tunnel data
12913. Check query timing intervals for beaconing pattern (likely sub-second for active tunnel)
12924. Examine TXT record responses for size anomalies (tunnel tools use maximum-size TXT responses)
12935. Compare subdomain patterns against known tool signatures (Iodine, dnscat2, dns2tcp)
12946. Query passive DNS for `tunnelsvc.example.com` registration date, nameserver, and historical resolutions
12957. If confirmed, add domain to DNS RPZ blocklist and isolate endpoint via EDR
12968. Capture full packet trace for forensic analysis of tunnel payload content
1297
1298**Pitfalls**:
1299- Blocking the domain before capturing evidence (need packet captures for forensics)
1300- Assuming all high-entropy DNS is malicious (CDN subdomains like Akamai can have high entropy)
1301- Not checking for multiple tunnel domains (attacker may have fallback C2 channels)
1302- Missing the initial compromise vector by focusing only on the DNS channel
1303- Not checking other hosts for similar patterns (lateral movement may have already occurred)
1304
1305### Scenario: Building a DGA Detection Model for SOC Deployment
1306
1307**Context**: The threat intelligence team identified that a botnet family active in the industry uses DGA for C2 domain generation. The SOC needs an automated way to classify DNS queries as potentially DGA-generated and alert on matches.
1308
1309**Approach**:
13101. Collect training data: Tranco/Alexa top 1M for legitimate domains, DGArchive or OSINT feeds for known DGA domains
13112. Extract character-level features: entropy, length, digit ratio, consonant sequences, bigram scores
13123. Train Random Forest and Gradient Boosting classifiers, evaluate with 5-fold cross-validation
13134. Deploy the model as a scoring enrichment in the SIEM (Splunk ML Toolkit or Elastic ML)
13145. Set threshold: DGA probability > 0.85 generates alert, > 0.65 generates investigation ticket
13156. Create a whitelist of known high-entropy legitimate domains (CDNs, cloud services) to reduce false positives
13167. Retrain monthly with new DGA samples from threat intel feeds
1317
1318**Pitfalls**:
1319- Training only on one DGA family and missing others (dictionary-based DGAs like Suppobox have low entropy)
1320- Not whitelisting CDN and cloud service domains that have randomized subdomains
1321- Setting the threshold too low, overwhelming the SOC with false positives
1322- Not accounting for punycode/internationalized domain names in feature extraction
1323- Deploying without a feedback loop for analysts to flag false positives for model retraining
1324
1325## Output Format
1326
1327```
1328DNS C2 DETECTION ANALYSIS REPORT
1329====================================
1330Analysis Period: 2026-03-15 00:00 to 2026-03-19 23:59
1331Data Source: Zeek dns.log (gateway sensor)
1332Total Queries: 14,283,501
1333Unique Domains: 892,041
1334Hosts Analyzed: 3,847
1335
1336ENTROPY ANALYSIS
1337Queries with entropy > 3.5: 2,847 (0.02%)
1338Queries with subdomain > 40 chars: 1,203 (0.008%)
1339Suspicious base domains: 12
1340
1341 [CRITICAL] tunnelsvc.example[.]com
1342 Queries: 15,247 Source: 10.1.5.42 Avg Entropy: 4.21
1343 Avg Subdomain Length: 63 Record Types: TXT (98%), A (2%)
1344 Tool Signature: dnscat2 (hex prefix pattern match)
1345
1346 [HIGH] update-cdn.malicious[.]net
1347 Queries: 3,891 Source: 10.1.12.7 Avg Entropy: 3.87
1348 Avg Subdomain Length: 48 Record Types: A (60%), TXT (40%)
1349 Tool Signature: Cobalt Strike DNS beacon (interval pattern)
1350
1351BEACONING DETECTION
1352Beacon patterns detected: 4
1353
1354 Score: 85.0 10.1.5.42 -> tunnelsvc.example[.]com
1355 Interval: 0.5s +/- 0.1s Jitter: 8.2% Duration: 18.4h
1356 Queries: 15,247 Flags: very_low_jitter, persistent, high_volume
1357
1358 Score: 72.0 10.1.12.7 -> update-cdn.malicious[.]net
1359 Interval: 60.2s +/- 3.1s Jitter: 5.1% Duration: 72.1h
1360 Queries: 3,891 Flags: very_low_jitter, persistent, common_c2_interval:~60s
1361
1362DGA CLASSIFICATION
1363Domains classified: 892,041
1364DGA predictions (>0.85 conf): 47
1365DGA predictions (0.65-0.85): 183
1366
1367 [HIGH] a8f3k2m1x9.com (DGA prob: 0.97, entropy: 3.92)
1368 [HIGH] j7t2p5q8w3.net (DGA prob: 0.95, entropy: 4.01)
1369 [HIGH] m3x8k1f6y2.org (DGA prob: 0.94, entropy: 3.88)
1370
1371TXT RECORD ANALYSIS
1372Suspicious TXT responses: 8
1373Base64 payloads detected: 3
1374PowerShell stager patterns: 1
1375
1376 [CRITICAL] cmd.staging[.]example.com
1377 TXT Length: 4,096 Entropy: 5.82
1378 Finding: Base64-encoded PowerShell stager with IEX pattern
1379
1380RECOMMENDED ACTIONS
1381[CRITICAL] Block tunnelsvc.example[.]com and update-cdn.malicious[.]net in DNS RPZ
1382[CRITICAL] Isolate hosts 10.1.5.42 and 10.1.12.7 for forensic investigation
1383[HIGH] Block 47 high-confidence DGA domains in DNS firewall
1384[HIGH] Investigate cmd.staging[.]example.com TXT payload staging
1385[MEDIUM] Review 183 moderate-confidence DGA domains with threat intel
1386[MEDIUM] Deploy Suricata rules for dnscat2 and Cobalt Strike DNS signatures
1387```