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.

fix(integrity): SSHPivot real SOCKS5 dynamic port forwarding (MOD-020)

Mafifrizi255d1f56645d
diff --git a/ares/modules/lateral/modules.py b/ares/modules/lateral/modules.py
index d3c3a40..9102e30 100644
--- a/ares/modules/lateral/modules.py
+++ b/ares/modules/lateral/modules.py
@@ -25,6 +25,7 @@ from enum import Enum
from typing import Any, TYPE_CHECKING
from ares.core.campaign import Campaign, Finding, Severity
+from ares.core.errors import ModuleExecutionError
from ares.core.logger import audit, get_logger
from ares.modules.base import BaseModule, OpsecLevel
from ares.modules.params import (
@@ -1336,23 +1337,109 @@ class SSHPivot(BaseLateralModule):
secret: str,
local_port: int,
ssh_port: int = 22,
+ key_path: str = "",
+ **kwargs: Any,
) -> dict[str, Any]:
"""
- Establish a SOCKS5 proxy through the target host.
- Returns proxy config: {"host": "127.0.0.1", "port": local_port, "type": "socks5"}
+ Establish a real SOCKS5 dynamic port forward through the target host using asyncssh.
+ Returns proxy config: {"host": "127.0.0.1", "port": local_port, "type": "socks5", "via_host": target}
+ Raises ModuleExecutionError if asyncssh is not available or forwarding fails.
"""
- result = await self.move(
- target, username, "", secret,
- command="echo pivot_established",
- socks_port=local_port,
- port=ssh_port,
- )
- if result.success:
- logger.info("socks5_proxy_established",
- target=target, local_port=local_port)
- return {"host": "127.0.0.1", "port": local_port, "type": "socks5",
- "via_host": target}
- return {}
+ try:
+ import asyncssh
+ except ImportError as exc:
+ raise ModuleExecutionError(
+ "asyncssh is not installed. Real SOCKS5 dynamic port forwarding requires asyncssh. "
+ "Install: pip install asyncssh"
+ ) from exc
+
+ if not hasattr(asyncssh, "connect"):
+ raise ModuleExecutionError(
+ "Invalid asyncssh module: connect not found."
+ )
+
+ connect_kwargs: dict[str, Any] = {
+ "host": target,
+ "port": ssh_port,
+ "username": username,
+ "known_hosts": None,
+ }
+ if key_path:
+ connect_kwargs["client_keys"] = [key_path]
+ elif secret.strip().startswith("-----BEGIN"):
+ try:
+ connect_kwargs["client_keys"] = [asyncssh.import_private_key(secret)]
+ except Exception:
+ connect_kwargs["password"] = secret
+ else:
+ connect_kwargs["password"] = secret
+
+ try:
+ conn = await asyncssh.connect(**connect_kwargs)
+ if not hasattr(conn, "forward_socks"):
+ raise ModuleExecutionError(
+ "Installed asyncssh connection does not support forward_socks."
+ )
+ listener = await conn.forward_socks("127.0.0.1", local_port)
+ except ModuleExecutionError:
+ raise
+ except Exception as exc:
+ raise ModuleExecutionError(
+ f"Failed to establish SOCKS5 dynamic port forwarding on 127.0.0.1:{local_port} via {target}: {exc}"
+ ) from exc
+
+ # Keep alive & register to campaign PivotManager for lifecycle management & teardown
+ try:
+ from ares.modules.network.pivot import _PIVOT_MANAGERS
+ from ares.pivot.infrastructure import PivotManager, PivotTunnel, TunnelState, TunnelType
+ campaign_id = getattr(getattr(self, "campaign", None), "id", "default")
+ if campaign_id not in _PIVOT_MANAGERS:
+ _PIVOT_MANAGERS[campaign_id] = PivotManager(operator=getattr(self, "operator", "ares"))
+ pm = _PIVOT_MANAGERS[campaign_id]
+ tunnel = PivotTunnel(
+ tunnel_type=TunnelType.SSH_DYNAMIC,
+ pivot_host=target,
+ pivot_port=ssh_port,
+ local_host="127.0.0.1",
+ local_port=local_port,
+ username=username,
+ operator=pm.operator,
+ state=TunnelState.ACTIVE,
+ )
+ tunnel._conn = conn
+ tunnel._forwarder = listener
+ pm._tunnels[tunnel.tunnel_id] = tunnel
+ except Exception as e:
+ logger.warning("ssh_pivot_register_manager_error", error=str(e))
+
+ logger.info("socks5_proxy_established", target=target, local_port=local_port)
+ return {
+ "host": "127.0.0.1",
+ "port": local_port,
+ "type": "socks5",
+ "via_host": target,
+ }
+
+ async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
+ findings, raw = await super().run(**kwargs)
+ socks_port = kwargs.get("socks_port")
+ target = kwargs.get("target", "")
+ username = kwargs.get("username", "")
+ secret = kwargs.get("secret", "")
+ ssh_port = kwargs.get("ssh_port") or kwargs.get("port", 22)
+ key_path = kwargs.get("key_path", "")
+
+ if raw.get("result", {}).get("success") and socks_port:
+ proxy_info = await self.establish_socks5(
+ target=target,
+ username=username,
+ secret=secret,
+ local_port=int(socks_port),
+ ssh_port=int(ssh_port),
+ key_path=key_path,
+ )
+ raw["socks5_proxy"] = f"socks5://{proxy_info['host']}:{proxy_info['port']}"
+ return findings, raw
# ── RDP Lateral ────────────────────────────────────────────────────────────────
diff --git a/tests/unit/modules/test_ssh_pivot_socks5_mod020.py b/tests/unit/modules/test_ssh_pivot_socks5_mod020.py
new file mode 100644
index 0000000..f1f499a
--- /dev/null
+++ b/tests/unit/modules/test_ssh_pivot_socks5_mod020.py
@@ -0,0 +1,154 @@
+"""
+Tests for MOD-020: SSHPivot real SOCKS5 dynamic port forwarding.
+Verifies:
+1. establish_socks5 invokes asyncssh.forward_socks('127.0.0.1', local_port)
+2. If asyncssh is unavailable, raises ModuleExecutionError (not a fake dict)
+3. If connection or forward_socks fails, raises ModuleExecutionError
+4. In run(), socks5_proxy is populated only on verified forward
+"""
+
+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.lateral.modules import LateralResult, LateralTechnique, SSHPivot
+
+
+def _make_module():
+ settings = AresSettings(
+ ares_secret_key="test-secret-key-32chars-minimum!!",
+ ares_encryption_key="test-encryption-key-32chars-min!!",
+ )
+ campaign = Campaign(
+ name="SSHPivot-MOD020-Test",
+ operator="test_operator",
+ scope=[ScopeEntry(cidr="10.0.0.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ noise = NoiseController(campaign)
+ mod = SSHPivot(settings=settings, campaign=campaign, noise=noise)
+ mod._log_context = {}
+ return mod
+
+
+async def test_establish_socks5_calls_forward_socks():
+ """Verify establish_socks5 connects via asyncssh and calls forward_socks on 127.0.0.1:port."""
+ mod = _make_module()
+
+ mock_asyncssh = MagicMock()
+ mock_conn = AsyncMock()
+ mock_listener = MagicMock()
+ mock_conn.forward_socks = AsyncMock(return_value=mock_listener)
+ mock_asyncssh.connect = AsyncMock(return_value=mock_conn)
+
+ with patch.dict("sys.modules", {"asyncssh": mock_asyncssh}):
+ res = await mod.establish_socks5(
+ target="10.0.0.50",
+ username="root",
+ secret="password123",
+ local_port=1080,
+ ssh_port=2222,
+ )
+
+ assert res["host"] == "127.0.0.1"
+ assert res["port"] == 1080
+ assert res["type"] == "socks5"
+ assert res["via_host"] == "10.0.0.50"
+
+ # Verify asyncssh.connect was called with target host and port
+ mock_asyncssh.connect.assert_called_once()
+ connect_call = mock_asyncssh.connect.call_args[1]
+ assert connect_call["host"] == "10.0.0.50"
+ assert connect_call["port"] == 2222
+ assert connect_call["username"] == "root"
+
+ # Verify forward_socks called with exact local address and port
+ mock_conn.forward_socks.assert_called_once_with("127.0.0.1", 1080)
+
+
+async def test_establish_socks5_no_asyncssh_raises_module_execution_error():
+ """Verify establish_socks5 raises ModuleExecutionError if asyncssh is not installed."""
+ mod = _make_module()
+
+ with patch.dict("sys.modules", {"asyncssh": None}):
+ with pytest.raises(ModuleExecutionError) as exc_info:
+ await mod.establish_socks5(
+ target="10.0.0.50",
+ username="root",
+ secret="password123",
+ local_port=1080,
+ )
+ assert "asyncssh is not installed" in str(exc_info.value)
+
+
+async def test_establish_socks5_connection_failure_raises_module_execution_error():
+ """Verify establish_socks5 raises ModuleExecutionError when asyncssh connection fails."""
+ mod = _make_module()
+
+ mock_asyncssh = MagicMock()
+ mock_asyncssh.connect = AsyncMock(side_effect=OSError("Connection refused"))
+
+ with patch.dict("sys.modules", {"asyncssh": mock_asyncssh}):
+ with pytest.raises(ModuleExecutionError) as exc_info:
+ await mod.establish_socks5(
+ target="10.0.0.50",
+ username="root",
+ secret="password123",
+ local_port=1080,
+ )
+ assert "Failed to establish SOCKS5" in str(exc_info.value)
+
+
+async def test_sshpivot_run_with_socks_port():
+ """Verify run() invokes establish_socks5 when socks_port is passed and move succeeds."""
+ mod = _make_module()
+
+ success_lateral = LateralResult(
+ technique=LateralTechnique.SSH,
+ source_host="operator",
+ target_host="10.0.0.50",
+ username="root",
+ domain="",
+ success=True,
+ privilege="root",
+ output="uid=0(root)",
+ duration_ms=50.0,
+ )
+
+ fake_proxy = {
+ "host": "127.0.0.1",
+ "port": 1080,
+ "type": "socks5",
+ "via_host": "10.0.0.50",
+ }
+
+ with patch.object(mod, "move", new_callable=AsyncMock) as mock_move, \
+ patch.object(mod, "establish_socks5", new_callable=AsyncMock) as mock_estab, \
+ patch.object(mod, "before_request", new_callable=AsyncMock):
+
+ mock_move.return_value = success_lateral
+ mock_estab.return_value = fake_proxy
+
+ findings, raw = await mod.run(
+ target="10.0.0.50",
+ username="root",
+ secret="password",
+ socks_port=1080,
+ )
+
+ mock_estab.assert_called_once_with(
+ target="10.0.0.50",
+ username="root",
+ secret="password",
+ local_port=1080,
+ ssh_port=22,
+ key_path="",
+ )
+ assert raw["socks5_proxy"] == "socks5://127.0.0.1:1080"