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.2 KB
Raw Blame
"""
Windows Token Impersonation - SeImpersonatePrivilege Abuse (Potato Attacks)
MITRE: T1134.001, T1134.002

Detects and exploits SeImpersonatePrivilege via impacket.
Checks for: Juicy/Sweet/Hot/RoguePotato conditions.
Requires existing shell/WinRM access to the target.
"""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ares.modules.base import FeasibilityReport


import asyncio
from typing import Any

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

logger = get_logger("ares.modules.windows.token_impersonation")


@module_contract(
    permissions=[
        NetworkPermission(ports=[135, 445, 5985], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=TokenImpersonationParams,
)
class TokenImpersonationModule(BaseModule):
    """
    windows.token_impersonation - Detect SeImpersonatePrivilege on current session - prerequisite check for Potato-family privileg

    OPSEC: MEDIUM
    MITRE: "T1134.001", "T1134.002"
    REQUIRES: "lateral_session"
    OUTPUTS:  "privesc_vectors"
    """
    MODULE_ID          = "windows.token_impersonation"
    MODULE_NAME        = "Token Impersonation"
    MODULE_CATEGORY    = "windows"
    MODULE_DESCRIPTION = (
        "Detect SeImpersonatePrivilege on current session - "
        "prerequisite check for Potato-family privilege escalation attacks"
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.MEDIUM
    REQUIRES           = ["lateral_session"]
    OUTPUTS            = ["privesc_vectors"]
    MITRE_TECHNIQUES   = ["T1134.001", "T1134.002"]
    PARAMS_MODEL       = TokenImpersonationParams
    ENABLED            = False
    DISABLED_REASON    = "module disabled: privilege check heuristic insufficient, named pipe != exploitation confirmed (MOD-030)"

    async def assess_feasibility(self, ctx: "Any") -> "FeasibilityReport":  # noqa: F821
        """Pre-flight Defense Feasibility Assessment: Disabled under MOD-030."""
        from ares.modules.base import FeasibilityReport
        return FeasibilityReport(
            feasible=False,
            score=0.0,
            risk_level="high_noise",
            blockers=[self.DISABLED_REASON],
            recommended_alternatives=["windows.lsass_dump", "windows.lsa_secrets"],
            details={"disabled": True, "reason": self.DISABLED_REASON},
        )

    async def validate(self, ctx: "Any") -> None:
        from ares.core.errors import ModuleValidationError
        raise ModuleValidationError(
            self.DISABLED_REASON,
            module_id=self.MODULE_ID,
        )

    async def execute(self, ctx: "Any") -> "ModuleResult":
        """ExecutionContext-based entry point (v0.9.0+): Disabled under MOD-030."""
        from ares.core.errors import ModuleError
        raise ModuleError(
            self.DISABLED_REASON,
            module_id=self.MODULE_ID,
        )
        target   = getattr(ctx, "target", "")
        username = ""
        password = ""
        domain   = getattr(ctx, "domain", "")
        extra_params: dict[str, Any] = {}

        params = getattr(ctx, "params", {})
        if isinstance(params, TokenImpersonationParams):
            target = params.target or target
            username = params.username or ""
            password = params.password.get_secret_value() if hasattr(params.password, "get_secret_value") else (params.password or "")
            domain = params.domain or domain
        elif isinstance(params, dict):
            target = params.get("target") or target
            username = params.get("username", "")
            raw_pass = params.get("password") or params.get("secret", "")
            password = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else (raw_pass or "")
            domain = params.get("domain") or domain
            extra_params = {k: v for k, v in params.items() if k not in ("target", "username", "password", "secret", "domain")}

        findings, raw = await self.run(
            target=target, username=username, password=password, domain=domain,
            **extra_params
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for finding in findings:
            ev = EvidenceRecord(
                artifact_id=f"windows-token-{target.replace('.', '-')}",
                source_target=target,
                collected_by=self.MODULE_ID,
                data={
                    "target": target,
                    "title": finding.title,
                    "severity": str(finding.severity),
                },
                tags=["windows", "token_impersonation"],
            )
            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
        token_target = target or "TargetHost"
        kql_query = (
            "// ARES Closed-Loop Telemetry: Detect Token Impersonation & Privilege Escalation\n"
            "// Detects Security Event 4673 (Privilege Service Called) for SeImpersonatePrivilege / SeAssignPrimaryTokenPrivilege\n"
            "SecurityEvent\n"
            "| where EventID in (4672, 4673)\n"
            "| where PrivilegeList has \"SeImpersonatePrivilege\" or PrivilegeList has \"SeAssignPrimaryTokenPrivilege\"\n"
            "| project TimeGenerated, Computer, SubjectUserName, PrivilegeList, ProcessName\n"
        )
        sigma_rule = (
            f"title: Token Impersonation Privilege Exploitation ({token_target})\n"
            f"id: 7a8b9c0d-ares-token-{abs(hash(token_target)) % 1000000:06d}\n"
            f"status: experimental\n"
            f"description: Detects exploitation of SeImpersonatePrivilege to escalate privileges to SYSTEM via named pipes or RPC.\n"
            f"logsource:\n"
            f"  product: windows\n"
            f"  service: security\n"
            f"detection:\n"
            f"  selection:\n"
            f"    EventID: 4673\n"
            f"    PrivilegeList|contains: 'SeImpersonatePrivilege'\n"
            f"  condition: selection\n"
            f"level: high\n"
            f"tags:\n"
            f"  - attack.privilege_escalation\n"
            f"  - attack.t1134.001\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): Token Impersonation ({token_target})",
                    "loot_type": "detection_rule_kql",
                    "description": "Microsoft Sentinel KQL query for detecting SeImpersonatePrivilege exploitation",
                    "content": {"kql": kql_query, "target": token_target},
                    "tags": ["detection", "kql", "sentinel", "blue_team"],
                },
                {
                    "name": f"Detection Rule (Sigma): Token Impersonation ({token_target})",
                    "loot_type": "detection_rule_sigma",
                    "description": "Sigma detection rule for SeImpersonatePrivilege exploitation",
                    "content": {"sigma": sigma_rule, "target": token_target},
                    "tags": ["detection", "sigma", "blue_team"],
                },
            ])
        raw["loot"] = loot_items
        raw["se_impersonate_privilege_evaluated"] = True
        raw["named_pipe_coercion_audited"] = 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("windows.token_impersonation")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        from ares.core.errors import ModuleError
        raise ModuleError(
            self.DISABLED_REASON,
            module_id=self.MODULE_ID,
        )

        target   = sanitize_hostname(kwargs.get("target", ""))
        username = kwargs.get("username", "")
        password = kwargs.get("password", "") or kwargs.get("secret", "")
        domain   = kwargs.get("domain", "")
        dry_run  = kwargs.get("dry_run", False)

        if not target:
            return [], {"error": "no_target"}
        if dry_run:
            return [], {"dry_run": True}

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

        try:
            from impacket.smbconnection import SMBConnection
        except ImportError:
            return [], {"error": "impacket not installed - pip install ares-redteam[ad]"}

        logger.info("token_impersonation_check", target=target, username=username)
        from ares.core.logger import audit as _audit
        _audit("token_impersonation", actor=username, source="operator",
               target=target, technique="T1134.001")
        await self.noise.rate_limiter.acquire("smb")
        await self.noise.jitter.sleep()

        # Reveal NTLM hash if provided instead of cleartext
        lmhash, nthash = "", ""
        if password and len(password) in (32, 65) and ":" in password or len(password) == 32:
            parts = password.split(":")
            if len(parts) == 2:
                lmhash, nthash = parts[0], parts[1]
            else:
                nthash = password
            password = ""

        # Run whoami /priv via WMI to check SeImpersonatePrivilege
        privs_output = ""  # noqa: F841
        loop = asyncio.get_running_loop()
        try:
            from impacket.dcerpc.v5 import transport, wmi

            def _check_privs() -> str:
                try:
                    smb = SMBConnection(target, target, timeout=10)
                    smb.login(username, password, domain, lmhash, nthash)
                    # Use WMI to run whoami /priv
                    string_binding = f"ncacn_ip_tcp:{target}[135]"
                    rpctransport   = transport.DCERPCTransportFactory(string_binding)
                    rpctransport.set_credentials(username, password, domain, lmhash, nthash)
                    dce = rpctransport.get_dce_rpc()
                    dce.connect()
                    dce.bind(wmi.MSRPC_UUID_WMI)
                    # Query Win32_Process
                    wmi_iface = wmi.WMIInterface(dce)
                    query     = "SELECT * FROM Win32_Process WHERE Name = 'lsass.exe'"
                    results   = wmi_iface.ExecQuery(query)  # noqa: F841
                    # Just connectivity check - real priv check via WMI is complex
                    return "connected"
                except Exception as e:
                    return str(e)[:200]

            result = await loop.run_in_executor(None, _check_privs)
        except Exception as e:
            result = str(e)[:200]

        # Audit Named Pipes for PrintSpoofer / Potato attack vectors
        pipe_results = await loop.run_in_executor(
            None,
            lambda: self._audit_named_pipes_sync(target, username, password, domain, lmhash, nthash),
        )

        # Check for service accounts that commonly have SeImpersonatePrivilege
        # IIS AppPool, Network Service, Local Service
        service_accounts = ["iis apppool", "network service", "local service", "nt service\\", "mssqlserver", "mssql$"]
        has_impersonate_indicator = any(sa in username.lower() for sa in service_accounts)

        impersonation_vectors: list[str] = []

        if pipe_results.get("spoolss"):
            impersonation_vectors.append("PrintSpoofer (\\pipe\\spoolss)")
            if has_impersonate_indicator:
                self.finding(
                    title=f"PrintSpoofer SYSTEM Escalation Vector Confirmed on {target}",
                    description=(
                        f"Account '{username}' on {target} has service account privileges "
                        "and the Print Spooler named pipe (\\pipe\\spoolss) is accessible. "
                        "This allows PrintSpoofer / PipePotato attacks to coerce local RPC authentication "
                        "from NT AUTHORITY\\SYSTEM across the named pipe, providing immediate SYSTEM privileges."
                    ),
                    severity=Severity.CRITICAL,
                    mitre_technique="T1134.001",
                    mitre_tactic="Privilege Escalation",
                    evidence={
                        "target": target,
                        "account": username,
                        "named_pipe": "\\pipe\\spoolss",
                        "exploit_vector": "PrintSpoofer / PipePotato",
                        "prerequisite": "SeImpersonatePrivilege + Spooler Pipe",
                    },
                    remediation=(
                        "Disable the Print Spooler service if printing is not required: "
                        "Stop-Service -Name Spooler -Force; Set-Service -Name Spooler -StartupType Disabled. "
                        "Ensure service accounts do not hold SeImpersonatePrivilege unless strictly necessary."
                    ),
                    host=target,
                    confidence=0.95,
                )
            else:
                self.finding(
                    title=f"Print Spooler Named Pipe Accessible on {target} (PrintSpoofer Vector)",
                    description=(
                        f"The Print Spooler named pipe (\\pipe\\spoolss) is open and responsive on {target}. "
                        "Any process executing with SeImpersonatePrivilege (e.g. IIS AppPool, SQL Server, Local Service) "
                        "can exploit PrintSpoofer to escalate privileges to SYSTEM."
                    ),
                    severity=Severity.HIGH,
                    mitre_technique="T1134.001",
                    mitre_tactic="Privilege Escalation",
                    evidence={
                        "target": target,
                        "named_pipe": "\\pipe\\spoolss",
                        "vector": "PrintSpoofer",
                    },
                    remediation="Disable Print Spooler on non-print-servers to remove the local coercion surface.",
                    host=target,
                    confidence=0.85,
                )

        if pipe_results.get("efsrpc"):
            impersonation_vectors.append("EfsPotato / PetitPotam Local (\\pipe\\efsrpc)")

        if has_impersonate_indicator and not pipe_results.get("spoolss"):
            self.finding(
                title=f"SeImpersonatePrivilege Likely Present on {target}",
                description=(
                    f"Account '{username}' on {target} is a service account type that "
                    "typically holds SeImpersonatePrivilege. "
                    "This enables Potato-family attacks (GodPotato, RoguePotato, "
                    "PrintSpoofer) to escalate to SYSTEM."
                ),
                severity=Severity.HIGH,
                mitre_technique="T1134.001",
                mitre_tactic="Privilege Escalation",
                evidence={"target": target, "account": username,
                           "technique": "Potato family (GodPotato/RoguePotato/PrintSpoofer)"},
                remediation=(
                    "Remove SeImpersonatePrivilege from service accounts where not required. "
                    "Use virtual accounts or Group Managed Service Accounts (gMSA) instead. "
                    "Enable Windows Defender Credential Guard."
                ),
                host=target, confidence=0.75,
            )

        raw = {
            "target": target,
            "account": username,
            "result": result,
            "has_impersonate_indicator": has_impersonate_indicator,
            "named_pipes_checked": pipe_results,
            "impersonation_vectors": impersonation_vectors,
        }
        raw["privesc_vectors"] = self._findings  # OUTPUTS key
        return self._findings[:], raw

    def _audit_named_pipes_sync(
        self, target: str, username: str, password: str, domain: str,
        lmhash: str = "", nthash: str = "",
    ) -> dict[str, bool]:
        """
        Non-destructive SMB named pipe accessibility probe.
        Checks for pipes frequently used in privilege escalation and coercion:
        - spoolss: Print Spooler pipe (enables PrintSpoofer / PipePotato)
        - efsrpc: Encrypting File System RPC (enables EfsPotato / PetitPotam local coercion)
        - svcctl: Service Control Manager RPC pipe
        - samr: Security Account Manager RPC pipe
        """
        accessible_pipes: dict[str, bool] = {
            "spoolss": False,
            "efsrpc": False,
            "svcctl": False,
            "samr": False,
        }
        try:
            from impacket.dcerpc.v5 import transport
            from impacket.smbconnection import SMBConnection

            smb = SMBConnection(target, target, timeout=10)
            smb.login(username, password, domain, lmhash, nthash)

            pipes_to_test = [
                ("spoolss", "\\pipe\\spoolss"),
                ("efsrpc", "\\pipe\\efsrpc"),
                ("svcctl", "\\pipe\\svcctl"),
                ("samr", "\\pipe\\samr"),
            ]

            for pipe_name, pipe_path in pipes_to_test:
                try:
                    rpc_trans = transport.DCERPCTransportFactory(f"ncacn_np:{target}[{pipe_path}]")
                    rpc_trans.set_smb_connection(smb)
                    dce = rpc_trans.get_dce_rpc()
                    dce.connect()
                    accessible_pipes[pipe_name] = True
                    try:
                        dce.disconnect()
                    except Exception:
                        pass
                except Exception:
                    pass

            try:
                smb.logoff()
            except Exception:
                pass
        except Exception as exc:
            logger.debug("named_pipe_audit_failed", target=target, error=str(exc)[:80])

        return accessible_pipes