[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73ASGK9VH0ZF9E1XD5SMF35":3,"skill-same:01M73ASGK9VH0ZF9E1XD5SMF35":93},{"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":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":53,"commitSha":54,"skillDirectory":55,"forksCount":56,"repositoryHtmlUrl":57,"repositoryHomepageUrl":58,"ownerHtmlUrl":59,"ownerBlogUrl":60,"ownerDescription":61,"updatedAt":62,"install":63,"resources":76},"01M73ASGK9VH0ZF9E1XD5SMF35","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.","Horonomos-laps\u002FYana-AI","Horonomos-laps","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F355299122?v=4","01M76B3QPXE88ET2SQPDPVATZT"," Horonomos-laps","01M72ZQRJPCYPSSWT4D00VJR2A",13,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: detecting-dns-exfiltration-with-dns-query-analysis\ndescription: Detect data exfiltration through DNS tunneling by analyzing query entropy,\n  subdomain length, query volume, TXT record abuse, and response payload sizes using\n  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\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\nnist_csf:\n- PR.IR-01\n- DE.CM-01\n- ID.AM-03\n- PR.DS-02\nmitre_attack:\n- T1046\n- T1040\n- T1557\n- T1071\n- T1048\nsource: https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\nsource_commit: 04450304b12645cb2b974ab96d28c0664758a88d\nnote: \"Vendored verbatim from an external Apache-2.0 security-skill library, pinned by commit. Exceeds the internal 300-line skill guideline (agent-code-constraints.md) -- kept as-is because this is vendored reference material (forensics\u002Fthreat-intel procedure), not Yana AI-authored content, and trimming would damage technical accuracy.\"\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,"note":25,"tags":26,"author":36,"domain":37,"source":38,"license":15,"version":39,"nist_csf":40,"subdomain":45,"description":7,"mitre_attack":46,"source_commit":52},"Vendored verbatim from an external Apache-2.0 security-skill library, pinned by commit. Exceeds the internal 300-line skill guideline (agent-code-constraints.md) -- kept as-is because this is vendored reference material (forensics\u002Fthreat-intel procedure), not Yana AI-authored content, and trimming would damage technical accuracy.",[27,28,29,30,31,32,33,34,35],"dns-exfiltration","dns-tunneling","data-exfiltration","threat-detection","entropy-analysis","passive-dns","network-monitoring","iodine","dnscat2","mahipal","cybersecurity","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills","1.0",[41,42,43,44],"PR.IR-01","DE.CM-01","ID.AM-03","PR.DS-02","network-security",[47,48,49,50,51],"T1046","T1040","T1557","T1071","T1048","04450304b12645cb2b974ab96d28c0664758a88d","main","481dcd7dd2e288b9d627a2bd017db70e64e6c6fa","core\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis",2,"https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI","https:\u002F\u002Fyana.vutam.link\u002F","https:\u002F\u002Fgithub.com\u002FHoronomos-laps","https:\u002F\u002Fyana.vutam.link","An open-source governed runtime & execution environment for multi-agent AI systems.","2026-11-14 13:24:09",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add Horonomos-laps\u002FYana-AI --skill detecting-dns-exfiltration-with-dns-query-analysis",{"tool":69,"command":70},"bunx","bunx skills add Horonomos-laps\u002FYana-AI --skill detecting-dns-exfiltration-with-dns-query-analysis",{"tool":72,"command":73},"pnpm","pnpm dlx skills add Horonomos-laps\u002FYana-AI --skill detecting-dns-exfiltration-with-dns-query-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002FSKILL.md",true,[77,81,87],{"path":78,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":16},"LICENSE","许可证",11255,{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fapi-reference.md","REFERENCE","参考文档",1525,"https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002Freferences\u002Fapi-reference.md",{"path":88,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":91,"sourceHtmlUrl":92},"scripts\u002Fagent.py","SCRIPT","脚本",6114,"https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-dns-exfiltration-with-dns-query-analysis\u002Fscripts\u002Fagent.py",[94,102,109,117,125,133],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":98,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":20},"01M735GKET5YVYKAY62W2P5YXB","openai--sentry--sentry","Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.","MIT","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fopenai--sentry--sentry\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":20},"01M73DCAP83T17HY7SMGK7MGFE","ito-basket-compare","Compare Itô prediction-market baskets against a user's knowledge base, portfolio notes, financial context, watchlist, or research thesis. Use for read-only basket comparison and gap analysis without investment advice or live trading.","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fito-basket-compare\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":113,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":20},"01M734CYEMZFDR3KH6SW0JP8TD","implementing-network-traffic-baselining","Build network traffic baselines from NetFlow\u002FIPFIX data using Python pandas for statistical analysis, z-score anomaly detection, and hourly\u002Fdaily traffic pattern profiling","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":121,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":20},"01M73ASZ6NJRJM44Z2P84NGQ3Q","detecting-evasion-techniques-in-endpoint-logs","Detects defense evasion techniques used by adversaries in endpoint logs including log tampering, timestomping, process injection, and security tool disabling. Use when investigating suspicious endpoint behavior, building detection rules for evasion tactics, or conducting threat hunting for stealthy adversary activity. Activates for requests involving evasion detection, defense evasion analysis, log tampering detection, or MITRE ATT&CK TA0005.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FSKILL.md",[],[],{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":129,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":20},"01M734AFNXD06Z78QRK0VKGT7Q","implementing-microsegmentation-with-guardicore","Implementing microsegmentation using Akamai Guardicore Segmentation to map application dependencies, create granular network policies, visualize east-west traffic flows, and enforce least-privilege communication between workloads across data centers and cloud.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FSKILL.md",[],[],{"skillNo":134,"name":135,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":20},"01M736TK27QMCXK0DVCH25SJN5","ramdisk-tmpfs-patterns","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Framdisk-tmpfs-patterns\u002FSKILL.md",[],[]]