npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- Mapping the external attack surface of a target organization during authorized penetration tests
- Discovering hidden subdomains, internal hostnames, and IP addresses exposed via DNS records
- Testing whether DNS servers allow unauthorized zone transfers that leak the entire zone file
- Identifying mail servers, name servers, and service records for further targeted testing
- Validating DNS security configurations including DNSSEC, SPF, DKIM, and DMARC
Do not use against domains you do not have authorization to test, for DNS amplification or reflection attacks, or to overwhelm DNS servers with excessive query volumes.
Prerequisites
- Written authorization to perform DNS enumeration against the target domain
- DNS enumeration tools installed: dig, nslookup, host, dnsrecon, dnsenum, subfinder, amass
- Network access to the target's DNS servers (UDP/TCP port 53)
- Wordlist for subdomain brute-forcing (SecLists dns-wordlist or similar)
- Understanding of DNS record types (A, AAAA, CNAME, MX, NS, TXT, SOA, SRV, PTR)
Workflow
Step 1: Identify DNS Servers and Basic Records
# Find authoritative name servers
dig NS example.com +short
# ns1.example.com.
# ns2.example.com.
# Get SOA record for zone metadata
dig SOA example.com +short
# ns1.example.com. admin.example.com. 2024031501 3600 900 604800 86400
# Enumerate all common record types
dig example.com ANY +noall +answer
# Get MX records (mail servers)
dig MX example.com +short
# 10 mail.example.com.
# 20 mail-backup.example.com.
# Get TXT records (SPF, DKIM, DMARC, verification)
dig TXT example.com +short
# Check for DMARC policy
dig TXT _dmarc.example.com +short
# Check for DKIM selectors
dig TXT default._domainkey.example.com +short
dig TXT selector1._domainkey.example.com +short
dig TXT google._domainkey.example.com +short
# Get SRV records for common services
dig SRV _sip._tcp.example.com +short
dig SRV _ldap._tcp.example.com +short
dig SRV _kerberos._tcp.example.com +shortStep 2: Attempt Zone Transfers
# Attempt AXFR zone transfer against each name server
dig AXFR example.com @ns1.example.com
dig AXFR example.com @ns2.example.com
# Use host command for zone transfer
host -t axfr example.com ns1.example.com
# Use dnsrecon for automated zone transfer attempts
dnsrecon -d example.com -t axfr
# If zone transfer succeeds, save the output
dig AXFR example.com @ns1.example.com > zone_transfer_results.txt
# Test for IXFR (incremental zone transfer)
dig IXFR=2024031500 example.com @ns1.example.comStep 3: Subdomain Enumeration via Brute Force
# Use dnsenum for comprehensive enumeration
dnsenum --dnsserver ns1.example.com --enum -f /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -r example.com -o dnsenum_output.xml
# Use dnsrecon with brute force
dnsrecon -d example.com -t brt -D /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
# Use gobuster for fast DNS brute forcing
gobuster dns -d example.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt -t 50 -o gobuster_dns.txt
# Use subfinder for passive subdomain discovery
subfinder -d example.com -all -o subfinder_results.txt
# Use amass for comprehensive enumeration (passive + active)
amass enum -d example.com -passive -o amass_passive.txt
amass enum -d example.com -active -brute -o amass_active.txt
# Combine and deduplicate results
cat subfinder_results.txt amass_passive.txt amass_active.txt gobuster_dns.txt | sort -u > all_subdomains.txtStep 4: Reverse DNS and PTR Enumeration
# Reverse DNS lookup on discovered IP ranges
dnsrecon -d example.com -t rvl -r 10.10.0.0/24
# PTR record enumeration for IP range
for ip in $(seq 1 254); do
result=$(dig -x 10.10.1.$ip +short 2>/dev/null)
if [ -n "$result" ]; then
echo "10.10.1.$ip -> $result"
fi
done
# Use Nmap for reverse DNS on a subnet
nmap -sL 10.10.0.0/24 | grep "(" | awk '{print $5, $6}'
# Check for DNS cache snooping (information about queried domains)
dig @ns1.example.com www.competitor.com +norecurseStep 5: Analyze DNS Security Configuration
# Check DNSSEC validation
dig example.com +dnssec +short
dig DNSKEY example.com +short
dig DS example.com +short
# Test for DNS rebinding vulnerability
# Check if the DNS server has a short TTL that could enable rebinding
dig example.com +noall +answer | grep -i ttl
# Check for open recursive resolver (misconfiguration)
dig @ns1.example.com google.com +recurse
# If it resolves, the server is an open resolver
# Check for wildcard DNS records
dig nonexistent-subdomain-xyz123.example.com +short
# If it resolves, a wildcard record exists
# Test DNS over HTTPS/TLS support
# DoH test
curl -s -H 'accept: application/dns-json' 'https://dns.google/resolve?name=example.com&type=A'
# Verify SPF record for email security
dig TXT example.com +short | grep "v=spf1"
# Check for overly permissive SPF (+all, ?all)Step 6: Resolve and Map All Discovered Subdomains
# Resolve all discovered subdomains to IP addresses
while read subdomain; do
ip=$(dig +short A "$subdomain" | head -1)
if [ -n "$ip" ]; then
echo "$subdomain,$ip"
fi
done < all_subdomains.txt > resolved_subdomains.csv
# Identify unique IP addresses and their locations
cut -d',' -f2 resolved_subdomains.csv | sort -u > unique_ips.txt
# Check for internal IP addresses leaked via DNS
grep -E "^10\.|^172\.(1[6-9]|2[0-9]|3[01])\.|^192\.168\." resolved_subdomains.csv > internal_ip_leaks.txt
# Use httpx to probe web services on discovered subdomains
cat all_subdomains.txt | httpx -title -status-code -tech-detect -o httpx_results.txt
# Screenshot web services for documentation
cat all_subdomains.txt | httpx -screenshot -o screenshots/Key Concepts
| Term | Definition |
|---|---|
| Zone Transfer (AXFR) | DNS mechanism that replicates the complete zone file from a primary to secondary server; unauthorized transfers expose all records in the zone |
| Subdomain Enumeration | Process of discovering valid subdomains through brute force, certificate transparency logs, search engines, and passive DNS databases |
| DNSSEC | DNS Security Extensions that add cryptographic signatures to DNS responses, preventing cache poisoning and spoofing attacks |
| SPF/DKIM/DMARC | Email authentication protocols defined in DNS TXT records that prevent email spoofing and domain impersonation |
| Wildcard DNS | A DNS record using an asterisk (*) that matches any query for non-existent subdomains, potentially masking enumeration results |
| PTR Record | Reverse DNS record that maps an IP address to a hostname, often revealing internal naming conventions and server roles |
Tools & Systems
- dig: Standard DNS lookup utility with full support for all record types, DNSSEC validation, and zone transfer queries
- dnsrecon: Comprehensive DNS enumeration tool supporting zone transfers, brute force, reverse lookup, cache snooping, and Google dork queries
- subfinder: Fast passive subdomain discovery tool that queries certificate transparency logs, search engines, and DNS databases
- Amass (OWASP): Advanced attack surface mapping tool with both passive and active DNS enumeration, graph analysis, and data source integration
- gobuster: Fast brute-force tool for DNS subdomain enumeration using configurable wordlists and concurrent threads
Common Scenarios
Scenario: External Reconnaissance for a Web Application Penetration Test
Context: A security consultant is performing external reconnaissance for a web application penetration test. The client's primary domain is example.com, and the scope includes all subdomains and related infrastructure. The consultant has authorization to enumerate DNS records and probe discovered web services.
Approach:
- Query NS, MX, TXT, and SOA records for example.com to map the DNS infrastructure
- Attempt zone transfers against both nameservers -- ns2 succeeds, revealing 347 DNS records including internal staging environments
- Run subfinder and amass in passive mode to discover 89 additional subdomains from certificate transparency logs
- Brute-force subdomains with a 20,000-word list using gobuster, discovering 12 more subdomains not found in passive sources
- Resolve all subdomains and identify 15 that resolve to internal RFC1918 addresses (information disclosure)
- Probe all web-accessible subdomains with httpx, discovering a staging environment (staging.example.com) with default credentials
- Report zone transfer vulnerability, internal IP disclosure, and exposed staging environment to the client
Pitfalls:
- Sending thousands of DNS queries per second and triggering rate limiting or DNS-based DDoS protection
- Not checking for wildcard DNS records, resulting in false positive subdomain discoveries
- Missing subdomains that use separate DNS providers or CDN-specific CNAME records
- Overlooking TXT records that contain API keys, verification tokens, or internal comments
Output Format
## DNS Enumeration Report
**Target Domain**: example.com
**Authorized Nameservers**: ns1.example.com (203.0.113.10), ns2.example.com (203.0.113.11)
### Zone Transfer Status
| Nameserver | AXFR Result | Records Obtained |
|------------|-------------|------------------|
| ns1.example.com | REFUSED | 0 |
| ns2.example.com | SUCCESS | 347 records |
### Subdomain Discovery Summary
| Method | Subdomains Found |
|--------|-----------------|
| Zone Transfer | 347 |
| Passive (subfinder + amass) | 89 |
| Active Brute Force | 12 |
| **Total Unique** | **412** |
### Critical Findings
1. **Zone Transfer Allowed** (High): ns2.example.com allows AXFR from any source
2. **Internal IP Disclosure** (Medium): 15 subdomains resolve to RFC1918 addresses
3. **Exposed Staging Environment** (High): staging.example.com accessible with default credentials
4. **Missing DMARC Policy** (Medium): No DMARC record found, enabling email spoofing
5. **Weak SPF Record** (Low): SPF uses ~all (soft fail) instead of -all (hard fail)References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.1 KB
API Reference: Performing DNS Enumeration and Zone Transfer
dnspython Library
| Function/Class | Description |
|---|---|
dns.resolver.resolve(domain, rdtype) |
Query DNS records by type |
dns.zone.from_xfr(xfr_response) |
Parse zone transfer response |
dns.query.xfr(nameserver, domain) |
Perform AXFR zone transfer |
dns.rdatatype.to_text(rdtype) |
Convert record type to string |
dns.resolver.Resolver() |
Custom resolver with timeout settings |
DNS Record Types
| Type | Description |
|---|---|
| A | IPv4 address record |
| AAAA | IPv6 address record |
| MX | Mail exchange server |
| NS | Authoritative nameserver |
| TXT | Text record (SPF, DKIM, DMARC) |
| SOA | Start of Authority |
| CNAME | Canonical name alias |
| SRV | Service location record |
| CAA | Certificate Authority Authorization |
| AXFR | Full zone transfer request |
Email Security Records
| Record | Location | Description |
|---|---|---|
| SPF | domain TXT |
Authorized mail sender IPs |
| DMARC | _dmarc.domain TXT |
Email authentication policy |
| DKIM | selector._domainkey.domain TXT |
Email signing public key |
Key Libraries
- dnspython (
pip install dnspython): Full-featured DNS toolkit for Python - python-nmap (optional): Network port scanning for DNS services
- sublist3r (optional): Subdomain enumeration using search engines
Configuration
| Variable | Description |
|---|---|
| Target domain | Authorized target domain for enumeration |
| Resolver timeout | DNS query timeout (default 3 seconds) |
| Wordlist | Subdomain brute-force dictionary |
Common Subdomain Wordlists
| Source | Description |
|---|---|
| SecLists DNS | Discovery/DNS/subdomains-top1million-5000.txt |
| Assetnote | Best-DNS-Wordlist from Assetnote |
| Custom | Industry-specific subdomain patterns |
References
Scripts 1
agent.py8.3 KB
#!/usr/bin/env python3
"""
DNS Enumeration and Zone Transfer Agent — AUTHORIZED TESTING ONLY
Performs DNS reconnaissance including record enumeration, zone transfer
attempts, and subdomain discovery using dnspython.
WARNING: Only use with explicit written authorization for the target domain.
"""
import json
import sys
from datetime import datetime, timezone
import dns.resolver
import dns.zone
import dns.query
import dns.rdatatype
def enumerate_dns_records(domain: str) -> dict:
"""Enumerate common DNS record types for a domain."""
record_types = ["A", "AAAA", "MX", "NS", "TXT", "SOA", "CNAME", "SRV", "CAA"]
results = {}
for rtype in record_types:
try:
answers = dns.resolver.resolve(domain, rtype)
records = []
for rdata in answers:
records.append(str(rdata))
results[rtype] = records
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
results[rtype] = []
except dns.exception.DNSException:
results[rtype] = []
return results
def get_nameservers(domain: str) -> list[str]:
"""Resolve authoritative nameservers for a domain."""
nameservers = []
try:
ns_records = dns.resolver.resolve(domain, "NS")
for ns in ns_records:
ns_name = str(ns).rstrip(".")
try:
a_records = dns.resolver.resolve(ns_name, "A")
for a in a_records:
nameservers.append({"name": ns_name, "ip": str(a)})
except dns.exception.DNSException:
nameservers.append({"name": ns_name, "ip": "unresolved"})
except dns.exception.DNSException as e:
nameservers.append({"error": str(e)})
return nameservers
def attempt_zone_transfer(domain: str, nameservers: list[dict]) -> dict:
"""Attempt AXFR zone transfer against each nameserver."""
results = {"vulnerable": False, "records": [], "tested_servers": []}
for ns in nameservers:
ns_ip = ns.get("ip", "")
ns_name = ns.get("name", "")
if ns_ip == "unresolved" or "error" in ns:
continue
server_result = {"nameserver": ns_name, "ip": ns_ip, "transfer_allowed": False}
try:
zone = dns.zone.from_xfr(dns.query.xfr(ns_ip, domain, timeout=10))
server_result["transfer_allowed"] = True
results["vulnerable"] = True
for name, node in zone.nodes.items():
for rdataset in node.rdatasets:
for rdata in rdataset:
results["records"].append({
"name": str(name),
"type": dns.rdatatype.to_text(rdataset.rdtype),
"ttl": rdataset.ttl,
"data": str(rdata),
})
except dns.exception.FormError:
server_result["error"] = "Transfer refused (FORMERR)"
except dns.xfr.TransferError:
server_result["error"] = "Transfer refused"
except dns.exception.DNSException as e:
server_result["error"] = str(e)
except Exception as e:
server_result["error"] = str(e)
results["tested_servers"].append(server_result)
return results
def check_email_security(domain: str) -> dict:
"""Check SPF, DKIM, and DMARC DNS records."""
security = {"spf": None, "dmarc": None, "dkim_selectors": []}
try:
txt_records = dns.resolver.resolve(domain, "TXT")
for txt in txt_records:
txt_str = str(txt).strip('"')
if txt_str.startswith("v=spf1"):
security["spf"] = txt_str
except dns.exception.DNSException:
pass
try:
dmarc = dns.resolver.resolve(f"_dmarc.{domain}", "TXT")
for txt in dmarc:
txt_str = str(txt).strip('"')
if "v=DMARC1" in txt_str:
security["dmarc"] = txt_str
except dns.exception.DNSException:
pass
common_selectors = ["default", "google", "selector1", "selector2", "s1", "s2", "mail", "k1"]
for selector in common_selectors:
try:
dkim = dns.resolver.resolve(f"{selector}._domainkey.{domain}", "TXT")
for txt in dkim:
security["dkim_selectors"].append({
"selector": selector,
"record": str(txt).strip('"')[:100],
})
except dns.exception.DNSException:
pass
return security
def brute_force_subdomains(domain: str, wordlist: list[str] = None) -> list[dict]:
"""Brute-force subdomain discovery via DNS resolution."""
if wordlist is None:
wordlist = [
"www", "mail", "ftp", "admin", "api", "dev", "staging",
"test", "vpn", "portal", "app", "login", "secure",
"m", "blog", "shop", "cdn", "ns1", "ns2", "mx",
"remote", "gateway", "intranet", "extranet", "webmail",
"owa", "autodiscover", "sso", "auth", "git", "ci",
]
found = []
resolver = dns.resolver.Resolver()
resolver.timeout = 3
resolver.lifetime = 3
for sub in wordlist:
fqdn = f"{sub}.{domain}"
try:
answers = resolver.resolve(fqdn, "A")
ips = [str(a) for a in answers]
found.append({"subdomain": fqdn, "ips": ips, "record_type": "A"})
except dns.exception.DNSException:
pass
try:
answers = resolver.resolve(fqdn, "CNAME")
cnames = [str(c) for c in answers]
found.append({"subdomain": fqdn, "cnames": cnames, "record_type": "CNAME"})
except dns.exception.DNSException:
pass
return found
def generate_report(
domain: str, records: dict, nameservers: list, zone_transfer: dict,
email_security: dict, subdomains: list,
) -> str:
"""Generate DNS enumeration report."""
lines = [
"DNS ENUMERATION AND ZONE TRANSFER REPORT — AUTHORIZED TESTING ONLY",
"=" * 65,
f"Target Domain: {domain}",
f"Date: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}",
"",
"DNS RECORDS:",
]
for rtype, recs in records.items():
if recs:
lines.append(f" {rtype}: {', '.join(recs[:5])}")
lines.extend([
"",
f"NAMESERVERS ({len(nameservers)}):",
])
for ns in nameservers:
if "error" not in ns:
lines.append(f" {ns['name']} ({ns['ip']})")
vuln = "VULNERABLE" if zone_transfer["vulnerable"] else "NOT VULNERABLE"
lines.extend([
"",
f"ZONE TRANSFER: {vuln}",
f" Records Leaked: {len(zone_transfer['records'])}",
])
lines.extend([
"",
"EMAIL SECURITY:",
f" SPF: {'Present' if email_security['spf'] else 'MISSING'}",
f" DMARC: {'Present' if email_security['dmarc'] else 'MISSING'}",
f" DKIM Selectors Found: {len(email_security['dkim_selectors'])}",
"",
f"SUBDOMAINS DISCOVERED: {len(subdomains)}",
])
for sub in subdomains[:15]:
ips = sub.get("ips", sub.get("cnames", []))
lines.append(f" {sub['subdomain']} -> {', '.join(ips)}")
return "\n".join(lines)
if __name__ == "__main__":
print("[!] DNS ENUMERATION — AUTHORIZED TESTING ONLY\n")
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <target_domain>")
sys.exit(1)
domain = sys.argv[1]
print(f"[*] Enumerating DNS records for {domain}...")
records = enumerate_dns_records(domain)
print("[*] Resolving nameservers...")
nameservers = get_nameservers(domain)
print("[*] Attempting zone transfer...")
zone_transfer = attempt_zone_transfer(domain, nameservers)
print("[*] Checking email security records...")
email_security = check_email_security(domain)
print("[*] Brute-forcing subdomains...")
subdomains = brute_force_subdomains(domain)
report = generate_report(domain, records, nameservers, zone_transfer, email_security, subdomains)
print(report)
output = f"dns_enum_{domain.replace('.', '_')}_{datetime.now(timezone.utc).strftime('%Y%m%d')}.json"
with open(output, "w") as f:
json.dump({"records": records, "nameservers": nameservers, "zone_transfer": zone_transfer,
"email_security": email_security, "subdomains": subdomains}, f, indent=2)
print(f"\n[*] Results saved to {output}")