ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(security): disable windows.dpapi - stub implementation, vault poisoning risk (MOD-029)
Mafifrizi4edf14fd24fa
diff --git a/ares/modules/windows/dpapi.py b/ares/modules/windows/dpapi.pyindex dc0c2ea..5f5915d 100644--- a/ares/modules/windows/dpapi.py+++ b/ares/modules/windows/dpapi.py@@ -74,124 +74,35 @@ class DPAPIModule(BaseModule):MITRE_TECHNIQUES = ["T1555.004", "T1555.003"]MODULE_TIMEOUT_SECONDS: int | None = 180 # secondsPARAMS_MODEL = DPAPIParams+ ENABLED = False+ DISABLED_REASON = "module disabled: DPAPI decryption not implemented, stub only - false credential injection risk (MOD-029)"async def assess_feasibility(self, ctx: "Any") -> "FeasibilityReport":- """- Pre-flight Defense Feasibility Assessment:- Evaluates credential accessibility, user context, and target host defense posture.- DPAPI operates in user space and does not access LSASS memory, making it an optimal- stealthy alternative when Credential Guard, PPL, or EDR process hooks are active.- """+ """Pre-flight Defense Feasibility Assessment: Disabled under MOD-029."""from ares.modules.base import FeasibilityReport- from ares.core.campaign import NoiseProfile-- 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", ""))- if not target:- blockers.append("No target host specified")- score -= 0.5-- username = getattr(ctx, "params", {}).get("username", "")- mode = getattr(ctx, "params", {}).get("mode", "auto")- password = getattr(ctx, "params", {}).get("password", "") or getattr(ctx, "params", {}).get("secret", "")- nt_hash = getattr(ctx, "params", {}).get("nt_hash", "")- backup_key = getattr(ctx, "params", {}).get("backup_key", "")-- if not username:- cred = getattr(ctx, "best_credential", lambda: None)()- if cred:- username = cred.username- if not password:- password = getattr(cred, "password", "")- if not nt_hash and getattr(cred, "hash", ""):- nt_hash = cred.hash-- if not username:- blockers.append("Target username required for DPAPI blob masterkey resolution")- score -= 0.4- recommendations.extend(["windows.token_impersonation", "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 target has Credential Guard or PPL, DPAPI is the preferred evasion technique!- if host_state.has_defense("credential_guard") or host_state.has_defense("ppl"):- score = min(1.0, score + 0.1)- opsec_tuning["evasion_advantage"] = (- "Target enforces Credential Guard / PPL. DPAPI is optimal because it recovers "- "stored user secrets (browser credentials, Windows Vault, WiFi, RDP) from disk "- "without triggering LSASS memory protections."- )- if host_state.has_defense("edr"):- opsec_tuning["edr_note"] = "EDR active on host: DPAPI avoids process injection; file access is low-noise."-- if mode == "backup" and not backup_key:- blockers.append("Backup key mode selected but no domain backup key provided")- score -= 0.3- recommendations.append("windows.lsa_secrets")-- if mode == "offline" and not (nt_hash or password):- blockers.append("Offline mode requires user NT hash or password for masterkey derivation")- score -= 0.3-- 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.4return 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, "username": username, "mode": mode},+ 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.context import ExecutionContextfrom 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 isinstance(ctx.params, dict) else getattr(ctx.params, "target", ""))- if not target:- raise ModuleValidationError(- "windows.dpapi requires 'target' - IP of target Windows host.",- module_id=self.MODULE_ID, field="target",- )- username = (ctx.params.get("username", "") if isinstance(ctx.params, dict) else getattr(ctx.params, "username", ""))- if not username:- raise ModuleValidationError(- "windows.dpapi requires 'username' - target user whose DPAPI blobs to decrypt.",- module_id=self.MODULE_ID, field="username",- )- await super().validate(ctx)+ raise ModuleValidationError(+ self.DISABLED_REASON,+ module_id=self.MODULE_ID,+ )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})+ """ExecutionContext-based entry point (v0.9.0+): Disabled under MOD-029."""+ from ares.core.errors import ModuleError+ raise ModuleError(+ self.DISABLED_REASON,+ module_id=self.MODULE_ID,+ )target = getattr(ctx, "target", "")username = ""@@ -321,11 +232,16 @@ class DPAPIModule(BaseModule):)@trace_module("windows.dpapi")- async def run(self, target: str, username: str, password: str = "",+ async def run(self, target: str = "", username: str = "", password: str = "",domain: str = "", lmhash: str = "", nthash_login: str = "",target_user: str = "", nt_hash: str = "",backup_key: str = "", mode: str = "auto",campaign_id: str = "", **kwargs: Any):+ from ares.core.errors import ModuleError+ raise ModuleError(+ self.DISABLED_REASON,+ module_id=self.MODULE_ID,+ )await self.before_request(target, "default")logger.info("dpapi_start", target=target, mode=mode, target_user=target_user)diff --git a/tests/unit/test_defense_feasibility_matrix.py b/tests/unit/test_defense_feasibility_matrix.pyindex 2aaf2c5..886add4 100644--- a/tests/unit/test_defense_feasibility_matrix.py+++ b/tests/unit/test_defense_feasibility_matrix.py@@ -168,9 +168,8 @@ class TestDPAPIFeasibility:params={"username": "jdoe", "password": "UserPass123"},)report = await mod.assess_feasibility(ctx)- assert report.feasible is True- assert report.score >= 0.8- assert report.risk_level == "medium"+ assert report.feasible is False+ assert any("MOD-029" in b for b in report.blockers)@pytest.mark.asyncioasync def test_credential_guard_evasion_advantage(self, dummy_settings, test_campaign, test_noise):@@ -187,10 +186,8 @@ class TestDPAPIFeasibility:session=session,)report = await mod.assess_feasibility(ctx)- assert report.feasible is True- assert report.score == 1.0- assert "evasion_advantage" in report.opsec_tuning- assert "Credential Guard" in report.opsec_tuning["evasion_advantage"]+ assert report.feasible is False+ assert any("MOD-029" in b for b in report.blockers)@pytest.mark.asyncioasync def test_backup_mode_without_key_blocks(self, dummy_settings, test_campaign, test_noise):@@ -202,8 +199,8 @@ class TestDPAPIFeasibility:params={"username": "jdoe", "mode": "backup"},)report = await mod.assess_feasibility(ctx)- assert any("Backup key" in b for b in report.blockers)- assert "windows.lsa_secrets" in report.recommended_alternatives+ assert report.feasible is False+ assert any("MOD-029" in b for b in report.blockers)class TestLSASecretsFeasibility:@@ -361,13 +358,10 @@ class TestAttackPlannerDefenseEvasion:)suggestions = planner.suggest(ctx, limit=5)- # DPAPI should rank higher than LSASS dump due to Credential Guard penalty+ # DPAPI is disabled under MOD-029 and must not be suggested by plannersuggested_ids = [s.module_id for s in suggestions]- assert "windows.dpapi" in suggested_ids- dpapi_score = next((s.score for s in suggestions if s.module_id == "windows.dpapi"), None)- lsass_score = next((s.score for s in suggestions if s.module_id == "windows.lsass_dump"), 0.0)- assert dpapi_score is not None- assert dpapi_score > lsass_score+ assert "windows.dpapi" not in suggested_ids+ assert registry.is_disabled("windows.dpapi") is Truedef test_planner_penalizes_psexec_when_edr_monitors_services(self):from ares.goal.planner import AttackPlanner, PlannerContextdiff --git a/tests/unit/test_disabled_modules_batch4.py b/tests/unit/test_disabled_modules_batch4.pynew file mode 100644index 0000000..c5c3f42--- /dev/null+++ b/tests/unit/test_disabled_modules_batch4.py@@ -0,0 +1,104 @@+"""+Tests for disabled Batch 4 modules:+ - windows.dpapi (MOD-029)+ - windows.token_impersonation (MOD-030)+Verifies:+ - Module does not appear in active module lists (all, by_category, list_metadata)+ - Module cannot produce findings+ - Module cannot contaminate the vault+ - Calling run(), execute(), or validate() raises explicit ModuleError / ModuleValidationError+"""+from __future__ import annotations++import asyncio+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.context import ExecutionContext+from ares.core.errors import ModuleError, ModuleValidationError+from ares.core.noise import NoiseController+from ares.core.plugin.loader import PluginLoader+from ares.modules.windows.dpapi import DPAPIModule+++def _run(coro):+ return asyncio.run(coro)+++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-Disabled-Batch4",+ operator="test_operator",+ scope=[ScopeEntry(cidr="10.0.0.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return cls(settings=settings, campaign=campaign, noise=noise), campaign+++class TestDPAPIDisabled:+ def test_dpapi_attributes(self):+ assert DPAPIModule.MODULE_ID == "windows.dpapi"+ assert DPAPIModule.ENABLED is False+ assert "MOD-029" in DPAPIModule.DISABLED_REASON++ def test_dpapi_registry_exclusion(self):+ loader = PluginLoader()+ loader._load_builtin()+ reg = loader.registry++ assert "windows.dpapi" not in [m["id"] for m in reg.list_metadata()]+ assert "windows.dpapi" not in [cls.MODULE_ID for cls in reg.all()]+ assert "windows.dpapi" not in [cls.MODULE_ID for cls in reg.by_category("windows")]+ assert reg.is_disabled("windows.dpapi") is True+ assert "MOD-029" in (reg.get_disabled_reason("windows.dpapi") or "")+ assert "windows.dpapi" not in reg++ def test_dpapi_direct_run_raises_explicit_exception(self):+ mod, _ = _make_module(DPAPIModule)+ with pytest.raises(ModuleError) as exc_info:+ _run(mod.run(target="10.0.0.5", username="target_user", password="secret"))+ assert "module disabled: DPAPI decryption not implemented, stub only - false credential injection risk (MOD-029)" in str(exc_info.value)+ assert len(mod._findings) == 0++ def test_dpapi_execute_raises_explicit_exception(self):+ mod, campaign = _make_module(DPAPIModule)+ ctx = ExecutionContext.build(+ campaign=campaign,+ target="10.0.0.5",+ module_id="windows.dpapi",+ params={"target": "10.0.0.5", "username": "target_user", "password": "secret"},+ )+ with pytest.raises(ModuleError) as exc_info:+ _run(mod.execute(ctx))+ assert "module disabled: DPAPI decryption not implemented, stub only - false credential injection risk (MOD-029)" in str(exc_info.value)+ assert len(mod._findings) == 0++ def test_dpapi_validate_raises_explicit_exception(self):+ mod, campaign = _make_module(DPAPIModule)+ ctx = ExecutionContext.build(+ campaign=campaign,+ target="10.0.0.5",+ module_id="windows.dpapi",+ params={"target": "10.0.0.5", "username": "target_user"},+ )+ with pytest.raises(ModuleValidationError) as exc_info:+ _run(mod.validate(ctx))+ assert "module disabled: DPAPI decryption not implemented, stub only - false credential injection risk (MOD-029)" in str(exc_info.value)++ def test_dpapi_assess_feasibility_reports_disabled(self):+ mod, campaign = _make_module(DPAPIModule)+ ctx = ExecutionContext.build(+ campaign=campaign,+ target="10.0.0.5",+ module_id="windows.dpapi",+ params={"target": "10.0.0.5", "username": "target_user"},+ )+ report = _run(mod.assess_feasibility(ctx))+ assert report.feasible is False+ assert any("MOD-029" in b for b in report.blockers)diff --git a/tests/unit/test_roadmap_modules.py b/tests/unit/test_roadmap_modules.pyindex 4a287cd..f655aa5 100644--- a/tests/unit/test_roadmap_modules.py+++ b/tests/unit/test_roadmap_modules.py@@ -457,32 +457,30 @@ class TestWindowsDPAPI:def test_dry_run(self):from ares.modules.windows.dpapi import DPAPIModule+ from ares.core.errors import ModuleErrormod, _ = _make_module(DPAPIModule)ctx = _mock_ctx(params={"target": "10.0.0.5", "username": "user"})ctx.target = "10.0.0.5"ctx.dry_run = Trueasync def _test():- result = await mod.execute(ctx)- assert result.status == "dry_run"+ with pytest.raises(ModuleError) as exc_info:+ await mod.execute(ctx)+ assert "module disabled: DPAPI decryption not implemented" in str(exc_info.value)_run(_test())def test_auth_error_classified(self):- """SMB login failure must surface as AuthenticationFailed, not generic error."""+ """Disabled module must raise explicit ModuleError on run()."""from ares.modules.windows.dpapi import DPAPIModule- from ares.core.errors import AuthenticationFailed+ from ares.core.errors import ModuleErrormod, _ = _make_module(DPAPIModule)async def _test():- with patch.object(- mod,- "_transfer_dpapi_files",- side_effect=Exception("STATUS_LOGON_FAILURE"),- ):- with pytest.raises((AuthenticationFailed, Exception)):- await mod.run(- target="10.0.0.5", username="user", password="wrong"- )+ with pytest.raises(ModuleError) as exc_info:+ await mod.run(+ target="10.0.0.5", username="user", password="wrong"+ )+ assert "module disabled: DPAPI decryption not implemented" in str(exc_info.value)_run(_test())def test_chrome_parse_returns_list_on_missing_file(self):diff --git a/tests/unit/test_staged_modules.py b/tests/unit/test_staged_modules.pyindex 8ff3313..023b3e5 100644--- a/tests/unit/test_staged_modules.py+++ b/tests/unit/test_staged_modules.py@@ -469,17 +469,13 @@ class TestGhostForgeModule:def test_dpapi_closed_loop_telemetry(self, monkeypatch):from ares.modules.windows.dpapi import DPAPIModule+ from ares.core.errors import ModuleErrormod, _ = _make_module(DPAPIModule)- async def fake_run(*args, **kwargs):- return [], {"masterkeys": [{"guid": "abc-123"}], "loot": []}- monkeypatch.setattr(mod, "run", fake_run)ctx = _mock_ctx(params={"target": "10.0.0.5", "username": "Admin", "password": "Password123!"})ctx.dry_run = False- res = _run(mod.execute(ctx))- assert res.status in ("partial", "success")- assert res.raw.get("domain_backup_key_evaluated") is True- assert any(l["loot_type"] == "detection_rule_kql" for l in res.raw["loot"])- assert any(l["loot_type"] == "detection_rule_sigma" for l in res.raw["loot"])+ with pytest.raises(ModuleError) as exc_info:+ _run(mod.execute(ctx))+ assert "module disabled: DPAPI decryption not implemented" in str(exc_info.value)def test_scheduled_task_closed_loop_telemetry(self, monkeypatch):from ares.modules.persistence.scheduled_task import ScheduledTaskPersistence