[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71FERBN3HE2Z5PF539WZ0MH":3,"skill-same:01M71FERBN3HE2Z5PF539WZ0MH":95},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":68,"commitSha":69,"skillDirectory":70,"forksCount":14,"repositoryHtmlUrl":71,"repositoryHomepageUrl":6,"ownerHtmlUrl":72,"ownerBlogUrl":6,"ownerDescription":73,"updatedAt":74,"install":75,"resources":88},"01M71FERBN3HE2Z5PF539WZ0MH","layer7-dns-forensic-dnsexfil-detect",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.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fnet-layer7-dns\u002Fdnsexfil\u002Fdetect\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"forensic","layer7 dns forensic dnsexfil detect","detect","dns","read","de","subdomain","threat-detection","data-exfiltration","monitoring","dns-tunneling","exfiltration","analysis","Bash","query","cybersecurity","network-monitoring","cm","entropy","volume","2026-11-10 10:12:30",false,"---\nname: layer7-dns-forensic-dnsexfil-detect\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:\n- dns-exfiltration\n- dns-tunneling\n- data-exfiltration\n- threat-detection\n- entropy-analysis\n- passive-dns\n- network-monitoring\n- iodine\n- dnscat2\nnist_csf:\n- PR.IR-01\n- DE.CM-01\n- ID.AM-03\n- PR.DS-02\nmodel: sonnet\nmaxTurns: 20\ntools: [Read, Bash, Glob, Grep]\nmitre_attack:\n- T1041\n- T1059\n- T1071.004\n- T1595.002\ncapec: []\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":44,"capec":50,"model":51,"tools":52,"domain":34,"maxTurns":56,"nist_csf":57,"subdomain":62,"description":7,"mitre_attack":63},[45,29,27,26,46,47,35,48,49],"dns-exfiltration","entropy-analysis","passive-dns","iodine","dnscat2",[],"sonnet",[53,32,54,55],"Read","Glob","Grep",20,[58,59,60,61],"PR.IR-01","DE.CM-01","ID.AM-03","PR.DS-02","network-security",[64,65,66,67],"T1041","T1059","T1071.004","T1595.002","main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fnet-layer7-dns\u002Fdnsexfil\u002Fdetect","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":76,"prompt":86,"zipAvailable":87},[77,80,83],{"tool":78,"command":79},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill layer7-dns-forensic-dnsexfil-detect",{"tool":81,"command":82},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill layer7-dns-forensic-dnsexfil-detect",{"tool":84,"command":85},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill layer7-dns-forensic-dnsexfil-detect","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fnet-layer7-dns\u002Fdnsexfil\u002Fdetect\u002FSKILL.md",true,[89],{"path":90,"resourceType":91,"resourceTypeDesc":92,"sizeBytes":93,"sourceHtmlUrl":94},"index.json","REFERENCE","参考文档",675,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fnet-layer7-dns\u002Fdnsexfil\u002Fdetect\u002Findex.json",[96,106,128,148,169,191],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":100,"licenseFileUrl":101,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":105},"01M73MDK3NT5XHNYTQ5P5172V9","devel-jb-algorithmic-art","- Embed algorithms inline in the HTML artifact (don't create separate .","Apache-2.0","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fdevel-jb-algorithmic-art\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fdevel-jb-algorithmic-art\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":39},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[113,21,114,115,116,117,118,34,119,120,121,122,123,124,125,126,127,36,24],"services","services wmi persistence detect","wmi","persistence","process-forensics","process","forensics","t1546.003","event-subscription","subscription","repository","commandline-consumer","subscriptions","event","activescript",{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":132,"categories":133,"keywords":134,"publishedAt":39},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[135,115,136,113,137,138,32,31,139,34,140,141,142,143,144,23,145,146,24,147],"exec","services wmi exec exploit","exploit","across","team","traffic","remote","crackmapexec","Impacket","lateral-movement","lateral movement","command","native",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":154,"publishedAt":39},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[155,156,157,158,159,51,160,161,162,163,23,24,164,165,31,166,32,34,167,168],"extract","registry artifact extract","registry","artifact","digital-forensics","regripper","windows-registry","evidence-collection","software","uncover","analyze","collection","artifact-analysis","activity",{"skillNo":170,"name":171,"nameZh":6,"description":172,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":173,"categories":174,"keywords":175,"publishedAt":39},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[176,177,178,21,34,179,36,180,181,182,117,24,183,184,185,186,187,188,189,190],"processes","token","processes token impersonate detect","techniques","escalation","windows","attacks","via","impersonation","potato","exploitation","printspoofer","token-impersonation","seimpersonate","privilege-escalation",{"skillNo":192,"name":193,"nameZh":6,"description":194,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":195,"categories":196,"keywords":197,"publishedAt":39},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[198,176,199,21,200,201,118,24,183,202,203,204,31,117,34,179,205,36,206,181],"thread","injection","processes thread injection detect","thread-injection","nt-api","apc-injection","api","process-injection","memory"]