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