[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GXH2GTNE1RWEWTH1DYME9Q":3,"skill-same:01M6GXH2GTNE1RWEWTH1DYME9Q":90},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":6,"ownerHtmlUrl":57,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":58,"install":59,"resources":72},"01M6GXH2GTNE1RWEWTH1DYME9Q","detecting-dns-exfiltration-with-dns-query-analysis",null,"Detect data exfiltration through DNS tunneling by analyzing query entropy, subdomain length, query volume, TXT record abuse, and response payload sizes using passive DNS monitoring.","micsapp\u002Fmicstec-skills","micsapp","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F82411001?v=4","01M6GWCFQ6D3PV8EHNY62NN5VW","01M6GWCFVE1PA5HG0DKC7AMFJ3",4,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"detecting dns exfiltration with dns query analysis","detecting","with","dns query","query","analysis","exfiltration","dns","data-exfiltration","analyzing","network","network-monitoring","cybersecurity","entropy","threat-detection","subdomain","payload","dns-tunneling","volume","monitoring","2026-11-10 10:12:30",false,"---\nname: detecting-dns-exfiltration-with-dns-query-analysis\ndescription: Detect data exfiltration through DNS tunneling by analyzing query entropy, subdomain length, query volume, TXT record abuse, and response payload sizes using passive DNS monitoring.\ndomain: cybersecurity\nsubdomain: network-security\ntags: [dns-exfiltration, dns-tunneling, data-exfiltration, threat-detection, entropy-analysis, passive-dns, network-monitoring, iodine, dnscat2]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\n---\n\n# Detecting DNS Exfiltration with DNS Query Analysis\n\n## Overview\n\nDNS exfiltration exploits the Domain Name System as a covert channel to extract data from compromised networks. Attackers encode stolen data into DNS query names (subdomains) or DNS response records (TXT, CNAME, NULL), bypassing traditional security controls that typically allow DNS traffic unrestricted. Tools like iodine, dnscat2, and dns2tcp enable full TCP tunneling over DNS. Detection requires analyzing DNS query patterns for anomalies including excessive query length, high entropy subdomain strings, abnormal query volumes to single domains, and oversized TXT record responses. This skill covers building a comprehensive DNS exfiltration detection capability using passive DNS analysis, statistical methods, and machine learning approaches.\n\n\n## When to Use\n\n- When investigating security incidents that require detecting dns exfiltration with dns query analysis\n- When building detection rules or threat hunting queries for this domain\n- When SOC analysts need structured procedures for this analysis type\n- When validating security monitoring coverage for related attack techniques\n\n## Prerequisites\n\n- Access to DNS query logs (passive DNS capture, DNS server logs, or PCAP)\n- Zeek, Suricata, or tcpdump for DNS traffic capture\n- Python 3.8+ with scipy, numpy, pandas, and scikit-learn\n- SIEM platform for alert correlation\n- Baseline of normal DNS traffic patterns for the environment\n\n## Core Concepts\n\n### DNS Tunneling Mechanics\n\nDNS exfiltration encodes data in different parts of DNS messages:\n\n**Outbound (Query-based exfiltration):**\n```\nEncoded data as subdomain labels:\ndGhlIHNlY3JldCBkYXRh.exfil.attacker.com\n[base64-encoded data].[tunnel domain]\n\nQuery types used: A, AAAA, CNAME, MX, TXT, NULL\n```\n\n**Inbound (Response-based command channel):**\n```\nTXT records carry encoded commands\u002Fdata in responses\nCNAME records chain encoded data through multiple labels\nNULL records carry arbitrary binary data\n```\n\n### Detection Indicators\n\n| Indicator | Normal DNS | DNS Tunneling |\n|-----------|-----------|---------------|\n| Subdomain length | 5-20 chars | 40-253 chars |\n| Label count | 2-4 labels | 5-10+ labels |\n| Shannon entropy | 2.5-3.5 bits | 4.0-5.5 bits |\n| Query volume (per domain) | Variable | 100s-1000s\u002Fmin |\n| TXT response size | \u003C 100 bytes | 200-4000+ bytes |\n| Unique subdomains | Low | Very high |\n| Query type distribution | Mostly A\u002FAAAA | Heavy TXT, NULL, CNAME |\n\n### Common Tunneling Tools\n\n| Tool | Protocol | Encoding | Detection Difficulty |\n|------|----------|----------|---------------------|\n| iodine | IP-over-DNS | Base32\u002FBase64\u002FRaw | Medium |\n| dnscat2 | TCP-over-DNS | Hex encoding | Medium |\n| dns2tcp | TCP-over-DNS | Base64 | Medium |\n| DNSExfiltrator | Custom | Base64 | Low |\n| Cobalt Strike DNS | C2 over DNS | Custom encoding | High |\n\n## Workflow\n\n### Step 1: Capture DNS Traffic\n\n**Using Zeek:**\n```bash\n# Live capture\nzeek -i eth0 -C base\u002Fprotocols\u002Fdns\n\n# Offline PCAP analysis\nzeek -r traffic.pcap base\u002Fprotocols\u002Fdns\n\n# Output: dns.log with query, qtype, answers, TTL\n```\n\n**Using tcpdump:**\n```bash\n# Capture all DNS traffic\ntcpdump -i eth0 -w dns_capture.pcap port 53\n\n# Capture with size filter (large DNS packets)\ntcpdump -i eth0 -w large_dns.pcap 'port 53 and greater 512'\n```\n\n**Using Suricata:**\n```yaml\n# In suricata.yaml, enable DNS logging\noutputs:\n  - eve-log:\n      types:\n        - dns:\n            query: yes\n            answer: yes\n            formats: [detailed]\n```\n\n### Step 2: Analyze Query Characteristics\n\nPython script for DNS exfiltration detection:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"DNS Exfiltration Detector - Analyzes DNS logs for tunneling indicators.\"\"\"\n\nimport json\nimport math\nimport re\nimport sys\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nimport pandas as pd\n\n\ndef calculate_entropy(domain: str) -> float:\n    \"\"\"Calculate Shannon entropy of a string.\"\"\"\n    if not domain:\n        return 0.0\n    freq = defaultdict(int)\n    for char in domain:\n        freq[char] += 1\n    length = len(domain)\n    entropy = -sum(\n        (count \u002F length) * math.log2(count \u002F length)\n        for count in freq.values()\n    )\n    return entropy\n\n\ndef extract_subdomain(query: str) -> str:\n    \"\"\"Extract subdomain portion from FQDN.\"\"\"\n    parts = query.rstrip('.').split('.')\n    if len(parts) > 2:\n        return '.'.join(parts[:-2])\n    return ''\n\n\ndef get_base_domain(query: str) -> str:\n    \"\"\"Extract registered domain from FQDN.\"\"\"\n    parts = query.rstrip('.').split('.')\n    if len(parts) >= 2:\n        return '.'.join(parts[-2:])\n    return query\n\n\ndef is_base64_like(s: str) -> bool:\n    \"\"\"Check if string resembles base64 encoding.\"\"\"\n    b64_chars = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\u002F=')\n    if len(s) \u003C 10:\n        return False\n    char_ratio = sum(1 for c in s if c in b64_chars) \u002F len(s)\n    return char_ratio > 0.9 and calculate_entropy(s) > 4.0\n\n\ndef is_hex_encoded(s: str) -> bool:\n    \"\"\"Check if string appears hex-encoded.\"\"\"\n    hex_chars = set('0123456789abcdefABCDEF')\n    if len(s) \u003C 16:\n        return False\n    clean = s.replace('.', '').replace('-', '')\n    return all(c in hex_chars for c in clean) and len(clean) % 2 == 0\n\n\nclass DNSExfiltrationDetector:\n    def __init__(self):\n        self.domain_stats = defaultdict(lambda: {\n            'query_count': 0,\n            'unique_subdomains': set(),\n            'total_subdomain_length': 0,\n            'entropy_sum': 0.0,\n            'query_types': defaultdict(int),\n            'source_ips': set(),\n            'first_seen': None,\n            'last_seen': None,\n            'txt_response_sizes': [],\n        })\n\n        # Detection thresholds\n        self.thresholds = {\n            'min_query_count': 50,\n            'min_unique_subdomains': 30,\n            'avg_subdomain_length': 30,\n            'avg_entropy': 3.8,\n            'unique_ratio': 0.7,\n            'txt_query_ratio': 0.3,\n            'max_label_length': 63,\n            'max_subdomain_labels': 5,\n        }\n\n    def process_query(self, timestamp, src_ip, query, qtype, response_size=0):\n        \"\"\"Process a single DNS query and update statistics.\"\"\"\n        base_domain = get_base_domain(query)\n        subdomain = extract_subdomain(query)\n\n        stats = self.domain_stats[base_domain]\n        stats['query_count'] += 1\n        stats['unique_subdomains'].add(subdomain)\n        stats['total_subdomain_length'] += len(subdomain)\n        stats['entropy_sum'] += calculate_entropy(subdomain)\n        stats['query_types'][qtype] += 1\n        stats['source_ips'].add(src_ip)\n\n        if stats['first_seen'] is None:\n            stats['first_seen'] = timestamp\n        stats['last_seen'] = timestamp\n\n        if qtype in ('TXT', 'NULL') and response_size > 0:\n            stats['txt_response_sizes'].append(response_size)\n\n    def analyze(self):\n        \"\"\"Analyze accumulated statistics and return suspicious domains.\"\"\"\n        alerts = []\n\n        for domain, stats in self.domain_stats.items():\n            if stats['query_count'] \u003C self.thresholds['min_query_count']:\n                continue\n\n            unique_count = len(stats['unique_subdomains'])\n            avg_length = stats['total_subdomain_length'] \u002F stats['query_count']\n            avg_entropy = stats['entropy_sum'] \u002F stats['query_count']\n            unique_ratio = unique_count \u002F stats['query_count']\n\n            txt_queries = stats['query_types'].get('TXT', 0) + stats['query_types'].get('NULL', 0)\n            txt_ratio = txt_queries \u002F stats['query_count']\n\n            score = 0\n            indicators = []\n\n            if avg_length > self.thresholds['avg_subdomain_length']:\n                score += 25\n                indicators.append(f\"high_avg_subdomain_length={avg_length:.1f}\")\n\n            if avg_entropy > self.thresholds['avg_entropy']:\n                score += 25\n                indicators.append(f\"high_entropy={avg_entropy:.2f}\")\n\n            if unique_ratio > self.thresholds['unique_ratio']:\n                score += 20\n                indicators.append(f\"high_unique_ratio={unique_ratio:.2f}\")\n\n            if txt_ratio > self.thresholds['txt_query_ratio']:\n                score += 15\n                indicators.append(f\"high_txt_ratio={txt_ratio:.2f}\")\n\n            if unique_count > self.thresholds['min_unique_subdomains']:\n                score += 15\n                indicators.append(f\"unique_subdomains={unique_count}\")\n\n            # Check for encoding patterns\n            encoded_count = sum(\n                1 for sd in list(stats['unique_subdomains'])[:100]\n                if is_base64_like(sd) or is_hex_encoded(sd)\n            )\n            if encoded_count > 20:\n                score += 20\n                indicators.append(f\"encoded_subdomains={encoded_count}\")\n\n            if score >= 50:\n                duration = (stats['last_seen'] - stats['first_seen']).total_seconds() if stats['first_seen'] and stats['last_seen'] else 0\n                alerts.append({\n                    'domain': domain,\n                    'score': min(score, 100),\n                    'query_count': stats['query_count'],\n                    'unique_subdomains': unique_count,\n                    'avg_subdomain_length': round(avg_length, 1),\n                    'avg_entropy': round(avg_entropy, 2),\n                    'unique_ratio': round(unique_ratio, 2),\n                    'txt_ratio': round(txt_ratio, 2),\n                    'source_ips': list(stats['source_ips']),\n                    'duration_seconds': duration,\n                    'indicators': indicators,\n                })\n\n        return sorted(alerts, key=lambda x: x['score'], reverse=True)\n\n    def process_zeek_dns_log(self, log_path):\n        \"\"\"Process Zeek dns.log file.\"\"\"\n        with open(log_path, 'r') as f:\n            for line in f:\n                if line.startswith('#'):\n                    continue\n                fields = line.strip().split('\\t')\n                if len(fields) \u003C 22:\n                    continue\n                try:\n                    ts = datetime.fromtimestamp(float(fields[0]))\n                    src_ip = fields[2]\n                    query = fields[9]\n                    qtype = fields[11]\n                    self.process_query(ts, src_ip, query, qtype)\n                except (ValueError, IndexError):\n                    continue\n\n    def process_eve_json(self, log_path):\n        \"\"\"Process Suricata EVE JSON DNS log.\"\"\"\n        with open(log_path, 'r') as f:\n            for line in f:\n                try:\n                    event = json.loads(line)\n                    if event.get('event_type') != 'dns':\n                        continue\n                    dns = event.get('dns', {})\n                    ts = datetime.fromisoformat(event['timestamp'].replace('Z', '+00:00'))\n                    src_ip = event.get('src_ip', '')\n                    query = dns.get('rrname', '')\n                    qtype = dns.get('rrtype', '')\n                    self.process_query(ts, src_ip, query, qtype)\n                except (json.JSONDecodeError, KeyError, ValueError):\n                    continue\n\n\ndef main():\n    detector = DNSExfiltrationDetector()\n\n    log_file = sys.argv[1] if len(sys.argv) > 1 else '\u002Fopt\u002Fzeek\u002Flogs\u002Fcurrent\u002Fdns.log'\n\n    if log_file.endswith('.json'):\n        detector.process_eve_json(log_file)\n    else:\n        detector.process_zeek_dns_log(log_file)\n\n    alerts = detector.analyze()\n\n    if alerts:\n        print(f\"\\n{'='*80}\")\n        print(f\"DNS EXFILTRATION DETECTION RESULTS - {len(alerts)} suspicious domains found\")\n        print(f\"{'='*80}\\n\")\n\n        for alert in alerts:\n            severity = \"CRITICAL\" if alert['score'] >= 80 else \"HIGH\" if alert['score'] >= 60 else \"MEDIUM\"\n            print(f\"[{severity}] Domain: {alert['domain']}\")\n            print(f\"  Score: {alert['score']}\u002F100\")\n            print(f\"  Queries: {alert['query_count']}, Unique Subdomains: {alert['unique_subdomains']}\")\n            print(f\"  Avg Subdomain Length: {alert['avg_subdomain_length']}, Avg Entropy: {alert['avg_entropy']}\")\n            print(f\"  Source IPs: {', '.join(alert['source_ips'][:5])}\")\n            print(f\"  Indicators: {', '.join(alert['indicators'])}\")\n            print()\n    else:\n        print(\"No DNS exfiltration indicators detected.\")\n\n\nif __name__ == '__main__':\n    main()\n```\n\n### Step 3: Deploy Suricata Rules for DNS Exfiltration\n\n```\n# Detect long DNS queries (potential tunneling)\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - Excessive query length\"; dns.query; content:\".\"; pcre:\"\u002F^.{60,}\u002F\"; threshold:type both,track by_src,count 20,seconds 60; classtype:bad-unknown; sid:3000001; rev:1;)\n\n# Detect high-entropy DNS subdomain\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - High entropy subdomain\"; dns.query; pcre:\"\u002F^[a-zA-Z0-9+\\\u002F=]{30,}\\.\u002F\"; threshold:type both,track by_src,count 10,seconds 60; classtype:bad-unknown; sid:3000002; rev:1;)\n\n# Detect large TXT record responses\nalert dns any 53 -> $HOME_NET any (msg:\"DNS Exfiltration - Large TXT response\"; content:\"|00 10|\"; byte_test:2,>,400,0,relative; classtype:bad-unknown; sid:3000003; rev:1;)\n\n# Detect NULL record queries (used by iodine)\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - NULL record query (iodine indicator)\"; content:\"|00 0a|\"; classtype:bad-unknown; sid:3000004; rev:1;)\n\n# Detect dnscat2 traffic pattern\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - dnscat2 indicator\"; dns.query; content:\"dnscat\"; nocase; classtype:trojan-activity; sid:3000005; rev:1;)\n```\n\n### Step 4: SIEM Detection Rules\n\n**Splunk SPL query for DNS exfiltration:**\n\n```spl\nindex=dns sourcetype=zeek:dns\n| eval subdomain=mvindex(split(query,\".\"),0)\n| eval subdomain_len=len(subdomain)\n| eval label_count=mvcount(split(query,\".\"))\n| stats count as query_count,\n        dc(subdomain) as unique_subdomains,\n        avg(subdomain_len) as avg_sub_len,\n        values(src_ip) as source_ips\n        by query_domain\n| where query_count > 100 AND avg_sub_len > 30 AND unique_subdomains > 50\n| eval risk_score = case(\n    avg_sub_len > 50 AND unique_subdomains > 200, \"Critical\",\n    avg_sub_len > 40 AND unique_subdomains > 100, \"High\",\n    avg_sub_len > 30 AND unique_subdomains > 50, \"Medium\",\n    true(), \"Low\")\n| sort -query_count\n| table query_domain risk_score query_count unique_subdomains avg_sub_len source_ips\n```\n\n## Response Actions\n\n1. **Block the tunnel domain** at DNS resolver and firewall level\n2. **Isolate the source host** from the network for forensic investigation\n3. **Capture full PCAP** of the DNS traffic for evidence preservation\n4. **Identify exfiltrated data** by decoding captured DNS queries\n5. **Check for persistence** mechanisms on the compromised host\n6. **Update blocklists** with identified C2 domains and infrastructure\n\n## Best Practices\n\n- **DNS Logging** - Enable full DNS query and response logging at resolvers and network level\n- **Internal DNS Only** - Force all DNS through internal resolvers; block direct external DNS (port 53)\n- **Response Policy Zones** - Deploy RPZ feeds to block known tunneling domains\n- **Baseline First** - Establish normal DNS query patterns before setting detection thresholds\n- **TXT Record Monitoring** - Pay special attention to TXT and NULL record queries\n- **Encrypted DNS Awareness** - Monitor for DoH\u002FDoT usage that may bypass DNS inspection\n\n## References\n\n- [Splunk DNS Exfiltration Detection with Deep Learning](https:\u002F\u002Fwww.splunk.com\u002Fen_us\u002Fblog\u002Fsecurity\u002Fmachine-learning-in-security-detect-dns-data-exfiltration-using-deep-learning.html)\n- [Akamai DNS Data Exfiltration](https:\u002F\u002Fwww.akamai.com\u002Fglossary\u002Fwhat-is-dns-data-exfiltration)\n- [SANS Detecting DNS Tunneling](https:\u002F\u002Fwww.giac.org\u002Fpaper\u002Fgcia\u002F1116\u002Fdetecting-dns-tunneling\u002F108367)\n- [Fidelis DNS Tunneling Detection](https:\u002F\u002Ffidelissecurity.com\u002Fthreatgeek\u002Flearn\u002Fdns-tunneling-detection\u002F)\n","# Detecting DNS Exfiltration with DNS Query Analysis\n\n## Overview\n\nDNS exfiltration exploits the Domain Name System as a covert channel to extract data from compromised networks. Attackers encode stolen data into DNS query names (subdomains) or DNS response records (TXT, CNAME, NULL), bypassing traditional security controls that typically allow DNS traffic unrestricted. Tools like iodine, dnscat2, and dns2tcp enable full TCP tunneling over DNS. Detection requires analyzing DNS query patterns for anomalies including excessive query length, high entropy subdomain strings, abnormal query volumes to single domains, and oversized TXT record responses. This skill covers building a comprehensive DNS exfiltration detection capability using passive DNS analysis, statistical methods, and machine learning approaches.\n\n\n## When to Use\n\n- When investigating security incidents that require detecting dns exfiltration with dns query analysis\n- When building detection rules or threat hunting queries for this domain\n- When SOC analysts need structured procedures for this analysis type\n- When validating security monitoring coverage for related attack techniques\n\n## Prerequisites\n\n- Access to DNS query logs (passive DNS capture, DNS server logs, or PCAP)\n- Zeek, Suricata, or tcpdump for DNS traffic capture\n- Python 3.8+ with scipy, numpy, pandas, and scikit-learn\n- SIEM platform for alert correlation\n- Baseline of normal DNS traffic patterns for the environment\n\n## Core Concepts\n\n### DNS Tunneling Mechanics\n\nDNS exfiltration encodes data in different parts of DNS messages:\n\n**Outbound (Query-based exfiltration):**\n```\nEncoded data as subdomain labels:\ndGhlIHNlY3JldCBkYXRh.exfil.attacker.com\n[base64-encoded data].[tunnel domain]\n\nQuery types used: A, AAAA, CNAME, MX, TXT, NULL\n```\n\n**Inbound (Response-based command channel):**\n```\nTXT records carry encoded commands\u002Fdata in responses\nCNAME records chain encoded data through multiple labels\nNULL records carry arbitrary binary data\n```\n\n### Detection Indicators\n\n| Indicator | Normal DNS | DNS Tunneling |\n|-----------|-----------|---------------|\n| Subdomain length | 5-20 chars | 40-253 chars |\n| Label count | 2-4 labels | 5-10+ labels |\n| Shannon entropy | 2.5-3.5 bits | 4.0-5.5 bits |\n| Query volume (per domain) | Variable | 100s-1000s\u002Fmin |\n| TXT response size | \u003C 100 bytes | 200-4000+ bytes |\n| Unique subdomains | Low | Very high |\n| Query type distribution | Mostly A\u002FAAAA | Heavy TXT, NULL, CNAME |\n\n### Common Tunneling Tools\n\n| Tool | Protocol | Encoding | Detection Difficulty |\n|------|----------|----------|---------------------|\n| iodine | IP-over-DNS | Base32\u002FBase64\u002FRaw | Medium |\n| dnscat2 | TCP-over-DNS | Hex encoding | Medium |\n| dns2tcp | TCP-over-DNS | Base64 | Medium |\n| DNSExfiltrator | Custom | Base64 | Low |\n| Cobalt Strike DNS | C2 over DNS | Custom encoding | High |\n\n## Workflow\n\n### Step 1: Capture DNS Traffic\n\n**Using Zeek:**\n```bash\n# Live capture\nzeek -i eth0 -C base\u002Fprotocols\u002Fdns\n\n# Offline PCAP analysis\nzeek -r traffic.pcap base\u002Fprotocols\u002Fdns\n\n# Output: dns.log with query, qtype, answers, TTL\n```\n\n**Using tcpdump:**\n```bash\n# Capture all DNS traffic\ntcpdump -i eth0 -w dns_capture.pcap port 53\n\n# Capture with size filter (large DNS packets)\ntcpdump -i eth0 -w large_dns.pcap 'port 53 and greater 512'\n```\n\n**Using Suricata:**\n```yaml\n# In suricata.yaml, enable DNS logging\noutputs:\n  - eve-log:\n      types:\n        - dns:\n            query: yes\n            answer: yes\n            formats: [detailed]\n```\n\n### Step 2: Analyze Query Characteristics\n\nPython script for DNS exfiltration detection:\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"DNS Exfiltration Detector - Analyzes DNS logs for tunneling indicators.\"\"\"\n\nimport json\nimport math\nimport re\nimport sys\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nimport pandas as pd\n\n\ndef calculate_entropy(domain: str) -> float:\n    \"\"\"Calculate Shannon entropy of a string.\"\"\"\n    if not domain:\n        return 0.0\n    freq = defaultdict(int)\n    for char in domain:\n        freq[char] += 1\n    length = len(domain)\n    entropy = -sum(\n        (count \u002F length) * math.log2(count \u002F length)\n        for count in freq.values()\n    )\n    return entropy\n\n\ndef extract_subdomain(query: str) -> str:\n    \"\"\"Extract subdomain portion from FQDN.\"\"\"\n    parts = query.rstrip('.').split('.')\n    if len(parts) > 2:\n        return '.'.join(parts[:-2])\n    return ''\n\n\ndef get_base_domain(query: str) -> str:\n    \"\"\"Extract registered domain from FQDN.\"\"\"\n    parts = query.rstrip('.').split('.')\n    if len(parts) >= 2:\n        return '.'.join(parts[-2:])\n    return query\n\n\ndef is_base64_like(s: str) -> bool:\n    \"\"\"Check if string resembles base64 encoding.\"\"\"\n    b64_chars = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\u002F=')\n    if len(s) \u003C 10:\n        return False\n    char_ratio = sum(1 for c in s if c in b64_chars) \u002F len(s)\n    return char_ratio > 0.9 and calculate_entropy(s) > 4.0\n\n\ndef is_hex_encoded(s: str) -> bool:\n    \"\"\"Check if string appears hex-encoded.\"\"\"\n    hex_chars = set('0123456789abcdefABCDEF')\n    if len(s) \u003C 16:\n        return False\n    clean = s.replace('.', '').replace('-', '')\n    return all(c in hex_chars for c in clean) and len(clean) % 2 == 0\n\n\nclass DNSExfiltrationDetector:\n    def __init__(self):\n        self.domain_stats = defaultdict(lambda: {\n            'query_count': 0,\n            'unique_subdomains': set(),\n            'total_subdomain_length': 0,\n            'entropy_sum': 0.0,\n            'query_types': defaultdict(int),\n            'source_ips': set(),\n            'first_seen': None,\n            'last_seen': None,\n            'txt_response_sizes': [],\n        })\n\n        # Detection thresholds\n        self.thresholds = {\n            'min_query_count': 50,\n            'min_unique_subdomains': 30,\n            'avg_subdomain_length': 30,\n            'avg_entropy': 3.8,\n            'unique_ratio': 0.7,\n            'txt_query_ratio': 0.3,\n            'max_label_length': 63,\n            'max_subdomain_labels': 5,\n        }\n\n    def process_query(self, timestamp, src_ip, query, qtype, response_size=0):\n        \"\"\"Process a single DNS query and update statistics.\"\"\"\n        base_domain = get_base_domain(query)\n        subdomain = extract_subdomain(query)\n\n        stats = self.domain_stats[base_domain]\n        stats['query_count'] += 1\n        stats['unique_subdomains'].add(subdomain)\n        stats['total_subdomain_length'] += len(subdomain)\n        stats['entropy_sum'] += calculate_entropy(subdomain)\n        stats['query_types'][qtype] += 1\n        stats['source_ips'].add(src_ip)\n\n        if stats['first_seen'] is None:\n            stats['first_seen'] = timestamp\n        stats['last_seen'] = timestamp\n\n        if qtype in ('TXT', 'NULL') and response_size > 0:\n            stats['txt_response_sizes'].append(response_size)\n\n    def analyze(self):\n        \"\"\"Analyze accumulated statistics and return suspicious domains.\"\"\"\n        alerts = []\n\n        for domain, stats in self.domain_stats.items():\n            if stats['query_count'] \u003C self.thresholds['min_query_count']:\n                continue\n\n            unique_count = len(stats['unique_subdomains'])\n            avg_length = stats['total_subdomain_length'] \u002F stats['query_count']\n            avg_entropy = stats['entropy_sum'] \u002F stats['query_count']\n            unique_ratio = unique_count \u002F stats['query_count']\n\n            txt_queries = stats['query_types'].get('TXT', 0) + stats['query_types'].get('NULL', 0)\n            txt_ratio = txt_queries \u002F stats['query_count']\n\n            score = 0\n            indicators = []\n\n            if avg_length > self.thresholds['avg_subdomain_length']:\n                score += 25\n                indicators.append(f\"high_avg_subdomain_length={avg_length:.1f}\")\n\n            if avg_entropy > self.thresholds['avg_entropy']:\n                score += 25\n                indicators.append(f\"high_entropy={avg_entropy:.2f}\")\n\n            if unique_ratio > self.thresholds['unique_ratio']:\n                score += 20\n                indicators.append(f\"high_unique_ratio={unique_ratio:.2f}\")\n\n            if txt_ratio > self.thresholds['txt_query_ratio']:\n                score += 15\n                indicators.append(f\"high_txt_ratio={txt_ratio:.2f}\")\n\n            if unique_count > self.thresholds['min_unique_subdomains']:\n                score += 15\n                indicators.append(f\"unique_subdomains={unique_count}\")\n\n            # Check for encoding patterns\n            encoded_count = sum(\n                1 for sd in list(stats['unique_subdomains'])[:100]\n                if is_base64_like(sd) or is_hex_encoded(sd)\n            )\n            if encoded_count > 20:\n                score += 20\n                indicators.append(f\"encoded_subdomains={encoded_count}\")\n\n            if score >= 50:\n                duration = (stats['last_seen'] - stats['first_seen']).total_seconds() if stats['first_seen'] and stats['last_seen'] else 0\n                alerts.append({\n                    'domain': domain,\n                    'score': min(score, 100),\n                    'query_count': stats['query_count'],\n                    'unique_subdomains': unique_count,\n                    'avg_subdomain_length': round(avg_length, 1),\n                    'avg_entropy': round(avg_entropy, 2),\n                    'unique_ratio': round(unique_ratio, 2),\n                    'txt_ratio': round(txt_ratio, 2),\n                    'source_ips': list(stats['source_ips']),\n                    'duration_seconds': duration,\n                    'indicators': indicators,\n                })\n\n        return sorted(alerts, key=lambda x: x['score'], reverse=True)\n\n    def process_zeek_dns_log(self, log_path):\n        \"\"\"Process Zeek dns.log file.\"\"\"\n        with open(log_path, 'r') as f:\n            for line in f:\n                if line.startswith('#'):\n                    continue\n                fields = line.strip().split('\\t')\n                if len(fields) \u003C 22:\n                    continue\n                try:\n                    ts = datetime.fromtimestamp(float(fields[0]))\n                    src_ip = fields[2]\n                    query = fields[9]\n                    qtype = fields[11]\n                    self.process_query(ts, src_ip, query, qtype)\n                except (ValueError, IndexError):\n                    continue\n\n    def process_eve_json(self, log_path):\n        \"\"\"Process Suricata EVE JSON DNS log.\"\"\"\n        with open(log_path, 'r') as f:\n            for line in f:\n                try:\n                    event = json.loads(line)\n                    if event.get('event_type') != 'dns':\n                        continue\n                    dns = event.get('dns', {})\n                    ts = datetime.fromisoformat(event['timestamp'].replace('Z', '+00:00'))\n                    src_ip = event.get('src_ip', '')\n                    query = dns.get('rrname', '')\n                    qtype = dns.get('rrtype', '')\n                    self.process_query(ts, src_ip, query, qtype)\n                except (json.JSONDecodeError, KeyError, ValueError):\n                    continue\n\n\ndef main():\n    detector = DNSExfiltrationDetector()\n\n    log_file = sys.argv[1] if len(sys.argv) > 1 else '\u002Fopt\u002Fzeek\u002Flogs\u002Fcurrent\u002Fdns.log'\n\n    if log_file.endswith('.json'):\n        detector.process_eve_json(log_file)\n    else:\n        detector.process_zeek_dns_log(log_file)\n\n    alerts = detector.analyze()\n\n    if alerts:\n        print(f\"\\n{'='*80}\")\n        print(f\"DNS EXFILTRATION DETECTION RESULTS - {len(alerts)} suspicious domains found\")\n        print(f\"{'='*80}\\n\")\n\n        for alert in alerts:\n            severity = \"CRITICAL\" if alert['score'] >= 80 else \"HIGH\" if alert['score'] >= 60 else \"MEDIUM\"\n            print(f\"[{severity}] Domain: {alert['domain']}\")\n            print(f\"  Score: {alert['score']}\u002F100\")\n            print(f\"  Queries: {alert['query_count']}, Unique Subdomains: {alert['unique_subdomains']}\")\n            print(f\"  Avg Subdomain Length: {alert['avg_subdomain_length']}, Avg Entropy: {alert['avg_entropy']}\")\n            print(f\"  Source IPs: {', '.join(alert['source_ips'][:5])}\")\n            print(f\"  Indicators: {', '.join(alert['indicators'])}\")\n            print()\n    else:\n        print(\"No DNS exfiltration indicators detected.\")\n\n\nif __name__ == '__main__':\n    main()\n```\n\n### Step 3: Deploy Suricata Rules for DNS Exfiltration\n\n```\n# Detect long DNS queries (potential tunneling)\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - Excessive query length\"; dns.query; content:\".\"; pcre:\"\u002F^.{60,}\u002F\"; threshold:type both,track by_src,count 20,seconds 60; classtype:bad-unknown; sid:3000001; rev:1;)\n\n# Detect high-entropy DNS subdomain\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - High entropy subdomain\"; dns.query; pcre:\"\u002F^[a-zA-Z0-9+\\\u002F=]{30,}\\.\u002F\"; threshold:type both,track by_src,count 10,seconds 60; classtype:bad-unknown; sid:3000002; rev:1;)\n\n# Detect large TXT record responses\nalert dns any 53 -> $HOME_NET any (msg:\"DNS Exfiltration - Large TXT response\"; content:\"|00 10|\"; byte_test:2,>,400,0,relative; classtype:bad-unknown; sid:3000003; rev:1;)\n\n# Detect NULL record queries (used by iodine)\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - NULL record query (iodine indicator)\"; content:\"|00 0a|\"; classtype:bad-unknown; sid:3000004; rev:1;)\n\n# Detect dnscat2 traffic pattern\nalert dns $HOME_NET any -> any 53 (msg:\"DNS Exfiltration - dnscat2 indicator\"; dns.query; content:\"dnscat\"; nocase; classtype:trojan-activity; sid:3000005; rev:1;)\n```\n\n### Step 4: SIEM Detection Rules\n\n**Splunk SPL query for DNS exfiltration:**\n\n```spl\nindex=dns sourcetype=zeek:dns\n| eval subdomain=mvindex(split(query,\".\"),0)\n| eval subdomain_len=len(subdomain)\n| eval label_count=mvcount(split(query,\".\"))\n| stats count as query_count,\n        dc(subdomain) as unique_subdomains,\n        avg(subdomain_len) as avg_sub_len,\n        values(src_ip) as source_ips\n        by query_domain\n| where query_count > 100 AND avg_sub_len > 30 AND unique_subdomains > 50\n| eval risk_score = case(\n    avg_sub_len > 50 AND unique_subdomains > 200, \"Critical\",\n    avg_sub_len > 40 AND unique_subdomains > 100, \"High\",\n    avg_sub_len > 30 AND unique_subdomains > 50, \"Medium\",\n    true(), \"Low\")\n| sort -query_count\n| table query_domain risk_score query_count unique_subdomains avg_sub_len source_ips\n```\n\n## Response Actions\n\n1. **Block the tunnel domain** at DNS resolver and firewall level\n2. **Isolate the source host** from the network for forensic investigation\n3. **Capture full PCAP** of the DNS traffic for evidence preservation\n4. **Identify exfiltrated data** by decoding captured DNS queries\n5. **Check for persistence** mechanisms on the compromised host\n6. **Update blocklists** with identified C2 domains and infrastructure\n\n## Best Practices\n\n- **DNS Logging** - Enable full DNS query and response logging at resolvers and network level\n- **Internal DNS Only** - Force all DNS through internal resolvers; block direct external DNS (port 53)\n- **Response Policy Zones** - Deploy RPZ feeds to block known tunneling domains\n- **Baseline First** - Establish normal DNS query patterns before setting detection thresholds\n- **TXT Record Monitoring** - Pay special attention to TXT and NULL record queries\n- **Encrypted DNS Awareness** - Monitor for DoH\u002FDoT usage that may bypass DNS inspection\n\n## References\n\n- [Splunk DNS Exfiltration Detection with Deep Learning](https:\u002F\u002Fwww.splunk.com\u002Fen_us\u002Fblog\u002Fsecurity\u002Fmachine-learning-in-security-detect-dns-data-exfiltration-using-deep-learning.html)\n- [Akamai DNS Data Exfiltration](https:\u002F\u002Fwww.akamai.com\u002Fglossary\u002Fwhat-is-dns-data-exfiltration)\n- [SANS Detecting DNS Tunneling](https:\u002F\u002Fwww.giac.org\u002Fpaper\u002Fgcia\u002F1116\u002Fdetecting-dns-tunneling\u002F108367)\n- [Fidelis DNS Tunneling Detection](https:\u002F\u002Ffidelissecurity.com\u002Fthreatgeek\u002Flearn\u002Fdns-tunneling-detection\u002F)\n",{"name":5,"tags":43,"author":49,"domain":30,"license":14,"version":50,"subdomain":51,"description":7},[44,35,26,32,45,46,29,47,48],"dns-exfiltration","entropy-analysis","passive-dns","iodine","dnscat2","mahipal","1.0","network-security","master","3f5d983eb4ef375b749adcd6b07ec03bd82ae8a8","_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis",0,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills","https:\u002F\u002Fgithub.com\u002Fmicsapp","2026-03-20 11:24:18",{"source":8,"skillName":5,"commands":60,"prompt":70,"zipAvailable":71},[61,64,67],{"tool":62,"command":63},"npx","npx skills add micsapp\u002Fmicstec-skills --skill detecting-dns-exfiltration-with-dns-query-analysis",{"tool":65,"command":66},"bunx","bunx skills add micsapp\u002Fmicstec-skills --skill detecting-dns-exfiltration-with-dns-query-analysis",{"tool":68,"command":69},"pnpm","pnpm dlx skills add micsapp\u002Fmicstec-skills --skill detecting-dns-exfiltration-with-dns-query-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002FSKILL.md",true,[73,78,84],{"path":74,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002FLICENSE",{"path":79,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fapi-reference.md","REFERENCE","参考文档",1525,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002Freferences\u002Fapi-reference.md",{"path":85,"resourceType":86,"resourceTypeDesc":87,"sizeBytes":88,"sourceHtmlUrl":89},"scripts\u002Fagent.py","SCRIPT","脚本",6114,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002Fscripts\u002Fagent.py",[91,118,140,160,178,203],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":38},"01M6HBTJ02FXBFG9NYEHHYAP52","azure-apim-architecture","Analyzes and explains Azure API Management architecture decisions for enterprise API marketplace implementations using VNet Internal mode, Front Door, hybrid authentication, and multi-environment strategies. Use when discussing APIM component selection, network topology, cost optimization, or comparing alternatives like workspaces vs instances, VNet Internal vs External mode, or Front Door vs Application Gateway.","MIT","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fazure-apim-architecture\u002FSKILL.md",[],[99,100,101,102,103,104,105,106,28,107,108,109,110,111,112,113,114,115,116,117],"architecture","azure","azure apim architecture","component","authentication","gateway","topology","Optimization","api","team","environment","multi-environment","workspaces","instances","selection","strategies","azure api management","mode","for",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":38},"01M6HBT7J4H082JEEA670B3EQ9","apiops-deployment","Guides deployment of Azure API Management infrastructure using Infrastructure as Code (Bicep\u002FTerraform), CI\u002FCD pipelines (GitHub Actions\u002FAzure DevOps), and APIOps workflows. Use when deploying APIM, creating pipelines, or implementing dev→test→prod promotion strategies.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapiops-deployment\u002FSKILL.md",[],[125,126,127,128,100,129,130,131,132,133,134,135,107,108,114,136,137,115,138,139],"deployment","apiops deployment","workflows","azure devops","infrastructure","code","infrastructure as code","actions","ci","github actions","github-actions","as","guides","CI\u002FCD","implementing",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":38},"01M6HBT2HEA23THNE9E00GYQBE","apim-policy-authoring","Creates production-ready Azure API Management policy XML for authentication (OAuth 2.0, JWT validation, subscription keys), rate limiting, CORS configuration, error handling, and API transformations. Use when implementing API security, access control, or request\u002Fresponse processing logic.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapim-policy-authoring\u002FSKILL.md",[],[147,148,149,150,100,103,107,108,151,152,153,154,155,156,157,115,158,159,139,117],"policy","authoring","apim policy authoring","security","access","use","ready","api security","Access Control","error","processing","cors configuration","production-ready",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":38},"01M6HBSY65SB29J9WE9KYD0K6T","api-security-review","Reviews Azure API Management configurations for security vulnerabilities, OWASP API Security Top 10 compliance, VNet Internal mode validation, Private Link verification, and Azure Security Benchmark alignment. Use when performing security audits, pre-deployment validation, or compliance reviews.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapi-security-review\u002FSKILL.md",[],[167,150,168,107,154,169,100,125,170,171,172,173,108,174,115,175,176,177,116,117],"review","security review","api security review","benchmark","verification","owasp","owasp-api","alignment","azure security","reviews","top",{"skillNo":179,"name":180,"nameZh":6,"description":181,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":182,"categories":183,"keywords":184,"publishedAt":38},"01M6HBSRW4PDFE6K4F8JYPZQ05","jira-cli","Interact with Jira from the command line to create, list, view, edit, and transition issues, manage sprints and epics, and perform common Jira workflows. Use when the user asks about Jira tasks, tickets, issues, sprints, or needs to manage project work items.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fjira-cli\u002FSKILL.md",[],[185,186,187,127,188,189,190,191,107,192,193,194,195,196,197,198,199,200,201,202],"cli","jira","jira cli","init","tasks","create","issues","common","work","command","edit","list","view","project","project work","token","line","sprints",{"skillNo":204,"name":205,"nameZh":6,"description":206,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":207,"categories":208,"keywords":209,"publishedAt":38},"01M6HBSNS3JHMW603G47TWE31H","calculator","Performs arbitrary-precision arithmetic calculations including addition, subtraction, multiplication, division, and exponents. Use when the user asks to calculate, compute, or evaluate math expressions, or when precise decimal arithmetic is needed to avoid floating-point errors.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fcalculator\u002FSKILL.md",[],[205,210,211,212,213,214,215,152,216,217],"npm","js","calculate","node","math","user","compute","errors"]