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.

feat(windows): implement Credential Guard posture, Named Pipe audit, and Driver Blocklist check (Wave 3)

Mafifrizi32d69ae2725e
diff --git a/ares/modules/windows/lsass_dump.py b/ares/modules/windows/lsass_dump.py
index 38a572a..e50829a 100644
--- a/ares/modules/windows/lsass_dump.py
+++ b/ares/modules/windows/lsass_dump.py
@@ -221,6 +221,7 @@ class LsassDumpModule(BaseModule):
domain = getattr(ctx, "domain", "")
technique = "comsvcs"
+ force = False
params = getattr(ctx, "params", {})
if isinstance(params, LsassDumpParams):
target = params.target or target
@@ -228,6 +229,7 @@ class LsassDumpModule(BaseModule):
password = params.password.get_secret_value() if hasattr(params.password, "get_secret_value") else (params.password or "")
domain = params.domain or domain
technique = params.technique or "comsvcs"
+ force = getattr(params, "force", False)
elif isinstance(params, dict):
target = params.get("target") or target
username = params.get("username", "")
@@ -235,6 +237,7 @@ class LsassDumpModule(BaseModule):
password = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else (raw_pass or "")
domain = params.get("domain") or domain
technique = params.get("technique", "comsvcs")
+ force = bool(params.get("force", False))
target = sanitize_hostname(target)
@@ -251,6 +254,7 @@ class LsassDumpModule(BaseModule):
findings, raw = await self.run(
target=target, username=username, password=password,
domain=domain, lmhash=lmhash, nthash=nthash, technique=technique,
+ force=force,
)
# Cryptographic Evidence Records with SHA-256 Merkle Provenance
@@ -334,7 +338,7 @@ class LsassDumpModule(BaseModule):
@trace_module("windows.lsass_dump")
async def run(self, target: str, username: str, password: str = "",
domain: str = "", lmhash: str = "", nthash: str = "",
- technique: str = "comsvcs", **kwargs: Any):
+ technique: str = "comsvcs", force: bool = False, **kwargs: Any):
await self.before_request(target, "default")
logger.warning("lsass_dump_start", target=target, technique=technique,
msg="HIGH_NOISE - EDR_ALERT_LIKELY")
@@ -343,6 +347,64 @@ class LsassDumpModule(BaseModule):
loop = asyncio.get_running_loop()
+ # 1. Probe Credential Guard & RunAsPPL protections before attempting dump
+ protections = await loop.run_in_executor(
+ None,
+ lambda: self._check_lsass_protections_sync(target, username, password, domain, lmhash, nthash),
+ )
+
+ if (protections.get("runasppl") or protections.get("credential_guard") or protections.get("vbs")) and not force:
+ active_mitigations = []
+ if protections.get("runasppl"):
+ active_mitigations.append("RunAsPPL (LSA Protected Process Light)")
+ if protections.get("credential_guard"):
+ active_mitigations.append("Credential Guard (LsaIso.exe VBS Isolation)")
+ if protections.get("vbs") and not protections.get("credential_guard"):
+ active_mitigations.append("Virtualization-Based Security (VBS)")
+
+ mitigations_str = " + ".join(active_mitigations)
+ self.finding(
+ title=f"Credential Guard / RunAsPPL Active on {target} (LSASS Memory Protected)",
+ description=(
+ f"Remote posture assessment on {target} confirmed active LSASS hardening: {mitigations_str}. "
+ "Process memory is protected by the Windows kernel (RunAsPPL) and/or isolated in Virtual "
+ "Secure Mode (Credential Guard). Direct memory extraction (comsvcs / procdump / secretsdump) "
+ "is blocked by the kernel and triggers EDR alerts without yielding plaintext secrets."
+ ),
+ severity=Severity.LOW,
+ mitre_technique="T1003.001",
+ mitre_tactic="Credential Access",
+ evidence={
+ "target": target,
+ "active_mitigations": active_mitigations,
+ "protection_details": protections.get("details", {}),
+ "posture_status": "COMPLIANT_HARDENED",
+ },
+ remediation=(
+ "Target is compliant with modern credential protection standards. "
+ "To test alternative attack paths that do not touch LSASS memory: "
+ "1. Evaluate DPAPI secrets via windows.dpapi. "
+ "2. Audit token impersonation vectors via windows.token_impersonation. "
+ "3. Perform offline registry extraction (SAM/SECURITY) via windows.lsa_secrets. "
+ "4. Execute Kerberoasting via ad.kerberoast."
+ ),
+ host=target,
+ confidence=1.0,
+ )
+
+ raw = {
+ "target": target,
+ "technique": technique,
+ "hash_count": 0,
+ "hashes": [],
+ "ntlm_hashes": [],
+ "kerberos_tickets": [],
+ "protections": protections,
+ "mitigated": True,
+ }
+ await self.noise.jitter.sleep()
+ return self._findings[:], raw
+
if technique == "secretsdump":
# Direct via impacket - no touch disk, requires DA
hashes = await loop.run_in_executor(
@@ -393,6 +455,8 @@ class LsassDumpModule(BaseModule):
"hashes": [{"username": h["username"], "rid": h.get("rid", ""),
"nt_hash": h["nt_hash"]}
for h in hashes],
+ "protections": protections,
+ "mitigated": False,
}
raw["ntlm_hashes"] = raw.get("hashes", []) # OUTPUTS key
@@ -400,6 +464,94 @@ class LsassDumpModule(BaseModule):
await self.noise.jitter.sleep()
return self._findings[:], raw
+ def _check_lsass_protections_sync(
+ self, target: str, username: str, password: str, domain: str,
+ lmhash: str, nthash: str,
+ ) -> dict[str, Any]:
+ """
+ Query remote registry for LSASS Protection (RunAsPPL) and Virtualization-Based Security (Credential Guard).
+ HKLM\\SYSTEM\\CurrentControlSet\\Control\\Lsa -> RunAsPPL, RunAsPPLBoot, LsaCfgFlags
+ HKLM\\SYSTEM\\CurrentControlSet\\Control\\DeviceGuard -> EnableVirtualizationBasedSecurity
+ """
+ res: dict[str, Any] = {
+ "runasppl": False,
+ "credential_guard": False,
+ "vbs": False,
+ "details": {},
+ }
+ try:
+ from impacket.smbconnection import SMBConnection
+ from impacket.dcerpc.v5 import transport, rrp
+ from impacket.dcerpc.v5.rrp import (
+ hOpenLocalMachine, hBaseRegOpenKey, hBaseRegQueryValue,
+ hBaseRegCloseKey, DCERPCException,
+ )
+
+ smb = SMBConnection(target, target, timeout=10)
+ smb.login(username, password, domain, lmhash, nthash)
+
+ rpc_transport = transport.DCERPCTransportFactory(f"ncacn_np:{target}[\\pipe\\winreg]")
+ rpc_transport.set_smb_connection(smb)
+ dce = rpc_transport.get_dce_rpc()
+ dce.connect()
+ dce.bind(rrp.MSRPC_UUID_RRP)
+
+ hklm = hOpenLocalMachine(dce)["phKey"]
+
+ # 1. Check LSA registry keys
+ try:
+ lsa_key = hBaseRegOpenKey(dce, hklm, "SYSTEM\\CurrentControlSet\\Control\\Lsa")["phkResult"]
+ for val_name in ("RunAsPPL", "RunAsPPLBoot", "LsaCfgFlags"):
+ try:
+ val_data = hBaseRegQueryValue(dce, lsa_key, val_name)[1]
+ if isinstance(val_data, int):
+ res["details"][val_name] = val_data
+ if val_name in ("RunAsPPL", "RunAsPPLBoot") and val_data in (1, 2):
+ res["runasppl"] = True
+ if val_name == "LsaCfgFlags" and val_data in (1, 2):
+ res["credential_guard"] = True
+ elif isinstance(val_data, bytes) and len(val_data) >= 4:
+ import struct
+ int_val = struct.unpack("<I", val_data[:4])[0]
+ res["details"][val_name] = int_val
+ if val_name in ("RunAsPPL", "RunAsPPLBoot") and int_val in (1, 2):
+ res["runasppl"] = True
+ if val_name == "LsaCfgFlags" and int_val in (1, 2):
+ res["credential_guard"] = True
+ except (DCERPCException, Exception):
+ pass
+ hBaseRegCloseKey(dce, lsa_key)
+ except (DCERPCException, Exception):
+ pass
+
+ # 2. Check DeviceGuard VBS key
+ try:
+ dg_key = hBaseRegOpenKey(dce, hklm, "SYSTEM\\CurrentControlSet\\Control\\DeviceGuard")["phkResult"]
+ try:
+ vbs_val = hBaseRegQueryValue(dce, dg_key, "EnableVirtualizationBasedSecurity")[1]
+ if isinstance(vbs_val, int) and vbs_val == 1:
+ res["vbs"] = True
+ res["details"]["EnableVirtualizationBasedSecurity"] = 1
+ elif isinstance(vbs_val, bytes) and len(vbs_val) >= 4:
+ import struct
+ int_val = struct.unpack("<I", vbs_val[:4])[0]
+ res["details"]["EnableVirtualizationBasedSecurity"] = int_val
+ if int_val == 1:
+ res["vbs"] = True
+ except (DCERPCException, Exception):
+ pass
+ hBaseRegCloseKey(dce, dg_key)
+ except (DCERPCException, Exception):
+ pass
+
+ hBaseRegCloseKey(dce, hklm)
+ dce.disconnect()
+ smb.logoff()
+ except Exception as exc:
+ logger.debug("lsass_protection_check_failed", target=target, error=str(exc)[:80])
+
+ return res
+
def _secretsdump_sync(self, target: str, username: str, password: str,
domain: str, lmhash: str, nthash: str) -> list[dict]:
"""Direct secretsdump via impacket - no touch disk, DA required."""
diff --git a/ares/modules/windows/registry_enum.py b/ares/modules/windows/registry_enum.py
index 53a6cbf..9863269 100644
--- a/ares/modules/windows/registry_enum.py
+++ b/ares/modules/windows/registry_enum.py
@@ -140,6 +140,20 @@ _ENUM_TARGETS: list[tuple[str, str, list[str] | None, str, str]] = [
"UltraVNC stored password",
"HIGH",
),
+ (
+ "HKLM",
+ "SYSTEM\\CurrentControlSet\\Control\\CI\\Config",
+ ["VulnerableDriverBlocklistEnable"],
+ "Microsoft Recommended Driver Blocklist",
+ "HIGH",
+ ),
+ (
+ "HKLM",
+ "SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\\Scenarios\\HypervisorEnforcedCodeIntegrity",
+ ["Enabled"],
+ "Hypervisor-Enforced Code Integrity (HVCI)",
+ "MEDIUM",
+ ),
]
# HKCU paths (per-user) - enumerated under current user context
@@ -324,6 +338,8 @@ class RegistryEnumModule(BaseModule):
"autologon" in str(f).lower() for f in raw.get("cleartext_credentials", [])
)
raw["putty_stored_credentials_found"] = bool(raw.get("putty_sessions"))
+ raw["driver_blocklist_enabled"] = raw.get("driver_blocklist_enabled", False)
+ raw["hvci_enabled"] = raw.get("hvci_enabled", False)
raw["always_install_elevated_risk"] = any(
"alwaysinstallelevated" in str(f).lower() for f in findings
)
@@ -576,9 +592,55 @@ class RegistryEnumModule(BaseModule):
)
# VNC / SNMP / other credential keys
+ driver_blocklist_enabled = False
+ hvci_enabled = False
+
for hit in all_findings:
if "Winlogon" in hit["path"]:
continue # already handled above
+
+ if "CI\\Config" in hit["path"]:
+ val = hit["values"].get("VulnerableDriverBlocklistEnable")
+ is_enabled = False
+ if isinstance(val, int) and val == 1:
+ is_enabled = True
+ elif isinstance(val, str) and val.strip("\x00") in ("1", "0x1"):
+ is_enabled = True
+
+ if is_enabled:
+ driver_blocklist_enabled = True
+ else:
+ self.finding(
+ title=f"Microsoft Recommended Driver Blocklist Disabled on {target} (BYOVD Risk)",
+ description=(
+ f"The Microsoft Recommended Driver Blocklist is disabled or unconfigured on {target}. "
+ "Adversaries with local administrator privileges can load signed vulnerable third-party "
+ "drivers (Bring Your Own Vulnerable Driver - BYOVD) to terminate EDRs, tamper with "
+ "kernel structures, and bypass RunAsPPL."
+ ),
+ severity=Severity.HIGH,
+ mitre_technique="T1068",
+ mitre_tactic="Privilege Escalation",
+ evidence={
+ "host": target,
+ "path": hit["path"],
+ "value": val,
+ "threat_vector": "BYOVD / Kernel Tampering",
+ },
+ remediation=(
+ "Enable the Microsoft Recommended Driver Blocklist via Windows Security or registry: "
+ "reg add HKLM\\SYSTEM\\CurrentControlSet\\Control\\CI\\Config /v VulnerableDriverBlocklistEnable /t REG_DWORD /d 1 /f"
+ ),
+ host=target, confidence=0.95,
+ )
+ continue
+
+ if "HypervisorEnforcedCodeIntegrity" in hit["path"]:
+ val = hit["values"].get("Enabled")
+ if (isinstance(val, int) and val == 1) or (isinstance(val, str) and val.strip("\x00") in ("1", "0x1")):
+ hvci_enabled = True
+ continue
+
sev = _SEV_MAP.get(hit["severity"], Severity.MEDIUM)
self.finding(
title=f"{hit['description']} Found on {target}",
@@ -608,6 +670,32 @@ class RegistryEnumModule(BaseModule):
host=target, confidence=0.95,
)
+ # If CI\Config was not found at all, and there were no general connection errors, report unconfigured blocklist
+ ci_checked = any("CI\\Config" in hit["path"] for hit in all_findings)
+ if not ci_checked and not errors and (all_findings or putty_sessions):
+ self.finding(
+ title=f"Microsoft Recommended Driver Blocklist Unconfigured on {target} (BYOVD Risk)",
+ description=(
+ f"The Microsoft Recommended Driver Blocklist is not configured on {target}. "
+ "Adversaries with local administrator privileges can load signed vulnerable third-party "
+ "drivers (Bring Your Own Vulnerable Driver - BYOVD) to bypass EDR, tamper with "
+ "kernel memory, and disable endpoint protections."
+ ),
+ severity=Severity.HIGH,
+ mitre_technique="T1068",
+ mitre_tactic="Privilege Escalation",
+ evidence={
+ "host": target,
+ "path": "SYSTEM\\CurrentControlSet\\Control\\CI\\Config",
+ "status": "NOT_CONFIGURED",
+ },
+ remediation=(
+ "Enable the Microsoft Recommended Driver Blocklist via Windows Security or registry: "
+ "reg add HKLM\\SYSTEM\\CurrentControlSet\\Control\\CI\\Config /v VulnerableDriverBlocklistEnable /t REG_DWORD /d 1 /f"
+ ),
+ host=target, confidence=0.9,
+ )
+
# PuTTY sessions
if putty_sessions:
self.finding(
@@ -640,6 +728,8 @@ class RegistryEnumModule(BaseModule):
"target": target,
"credential_hits": all_findings,
"putty_sessions": putty_sessions,
+ "driver_blocklist_enabled": driver_blocklist_enabled,
+ "hvci_enabled": hvci_enabled,
"errors": errors,
}
raw["cleartext_credentials"] = self._findings # OUTPUTS key
diff --git a/ares/modules/windows/token_impersonation.py b/ares/modules/windows/token_impersonation.py
index cedf677..a8243d6 100644
--- a/ares/modules/windows/token_impersonation.py
+++ b/ares/modules/windows/token_impersonation.py
@@ -257,22 +257,31 @@ class TokenImpersonationModule(BaseModule):
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 = ""
+ loop = asyncio.get_running_loop()
try:
from impacket.dcerpc.v5 import transport, wmi # type: ignore[import]
from impacket.dcerpc.v5.dtypes import NULL # type: ignore[import]
- loop = asyncio.get_running_loop()
-
def _check_privs() -> str:
try:
smb = SMBConnection(target, target, timeout=10)
- smb.login(username, password, domain)
+ 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)
+ rpctransport.set_credentials(username, password, domain, lmhash, nthash)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(wmi.MSRPC_UUID_WMI)
@@ -289,25 +298,86 @@ class TokenImpersonationModule(BaseModule):
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\\"]
+ 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)
- if has_impersonate_indicator or result == "connected":
+ 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 (JuicyPotato, RoguePotato, "
+ "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 (JuicyPotato/RoguePotato/PrintSpoofer)"},
+ "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. "
@@ -316,7 +386,68 @@ class TokenImpersonationModule(BaseModule):
host=target, confidence=0.75,
)
- raw = {"target": target, "account": username, "result": result,
- "has_impersonate_indicator": has_impersonate_indicator}
+ 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.smbconnection import SMBConnection
+ from impacket.dcerpc.v5 import transport
+
+ 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
diff --git a/tests/unit/test_windows_resilience.py b/tests/unit/test_windows_resilience.py
new file mode 100644
index 0000000..ca999b7
--- /dev/null
+++ b/tests/unit/test_windows_resilience.py
@@ -0,0 +1,360 @@
+"""
+Unit test suite for Wave 3: Modern Windows Posture & Token Security.
+Verifies:
+ - windows.lsass_dump graceful posture assessment for Credential Guard and RunAsPPL.
+ - windows.lsass_dump force parameter override.
+ - windows.token_impersonation non-destructive Named Pipe audit (spoolss / PrintSpoofer, efsrpc).
+ - windows.registry_enum Microsoft Recommended Driver Blocklist (BYOVD mitigation) and HVCI checks.
+"""
+from __future__ import annotations
+
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
+
+from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry, Severity
+from ares.core.config import AresSettings
+from ares.core.noise import NoiseController
+from ares.modules.windows.lsass_dump import LsassDumpModule
+from ares.modules.windows.token_impersonation import TokenImpersonationModule
+from ares.modules.windows.registry_enum import RegistryEnumModule
+
+
+def mock_impacket_modules():
+ mock_impacket = MagicMock()
+ mock_smb = MagicMock()
+ mock_smb.SMBConnection = MagicMock()
+ mock_transport = MagicMock()
+ mock_rrp = MagicMock()
+ mock_rrp.MSRPC_UUID_RRP = "dummy-uuid"
+ mock_wmi = MagicMock()
+ mock_dtypes = MagicMock()
+ mock_dtypes.NULL = None
+
+ mock_modules = {
+ "impacket": mock_impacket,
+ "impacket.smbconnection": mock_smb,
+ "impacket.dcerpc": MagicMock(),
+ "impacket.dcerpc.v5": MagicMock(),
+ "impacket.dcerpc.v5.transport": mock_transport,
+ "impacket.dcerpc.v5.rrp": mock_rrp,
+ "impacket.dcerpc.v5.wmi": mock_wmi,
+ "impacket.dcerpc.v5.dtypes": mock_dtypes,
+ }
+ with patch.dict(sys.modules, mock_modules):
+ yield mock_modules
+
+
+def _make_module(cls):
+ settings = AresSettings(
+ ares_secret_key="test-secret-key-min32-chars-here!!",
+ ares_encryption_key="test-enc-key-min32-chars-here-xxx",
+ )
+ campaign = Campaign(
+ name="Test-Windows-Wave3",
+ operator="lead_operator",
+ scope=[
+ ScopeEntry(cidr="192.168.0.0/16"),
+ ScopeEntry(cidr="10.0.0.0/8"),
+ ],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ noise = NoiseController(campaign)
+ return cls(settings=settings, campaign=campaign, noise=noise)
+
+
+class TestLsassDumpResilience:
+ """Tests for Credential Guard & RunAsPPL pre-execution posture detection."""
+
+ @pytest.mark.asyncio
+ async def test_credential_guard_detected_graceful_posture(self, mock_impacket_modules):
+ mod = _make_module(LsassDumpModule)
+
+ # Mock remote registry check returning active Credential Guard
+ with patch.object(
+ mod,
+ "_check_lsass_protections_sync",
+ return_value={
+ "runasppl": False,
+ "credential_guard": True,
+ "vbs": True,
+ "details": {"LsaCfgFlags": 1, "EnableVirtualizationBasedSecurity": 1},
+ },
+ ), patch.object(mod, "_comsvcs_dump_sync") as mock_dump:
+ findings, raw = await mod.run(
+ target="192.168.1.10",
+ username="Administrator",
+ password="Password123!",
+ technique="comsvcs",
+ )
+
+ # Dump should NOT have been executed
+ mock_dump.assert_not_called()
+
+ assert raw["mitigated"] is True
+ assert raw["hash_count"] == 0
+ assert raw["hashes"] == []
+ assert raw["protections"]["credential_guard"] is True
+
+ # Hardened posture finding must be generated
+ assert len(findings) == 1
+ f = findings[0]
+ assert "Credential Guard / RunAsPPL Active" in f.title
+ assert f.severity == Severity.LOW
+ assert "192.168.1.10" in f.host
+ assert f.mitre_technique == "T1003.001"
+ assert "COMPLIANT_HARDENED" in str(f.evidence.get("posture_status"))
+
+ @pytest.mark.asyncio
+ async def test_runasppl_detected_graceful_posture(self, mock_impacket_modules):
+ mod = _make_module(LsassDumpModule)
+
+ with patch.object(
+ mod,
+ "_check_lsass_protections_sync",
+ return_value={
+ "runasppl": True,
+ "credential_guard": False,
+ "vbs": False,
+ "details": {"RunAsPPL": 1},
+ },
+ ), patch.object(mod, "_comsvcs_dump_sync") as mock_dump:
+ findings, raw = await mod.run(
+ target="192.168.1.11",
+ username="Administrator",
+ password="Password123!",
+ )
+
+ mock_dump.assert_not_called()
+ assert raw["mitigated"] is True
+ assert any("RunAsPPL" in f.title for f in findings)
+ assert any("RunAsPPL (LSA Protected Process Light)" in f.description for f in findings)
+
+ @pytest.mark.asyncio
+ async def test_force_override_bypasses_protection_check(self, mock_impacket_modules):
+ mod = _make_module(LsassDumpModule)
+
+ fake_hashes = [{"username": "Administrator", "rid": "500", "nt_hash": "aad3b435b51404eeaad3b435b51404ee"}]
+
+ with patch.object(
+ mod,
+ "_check_lsass_protections_sync",
+ return_value={
+ "runasppl": True,
+ "credential_guard": True,
+ "vbs": True,
+ "details": {},
+ },
+ ), patch.object(mod, "_comsvcs_dump_sync", return_value=fake_hashes) as mock_dump:
+ findings, raw = await mod.run(
+ target="192.168.1.12",
+ username="Administrator",
+ password="Password123!",
+ force=True,
+ )
+
+ # When force=True, dump must be called despite protections
+ mock_dump.assert_called_once()
+ assert raw["mitigated"] is False
+ assert raw["hash_count"] == 1
+ assert any("LSASS Dump" in f.title for f in findings)
+
+ @pytest.mark.asyncio
+ async def test_unprotected_target_executes_normal_dump(self, mock_impacket_modules):
+ mod = _make_module(LsassDumpModule)
+
+ fake_hashes = [
+ {"username": "Administrator", "rid": "500", "nt_hash": "329153f560eb329c0e1deea55e88a1e9"},
+ {"username": "krbtgt", "rid": "502", "nt_hash": "a5e88a1e9329153f560eb329c0e1dee1"},
+ ]
+
+ with patch.object(
+ mod,
+ "_check_lsass_protections_sync",
+ return_value={"runasppl": False, "credential_guard": False, "vbs": False, "details": {}},
+ ), patch.object(mod, "_comsvcs_dump_sync", return_value=fake_hashes):
+ findings, raw = await mod.run(
+ target="192.168.1.13",
+ username="Administrator",
+ password="Password123!",
+ )
+
+ assert raw["mitigated"] is False
+ assert raw["hash_count"] == 2
+ assert any(f.severity == Severity.CRITICAL for f in findings)
+ assert any("Golden Ticket possible" in f.description for f in findings)
+
+
+class TestTokenImpersonationNamedPipes:
+ """Tests for Named Pipe audit and PrintSpoofer / Potato attack vector detection."""
+
+ @pytest.mark.asyncio
+ async def test_printspoofer_confirmed_on_service_account(self, mock_impacket_modules):
+ mod = _make_module(TokenImpersonationModule)
+
+ with patch.object(
+ mod,
+ "_audit_named_pipes_sync",
+ return_value={"spoolss": True, "efsrpc": False, "svcctl": True, "samr": True},
+ ):
+ findings, raw = await mod.run(
+ target="192.168.1.20",
+ username="iis apppool\\defaultapppool",
+ password="Password123!",
+ )
+
+ assert raw["named_pipes_checked"]["spoolss"] is True
+ assert "PrintSpoofer (\\pipe\\spoolss)" in raw["impersonation_vectors"]
+
+ # Must generate CRITICAL confirmed vector finding
+ critical_finding = next((f for f in findings if f.severity == Severity.CRITICAL), None)
+ assert critical_finding is not None
+ assert "PrintSpoofer SYSTEM Escalation Vector Confirmed" in critical_finding.title
+ assert critical_finding.evidence.get("exploit_vector") == "PrintSpoofer / PipePotato"
+
+ @pytest.mark.asyncio
+ async def test_spooler_pipe_accessible_normal_user_vector(self, mock_impacket_modules):
+ mod = _make_module(TokenImpersonationModule)
+
+ with patch.object(
+ mod,
+ "_audit_named_pipes_sync",
+ return_value={"spoolss": True, "efsrpc": True, "svcctl": False, "samr": False},
+ ):
+ findings, raw = await mod.run(
+ target="192.168.1.21",
+ username="normal_user",
+ password="Password123!",
+ )
+
+ assert raw["named_pipes_checked"]["spoolss"] is True
+ assert "PrintSpoofer (\\pipe\\spoolss)" in raw["impersonation_vectors"]
+ assert "EfsPotato / PetitPotam Local (\\pipe\\efsrpc)" in raw["impersonation_vectors"]
+
+ # Generates HIGH finding alerting to Spooler exposure
+ spool_finding = next((f for f in findings if "Print Spooler Named Pipe Accessible" in f.title), None)
+ assert spool_finding is not None
+ assert spool_finding.severity == Severity.HIGH
+
+ @pytest.mark.asyncio
+ async def test_service_account_without_spooler_reports_potato(self, mock_impacket_modules):
+ mod = _make_module(TokenImpersonationModule)
+
+ with patch.object(
+ mod,
+ "_audit_named_pipes_sync",
+ return_value={"spoolss": False, "efsrpc": False, "svcctl": False, "samr": False},
+ ):
+ findings, raw = await mod.run(
+ target="192.168.1.22",
+ username="nt service\\mssql$sqlexpress",
+ password="Password123!",
+ )
+
+ assert raw["has_impersonate_indicator"] is True
+ assert any("SeImpersonatePrivilege Likely Present" in f.title for f in findings)
+
+
+class TestRegistryEnumDriverBlocklist:
+ """Tests for Microsoft Recommended Driver Blocklist and HVCI posture audits."""
+
+ @pytest.mark.asyncio
+ async def test_driver_blocklist_enabled(self, mock_impacket_modules):
+ mod = _make_module(RegistryEnumModule)
+
+ fake_hits = [
+ {
+ "hive": "HKLM",
+ "path": "SYSTEM\\CurrentControlSet\\Control\\CI\\Config",
+ "values": {"VulnerableDriverBlocklistEnable": 1},
+ "description": "Microsoft Recommended Driver Blocklist",
+ "severity": "HIGH",
+ },
+ {
+ "hive": "HKLM",
+ "path": "SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\\Scenarios\\HypervisorEnforcedCodeIntegrity",
+ "values": {"Enabled": 1},
+ "description": "Hypervisor-Enforced Code Integrity (HVCI)",
+ "severity": "MEDIUM",
+ },
+ ]
+
+ with patch("asyncio.get_running_loop") as mock_loop:
+ fake_loop = MagicMock()
+ mock_loop.return_value = fake_loop
+ fake_loop.run_in_executor = AsyncMock(return_value={"hits": fake_hits, "putty": [], "errors": []})
+
+ findings, raw = await mod.run(
+ target="192.168.1.30",
+ username="Administrator",
+ password="Password123!",
+ )
+
+ assert raw["driver_blocklist_enabled"] is True
+ assert raw["hvci_enabled"] is True
+ # When enabled, no BYOVD alert should be generated
+ assert not any("Driver Blocklist Disabled" in f.title for f in findings)
+
+ @pytest.mark.asyncio
+ async def test_driver_blocklist_disabled_reports_high_finding(self, mock_impacket_modules):
+ mod = _make_module(RegistryEnumModule)
+
+ fake_hits = [
+ {
+ "hive": "HKLM",
+ "path": "SYSTEM\\CurrentControlSet\\Control\\CI\\Config",
+ "values": {"VulnerableDriverBlocklistEnable": 0},
+ "description": "Microsoft Recommended Driver Blocklist",
+ "severity": "HIGH",
+ }
+ ]
+
+ with patch("asyncio.get_running_loop") as mock_loop:
+ fake_loop = MagicMock()
+ mock_loop.return_value = fake_loop
+ fake_loop.run_in_executor = AsyncMock(return_value={"hits": fake_hits, "putty": [], "errors": []})
+
+ findings, raw = await mod.run(
+ target="192.168.1.31",
+ username="Administrator",
+ password="Password123!",
+ )
+
+ assert raw["driver_blocklist_enabled"] is False
+ byovd_finding = next((f for f in findings if "Driver Blocklist Disabled" in f.title), None)
+ assert byovd_finding is not None
+ assert byovd_finding.severity == Severity.HIGH
+ assert "BYOVD" in byovd_finding.description
+ assert byovd_finding.mitre_technique == "T1068"
+
+ @pytest.mark.asyncio
+ async def test_driver_blocklist_unconfigured_reports_high_finding(self, mock_impacket_modules):
+ mod = _make_module(RegistryEnumModule)
+
+ fake_hits = [
+ {
+ "hive": "HKLM",
+ "path": "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
+ "values": {"AutoAdminLogon": "0"},
+ "description": "AutoLogon credentials",
+ "severity": "CRITICAL",
+ }
+ ]
+
+ with patch("asyncio.get_running_loop") as mock_loop:
+ fake_loop = MagicMock()
+ mock_loop.return_value = fake_loop
+ fake_loop.run_in_executor = AsyncMock(return_value={"hits": fake_hits, "putty": [], "errors": []})
+
+ findings, raw = await mod.run(
+ target="192.168.1.32",
+ username="Administrator",
+ password="Password123!",
+ )
+
+ assert raw["driver_blocklist_enabled"] is False
+ unconf_finding = next((f for f in findings if "Driver Blocklist Unconfigured" in f.title), None)
+ assert unconf_finding is not None
+ assert unconf_finding.severity == Severity.HIGH
+ assert "BYOVD" in unconf_finding.description