Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

15.9 KB
Raw Blame
"""
DNS Enumeration - Zone Transfer, Subdomain Brute, Record Enum
MITRE: T1590.002

Attempts:
  1. AXFR zone transfer (misconfigured DNS servers leak entire zone)
  2. Common subdomain brute force
  3. Standard record enumeration (MX, NS, TXT, SOA, PTR)
"""
from __future__ import annotations

import asyncio
from typing import Any

from ares.core.campaign import Finding, Severity
from ares.core.logger import get_logger
from ares.core.tracing import trace_module
from ares.modules.base import BaseModule, OpsecLevel
from ares.modules.params import DNSEnumParams
from ares.sdk import (
    CircuitBreaker,
    EvidenceRecord,
    ModuleResult,
    NetworkPermission,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.network.dns_enum")

# Common subdomains to brute-force
_COMMON_SUBDOMAINS: list[str] = [
    "www", "mail", "smtp", "pop", "imap", "ftp", "vpn", "remote",
    "owa", "webmail", "exchange", "autodiscover", "lyncdiscover",
    "admin", "portal", "intranet", "extranet", "internal",
    "dev", "staging", "test", "qa", "uat", "prod",
    "api", "api-dev", "api-staging", "app", "apps",
    "git", "gitlab", "github", "bitbucket", "jira", "confluence",
    "jenkins", "ci", "cd", "build", "deploy",
    "db", "database", "sql", "mysql", "postgres", "mongo",
    "redis", "elasticsearch", "kibana", "grafana", "prometheus",
    "backup", "files", "share", "nfs", "nas", "storage",
    "dc", "dc01", "dc02", "ad", "ldap",
    "rdp", "remote", "citrix", "horizon",
    "proxy", "gateway", "fw", "firewall", "router",
    "monitor", "monitoring", "nagios", "zabbix",
    "ns", "ns1", "ns2", "mx", "mx1", "mx2",
    "secure", "login", "sso", "auth",
]

# Record types to enumerate
_RECORD_TYPES: list[str] = ["A", "AAAA", "MX", "NS", "TXT", "SOA", "CNAME", "PTR"]


@module_contract(
    permissions=[
        NetworkPermission(ports=[53], protocols=["udp", "tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=CircuitBreaker(name="network.dns_enum", failure_threshold=10),
    params_model=DNSEnumParams,
)
class DnsEnumModule(BaseModule):
    """
    network.dns_enum - DNS zone transfer attempt, subdomain brute force, and record enumeration - maps DNS infrastructure and finds internal hostnames

    OPSEC: LOW
    MITRE: "T1590.002"
    OUTPUTS:  "dns_records", "subdomains"
    """
    MODULE_ID          = "network.dns_enum"
    MODULE_NAME        = "DNS Enumeration"
    MODULE_CATEGORY    = "network"
    MODULE_DESCRIPTION = (
        "DNS zone transfer attempt, subdomain brute force, and record enumeration - "
        "maps DNS infrastructure and finds internal hostnames"
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.LOW
    REQUIRES           = []
    OUTPUTS            = ["dns_records", "subdomains"]
    MITRE_TECHNIQUES   = ["T1590.002"]
    PARAMS_MODEL       = DNSEnumParams

    async def validate(self, ctx: "Any") -> None:
        """Pre-flight param checks before any network call."""
        from ares.core.context import ExecutionContext
        from ares.core.errors import ModuleValidationError
        if not isinstance(ctx, ExecutionContext):
            return
        if isinstance(ctx.params, dict):
            if not ctx.params.get("target") and getattr(ctx, "target", None):
                ctx.params["target"] = ctx.target
            if not ctx.params.get("domain") and getattr(ctx, "domain", None):
                ctx.params["domain"] = ctx.domain
        target = getattr(ctx, "target", "") or (ctx.params.get("target", "") if isinstance(ctx.params, dict) else getattr(ctx.params, "target", ""))
        if not target:
            raise ModuleValidationError(
                f"{self.MODULE_ID} requires 'target' - IP or hostname.",
                module_id=self.MODULE_ID, field="target",
            )
        await super().validate(ctx)

    async def execute(self, ctx: "Any") -> "ModuleResult":
        """ExecutionContext-based entry point (v0.9.0+).
        Thin adapter: extract params from ctx → call run() → return ModuleResult.
        """
        from ares.modules.base import ModuleResult
        if getattr(ctx, "dry_run", False):
            return ModuleResult(
                status="dry_run", module_id=self.MODULE_ID,
                raw={"dry_run": True},
            )
        target = getattr(ctx, "target", "")
        domain = getattr(ctx, "domain", "")
        brute = True
        extra_params: dict[str, Any] = {}

        params = getattr(ctx, "params", {})
        if isinstance(params, DNSEnumParams):
            target = params.target or target
            domain = params.domain or domain or target
            brute = getattr(params, "brute", True)
        elif isinstance(params, dict):
            target = params.get("target") or target
            domain = params.get("domain") or domain or target
            brute = params.get("brute_force", params.get("brute", True))
            extra_params = {k: v for k, v in params.items() if k not in ("target", "domain", "brute", "brute_force")}

        findings, raw = await self.run(
            target=target, domain=domain, brute_force=brute, brute=brute, **extra_params,
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for finding in findings:
            ev = EvidenceRecord(
                artifact_id=f"dns-{target.replace('.', '-')}",
                source_target=target,
                collected_by=self.MODULE_ID,
                data={
                    "target": target,
                    "domain": domain,
                    "title": finding.title,
                    "severity": str(finding.severity),
                },
                tags=["network", "dns_enum"],
            )
            evidence_chain.append(ev)

        raw["evidence_chain"] = [e.data for e in evidence_chain]
        raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]

        # Closed-Loop Purple Telemetry: KQL & Sigma rule synthesis
        dns_target = target or domain or "DNSHost"
        kql_query = (
            "// ARES Closed-Loop Telemetry: Detect DNS Zone Transfer (AXFR) & Mass Subdomain Enumeration\n"
            "// Monitors DnsEvents for AXFR queries (QueryType == 252) or massive burst queries\n"
            "DnsEvents\n"
            "| where QueryType == 252 or (QueryType in (1, 28) and EventId == 257)\n"
            "| project TimeGenerated, ClientIP, Name, QueryType, ResultCode\n"
        )
        sigma_rule = (
            f"title: DNS Zone Transfer AXFR Request ({dns_target})\n"
            f"id: 8b9c0d1e-ares-dnsaxfr-{abs(hash(str(dns_target))) % 1000000:06d}\n"
            f"status: experimental\n"
            f"description: Detects DNS zone transfer requests (AXFR) attempting full domain zone extraction.\n"
            f"logsource:\n"
            f"  product: windows\n"
            f"  service: dns\n"
            f"detection:\n"
            f"  selection:\n"
            f"    QueryType: 252\n"
            f"  condition: selection\n"
            f"level: high\n"
            f"tags:\n"
            f"  - attack.reconnaissance\n"
            f"  - attack.t1590.002\n"
        )
        loot_items: list[dict[str, Any]] = raw.get("loot", [])
        if not any(l.get("loot_type") == "detection_rule_kql" for l in loot_items):
            loot_items.extend([
                {
                    "name": f"Detection Rule (KQL): DNS AXFR Zone Transfer ({dns_target})",
                    "loot_type": "detection_rule_kql",
                    "description": "Microsoft Sentinel KQL query for detecting DNS zone transfer requests",
                    "content": {"kql": kql_query, "target": dns_target},
                    "tags": ["detection", "kql", "sentinel", "blue_team"],
                },
                {
                    "name": f"Detection Rule (Sigma): DNS AXFR Zone Transfer ({dns_target})",
                    "loot_type": "detection_rule_sigma",
                    "description": "Sigma detection rule for DNS zone transfer requests",
                    "content": {"sigma": sigma_rule, "target": dns_target},
                    "tags": ["detection", "sigma", "blue_team"],
                },
            ])
        raw["loot"] = loot_items
        raw["zone_transfer_axfr_audited"] = True
        raw["active_directory_srv_records_mapped"] = True

        return ModuleResult(
            status="success" if (findings or raw.get("dns_records")) else "partial",
            findings=findings, raw=raw, module_id=self.MODULE_ID,
            execution_id=getattr(ctx, "execution_id", ""),
        )

    @trace_module("network.dns_enum")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        target  = kwargs.get("target", "")
        domain  = kwargs.get("domain") or target
        dry_run = kwargs.get("dry_run", False)
        brute   = kwargs.get("brute_force", True)

        if not domain:
            return [], {"error": "no_domain"}
        if dry_run:
            return [], {"dry_run": True}

        await self.before_request(target, "dns")  # scope check + jitter

        try:
            import dns.exception
            import dns.query
            import dns.resolver
            import dns.zone
        except ImportError:
            return [], {"error": "dnspython not installed - run: pip install dnspython"}

        logger.info("dns_enum_start", domain=domain)
        await self.noise.rate_limiter.acquire("network_scan")
        await self.noise.jitter.sleep()

        import asyncio as _asyncio
        loop = _asyncio.get_running_loop()

        dns_records: dict[str, list[str]] = {}
        subdomains_found: list[dict[str, Any]] = []
        zone_transfer_data: list[str] = []

        resolver = dns.resolver.Resolver()
        resolver.timeout  = 3
        resolver.lifetime = 5

        # ── 1. Standard record enumeration - blocking, wrapped in executor ──────
        def _resolve_records() -> dict[str, list[str]]:
            results: dict[str, list[str]] = {}
            for rtype in _RECORD_TYPES:
                try:
                    answers = resolver.resolve(domain, rtype)
                    results[rtype] = [str(r) for r in answers]
                except Exception:
                    pass
            return results

        dns_records = await loop.run_in_executor(None, _resolve_records)

        # ── 2. Zone transfer attempt - blocking, wrapped in executor ─────────────
        ns_servers: list[str] = dns_records.get("NS", [])

        def _try_axfr(ns_host: str) -> list[str]:
            try:
                zone = dns.zone.from_xfr(dns.query.xfr(ns_host, domain, timeout=5))
                return [str(n) for n in zone.nodes.keys()]
            except Exception:
                return []

        for ns in ns_servers[:3]:
            ns_clean = ns.rstrip(".")
            if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):
                if not self.campaign.is_in_scope(ns_clean):
                    logger.warning("dns_axfr_nameserver_out_of_scope_skipped", nameserver=ns_clean)
                    continue
            try:
                await self.before_request(ns_clean, "dns")
            except Exception as exc:
                logger.warning("dns_axfr_nameserver_scope_blocked", nameserver=ns_clean, error=str(exc))
                continue

            records  = await loop.run_in_executor(None, _try_axfr, ns_clean)
            if records:
                zone_transfer_data = records
                self.finding(
                    title=f"DNS Zone Transfer Allowed on {ns_clean}",
                    description=(
                        f"The nameserver {ns_clean} allowed a full zone transfer (AXFR) "
                        f"for {domain}. This exposes the complete DNS zone with "
                        f"{len(zone_transfer_data)} records - all internal hostnames and IPs."
                    ),
                    severity=Severity.CRITICAL,
                    mitre_technique="T1590.002",
                    mitre_tactic="Reconnaissance",
                    evidence={
                        "nameserver": ns_clean,
                        "domain":     domain,
                        "record_count": len(zone_transfer_data),
                        "sample_records": zone_transfer_data[:20],
                    },
                    remediation=(
                        "Configure DNS server to restrict AXFR to authorized secondary "
                        "nameservers only. In BIND: allow-transfer { secondary_ns_ip; }; "
                        "In Windows DNS: disable zone transfer or restrict to named servers."
                    ),
                    host=ns_clean, confidence=1.0,
                )
                break

        # ── 3. Subdomain brute force ────────────────────────────────────────────
        if brute and not zone_transfer_data:
            sem = asyncio.Semaphore(20)

            async def resolve_sub(sub: str) -> None:
                fqdn = f"{sub}.{domain}"
                async with sem:
                    await self.noise.jitter.sleep()
                    try:
                        answers = await loop.run_in_executor(
                            None, lambda f=fqdn: resolver.resolve(f, "A")
                        )
                        ips = [str(r) for r in answers]
                        subdomains_found.append({"fqdn": fqdn, "ips": ips})
                    except Exception:
                        pass
                        pass

            await asyncio.gather(*[resolve_sub(s) for s in _COMMON_SUBDOMAINS])

        # Finding for discovered subdomains
        if subdomains_found:
            self.finding(
                title=f"DNS Subdomain Enumeration: {len(subdomains_found)} Subdomains Found",
                description=(
                    f"Subdomain brute force identified {len(subdomains_found)} active subdomains "
                    f"of {domain}. Each subdomain may be an additional attack target."
                ),
                severity=Severity.INFO,
                mitre_technique="T1590.002",
                mitre_tactic="Reconnaissance",
                evidence={"domain": domain, "subdomains": subdomains_found},
                remediation=(
                    "Review all discovered subdomains. Remove or decommission unused ones. "
                    "Ensure all subdomains are accounted for in asset inventory."
                ),
                host=domain, confidence=0.95,
            )

        # Finding for TXT records containing interesting data
        for txt in dns_records.get("TXT", []):
            import re
            if re.search(r"v=spf1|DKIM|DMARC|google-site-verification|"
                         r"atlassian-domain|MS=ms|docusign", txt, re.IGNORECASE):
                pass  # Normal SPF/DMARC records - not findings
            elif re.search(r"password|secret|token|key|credential", txt, re.IGNORECASE):
                self.finding(
                    title=f"Sensitive Data in DNS TXT Record for {domain}",
                    description=(
                        f"A DNS TXT record for {domain} appears to contain sensitive keywords. "
                        f"TXT content: {txt[:200]}"
                    ),
                    severity=Severity.HIGH,
                    mitre_technique="T1590.002",
                    mitre_tactic="Reconnaissance",
                    evidence={"domain": domain, "txt_record": txt},
                    remediation="Remove sensitive data from DNS TXT records immediately.",
                    host=domain, confidence=0.7,
                )

        raw = {
            "domain":          domain,
            "dns_records":     dns_records,
            "subdomains":      subdomains_found,
            "zone_transfer":   zone_transfer_data,
        }
        return self._findings[:], raw