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(integrity): pivot no-backend raises error not phantom active (MOD-019)
Mafifrizi811cca7b23df
diff --git a/ares/modules/network/pivot.py b/ares/modules/network/pivot.pyindex 6555787..34715e9 100644--- a/ares/modules/network/pivot.py+++ b/ares/modules/network/pivot.py@@ -27,6 +27,7 @@ import inspectfrom typing import Anyfrom ares.core.campaign import Finding, Severity+from ares.core.errors import ModuleExecutionErrorfrom ares.core.logger import audit, get_loggerfrom ares.core.security import sanitize_hostnamefrom ares.modules.base import BaseModule, OpsecLevel@@ -295,6 +296,8 @@ class PivotModule(BaseModule):reachable_subnets = reachable_subnets or [],key_path = key_path,)+ except ModuleExecutionError:+ raiseexcept Exception as exc:raise self._classify_error(exc) from excdiff --git a/ares/pivot/infrastructure.py b/ares/pivot/infrastructure.pyindex 820f0cc..6eda295 100644--- a/ares/pivot/infrastructure.py+++ b/ares/pivot/infrastructure.py@@ -25,6 +25,7 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any+from ares.core.errors import ModuleExecutionErrorfrom ares.core.logger import audit, get_loggerlogger = get_logger("ares.pivot")@@ -257,19 +258,29 @@ class PivotManager:logger.info("socks5_subprocess_established",pivot=pivot_host, local_port=local_port)else:- # asyncssh not installed and no ssh binary - record as active- # (operator must establish tunnel externally)- tunnel.state = TunnelState.ACTIVE- logger.warning("socks5_no_backend_available",- pivot=pivot_host,- hint="Install asyncssh: pip install asyncssh")+ tunnel.state = TunnelState.DEAD+ raise ModuleExecutionError(+ "No SSH backend available: asyncssh not installed and "+ "no 'ssh' binary found in PATH. Cannot establish tunnel. "+ "Install: pip install asyncssh"+ )+ except ModuleExecutionError:+ raiseexcept (OSError, ImportError) as exc:tunnel.state = TunnelState.DEADlogger.error("socks5_establishment_failed", pivot=pivot_host, error=str(exc))+ raise ModuleExecutionError(+ f"Failed to establish SOCKS5 tunnel: {exc}"+ ) from exc+ except ModuleExecutionError:+ raiseexcept Exception as exc:tunnel.state = TunnelState.DEADlogger.error("socks5_asyncssh_failed", pivot=pivot_host, error=str(exc)[:200])+ raise ModuleExecutionError(+ f"Failed to establish SOCKS5 tunnel via asyncssh: {exc}"+ ) from excself._tunnels[tunnel.tunnel_id] = tunnelif tunnel.state == TunnelState.ACTIVE:@@ -366,12 +377,21 @@ class PivotManager:tunnel._proc = proctunnel.state = TunnelState.ACTIVEelse:- tunnel.state = TunnelState.ACTIVE- logger.warning("local_fwd_no_backend", hint="pip install asyncssh")+ tunnel.state = TunnelState.DEAD+ raise ModuleExecutionError(+ "No SSH backend available: asyncssh not installed and "+ "no 'ssh' binary found in PATH. Cannot establish tunnel. "+ "Install: pip install asyncssh"+ )+ except ModuleExecutionError:+ raiseexcept Exception as exc:tunnel.state = TunnelState.DEADlogger.error("local_fwd_failed", error=str(exc)[:200])+ raise ModuleExecutionError(+ f"Failed to establish local port forward: {exc}"+ ) from excself._tunnels[tunnel.tunnel_id] = tunnelif tunnel.state == TunnelState.ACTIVE:diff --git a/tests/unit/pivot/test_pivot_no_backend_mod019.py b/tests/unit/pivot/test_pivot_no_backend_mod019.pynew file mode 100644index 0000000..80a36a6--- /dev/null+++ b/tests/unit/pivot/test_pivot_no_backend_mod019.py@@ -0,0 +1,93 @@+"""+Tests for MOD-019: network.pivot & PivotManager phantom active status fix.+Verifies:+1. ModuleExecutionError is raised when neither asyncssh nor ssh binary is available.+2. TunnelState never becomes ACTIVE without a successful backend connection.+3. PivotModule does not publish a successful SOCKS5 pivot finding if backend is unavailable.+"""++from unittest.mock import AsyncMock, MagicMock, patch+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.errors import ModuleExecutionError+from ares.core.noise import NoiseController+from ares.modules.network.pivot import PivotModule+from ares.pivot.infrastructure import PivotManager, TunnelState+++def _make_pivot_module():+ settings = AresSettings(+ ares_secret_key="test-secret-key-32chars-minimum!!",+ ares_encryption_key="test-encryption-key-32chars-min!!",+ )+ campaign = Campaign(+ name="Pivot-MOD019-Test",+ operator="test_operator",+ scope=[ScopeEntry(cidr="10.0.0.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return PivotModule(settings=settings, campaign=campaign, noise=noise)+++async def test_socks5_no_backend_raises_module_execution_error():+ """Verify establish_socks5 raises ModuleExecutionError when no backend is present."""+ pm = PivotManager(operator="test_op")++ with patch.dict("sys.modules", {"asyncssh": None}), \+ patch("shutil.which", return_value=None):+ with pytest.raises(ModuleExecutionError) as exc_info:+ await pm.establish_socks5(+ pivot_host="10.0.0.5",+ username="root",+ secret="pass",+ local_port=1080,+ )+ assert "No SSH backend available" in str(exc_info.value)++ # TunnelState must never be ACTIVE+ assert pm.active_tunnels() == []+++async def test_local_forward_no_backend_raises_module_execution_error():+ """Verify establish_local_forward raises ModuleExecutionError when no backend is present."""+ pm = PivotManager(operator="test_op")++ with patch.dict("sys.modules", {"asyncssh": None}), \+ patch("shutil.which", return_value=None):+ with pytest.raises(ModuleExecutionError) as exc_info:+ await pm.establish_local_forward(+ pivot_host="10.0.0.5",+ username="root",+ secret="pass",+ remote_host="10.0.0.20",+ remote_port=80,+ local_port=8080,+ )+ assert "No SSH backend available" in str(exc_info.value)++ assert pm.active_tunnels() == []+++async def test_pivot_module_run_no_backend_no_phantom_finding():+ """Verify PivotModule.run raises ModuleExecutionError and emits no phantom active finding."""+ mod = _make_pivot_module()++ with patch.dict("sys.modules", {"asyncssh": None}), \+ patch("shutil.which", return_value=None):+ with pytest.raises(ModuleExecutionError):+ await mod.run(+ target="10.0.0.5",+ username="root",+ secret="password",+ local_port=1080,+ )++ # No findings should have been recorded as active SOCKS5+ active_findings = [f for f in mod._findings if "SOCKS5 Pivot Established" in f.title]+ assert len(active_findings) == 0diff --git a/tests/unit/test_executor_pivot_lateral.py b/tests/unit/test_executor_pivot_lateral.pyindex 06f1182..7d758b0 100644--- a/tests/unit/test_executor_pivot_lateral.py+++ b/tests/unit/test_executor_pivot_lateral.py@@ -212,21 +212,21 @@ class TestPivotManager:@pytest.mark.asyncioasync def test_establish_socks5_no_asyncssh_no_ssh_binary(self):- """Without asyncssh and no ssh binary, tunnel is still registered."""+ """Without asyncssh and no ssh binary, ModuleExecutionError is raised (MOD-019)."""+ from ares.core.errors import ModuleExecutionErrorpm = self._make_pm()with patch.dict("sys.modules", {"asyncssh": None}), \patch("shutil.which", return_value=None):- tunnel = await pm.establish_socks5(- pivot_host="10.0.0.5",- username="root",- secret="pass",- local_port=1080,- )-- assert tunnel.pivot_host == "10.0.0.5"- assert tunnel.local_port == 1080- assert tunnel.tunnel_id in pm._tunnels+ with pytest.raises(ModuleExecutionError) as exc_info:+ await pm.establish_socks5(+ pivot_host="10.0.0.5",+ username="root",+ secret="pass",+ local_port=1080,+ )+ assert "No SSH backend available" in str(exc_info.value)+ assert pm.active_tunnels() == []@pytest.mark.asyncioasync def test_establish_socks5_asyncssh_success(self):@@ -274,8 +274,12 @@ class TestPivotManager:@pytest.mark.asyncioasync def test_teardown_removes_tunnel(self):pm = self._make_pm()- with patch.dict("sys.modules", {"asyncssh": None}), \- patch("shutil.which", return_value=None):+ mock_asyncssh = MagicMock()+ mock_conn = AsyncMock()+ mock_conn.forward_socks = AsyncMock(return_value=MagicMock())+ mock_asyncssh.connect = AsyncMock(return_value=mock_conn)++ with patch.dict("sys.modules", {"asyncssh": mock_asyncssh}):tunnel = await pm.establish_socks5("10.0.0.5", "root", "pass", 1080)tid = tunnel.tunnel_id@@ -291,8 +295,12 @@ class TestPivotManager:@pytest.mark.asyncioasync def test_proxy_for_target_matches_subnet(self):pm = self._make_pm()- with patch.dict("sys.modules", {"asyncssh": None}), \- patch("shutil.which", return_value=None):+ mock_asyncssh = MagicMock()+ mock_conn = AsyncMock()+ mock_conn.forward_socks = AsyncMock(return_value=MagicMock())+ mock_asyncssh.connect = AsyncMock(return_value=mock_conn)++ with patch.dict("sys.modules", {"asyncssh": mock_asyncssh}):tunnel = await pm.establish_socks5("10.0.0.5", "root", "pass", 1080,reachable_subnets=["192.168.1.0/24"],@@ -329,8 +337,12 @@ class TestPivotManager:@pytest.mark.asyncioasync def test_generate_proxychains_config_with_tunnel(self):pm = self._make_pm()- with patch.dict("sys.modules", {"asyncssh": None}), \- patch("shutil.which", return_value=None):+ mock_asyncssh = MagicMock()+ mock_conn = AsyncMock()+ mock_conn.forward_socks = AsyncMock(return_value=MagicMock())+ mock_asyncssh.connect = AsyncMock(return_value=mock_conn)++ with patch.dict("sys.modules", {"asyncssh": mock_asyncssh}):await pm.establish_socks5("10.0.0.5", "root", "pass", 1080)cfg = pm.generate_proxychains_config()