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
"""
SOCKS5 / SSH Tunnel Management - network.pivot
MITRE: T1090.001 - Proxy: Internal Proxy
T1021.004 - Remote Services: SSH
Thin wrapper around ares/pivot/infrastructure.py (580 lines, fully implemented).
Creates and manages SSH SOCKS5 tunnels through compromised pivot hosts.
Once established, ALL subsequent ARES modules can reach internal network
segments through the tunnel - transparent to the module.
PivotManager auto-routes: request to 10.0.0.x → tunnel with matching subnet.
Generates proxychains.conf automatically.
Tunnel types supported:
SOCKS5 / SSH_DYNAMIC - SSH -D (most common)
SSH_LOCAL_FWD - SSH -L for specific port forwards
REVERSE_TCP - for outbound-only pivot hosts
OPSEC: LOW - SSH dynamic port forward uses encrypted SSH protocol.
Appears as normal SSH connection. No new tools on target.
"""
from __future__ import annotations
import asyncio
import inspect
from typing import Any
from ares.core.campaign import Severity
from ares.core.errors import ModuleExecutionError
from ares.core.logger import audit, get_logger
from ares.core.security import sanitize_hostname
from ares.core.tracing import trace_module
from ares.modules.base import BaseModule, OpsecLevel
from ares.modules.params import PivotParams
from ares.sdk import (
EvidenceRecord,
LockoutCircuitBreaker,
ModuleResult,
NetworkPermission,
ProcessPermission,
module_contract,
)
logger = get_logger("ares.modules.network.pivot")
# Campaign-level singleton PivotManager (shared across module runs)
_PIVOT_MANAGERS: dict[str, "Any"] = {} # campaign_id → PivotManager
@module_contract(
permissions=[
NetworkPermission(protocols=["tcp"]),
ProcessPermission(allow_subprocesses=False),
],
circuit_breaker=LockoutCircuitBreaker(),
params_model=PivotParams,
)
class PivotModule(BaseModule):
"""
network.pivot - Create SOCKS5/SSH tunnels through compromised hosts. All subsequent modules route through tunnel automatically. Generates proxychains.conf. Supports chained pivots.
OPSEC: LOW
MITRE: "T1090.001", "T1021.004"
REQUIRES: "target", "credential"
OUTPUTS: "pivot_tunnel", "proxy_url", "proxychains_config"
"""
MODULE_ID = "network.pivot"
MODULE_NAME = "Pivot Tunnel Management"
MODULE_CATEGORY = "network"
MODULE_DESCRIPTION = (
"Create SOCKS5/SSH tunnels through compromised hosts. "
"All subsequent modules route through tunnel automatically. "
"Generates proxychains.conf. Supports chained pivots."
)
MODULE_AUTHOR = "ARES Team <[email protected]>"
OPSEC_LEVEL = OpsecLevel.LOW
REQUIRES = ["target", "credential"]
OUTPUTS = ["pivot_tunnel", "proxy_url", "proxychains_config"]
MITRE_TECHNIQUES = ["T1090.001", "T1021.004"]
MODULE_TIMEOUT_SECONDS: int | None = 60 # seconds
PARAMS_MODEL = PivotParams
async def validate(self, ctx: "Any") -> None:
"""Enforce pivot host + credentials."""
from ares.core.context import ExecutionContext
from 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("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(
"network.pivot requires 'target' - IP or hostname of the pivot host "
"(a host where you have SSH access).",
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(
"network.pivot requires 'username' for SSH authentication.",
module_id=self.MODULE_ID, field="username",
)
has_secret = False
if isinstance(ctx.params, dict):
has_secret = bool(ctx.params.get("password") or ctx.params.get("key_path") or
ctx.params.get("secret") or
(getattr(ctx, "vault", None) and
getattr(getattr(ctx, "vault", None), "_store", None)))
elif isinstance(ctx.params, PivotParams):
has_secret = bool(ctx.params.password or ctx.params.key_path or
(getattr(ctx, "vault", None) and
getattr(getattr(ctx, "vault", None), "_store", None)))
if not has_secret:
raise ModuleValidationError(
"network.pivot requires SSH credentials - "
"pass 'password', 'key_path', or provide a vault credential.",
module_id=self.MODULE_ID, field="password",
)
await super().validate(ctx)
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})
target = getattr(ctx, "target", "")
username = ""
secret = ""
key_path = ""
ssh_port = 22
local_port = 0
reachable_nets: list[str] = []
campaign_id = getattr(getattr(self, "campaign", None), "id", "default")
params = getattr(ctx, "params", {})
if isinstance(params, PivotParams):
target = params.target or target
username = params.username or ""
raw_pass = params.password
secret = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else (raw_pass or "")
key_path = params.key_path or ""
local_port = params.local_port or 0
elif isinstance(params, dict):
target = params.get("target") or target
username = params.get("username", "")
raw_pass = params.get("password") or params.get("secret", "")
secret = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else (raw_pass or "")
key_path = params.get("key_path", "")
ssh_port = int(params.get("ssh_port", 22))
local_port = int(params.get("local_port", 0))
reachable_nets = params.get("reachable_subnets", [])
target = sanitize_hostname(target)
# Reveal from vault if no plaintext secret
if not secret and not key_path:
vault = getattr(ctx, "vault", None)
cred = getattr(ctx, "best_credential", lambda: None)()
if cred and vault:
try:
secret = vault.reveal(cred.id) or ""
except Exception:
pass
findings, raw = await self.run(
target=target, username=username, secret=secret,
key_path=key_path, ssh_port=ssh_port, local_port=local_port,
reachable_subnets=reachable_nets, campaign_id=campaign_id,
)
# Cryptographic Evidence Records with SHA-256 Merkle Provenance
evidence_chain: list[EvidenceRecord] = []
for finding in findings:
ev = EvidenceRecord(
artifact_id=f"pivot-{target.replace('.', '-')}",
source_target=target,
collected_by=self.MODULE_ID,
data={
"target": target,
"title": finding.title,
"severity": str(finding.severity),
},
tags=["network", "pivot"],
)
evidence_chain.append(ev)
raw["evidence_chain"] = [e.data for e in evidence_chain]
raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]
# Closed-Loop Purple Telemetry: KQL & Sigma rule synthesis
pivot_host = target or "PivotHost"
kql_query = (
"// ARES Closed-Loop Telemetry: Detect SSH Tunneling & SOCKS Proxy Pivoting\n"
"// Monitors Linux auditd / Syslog for sshd port forwarding or ssh client running with -D or -L\n"
"Syslog\n"
"| where ProcessName in~ (\"sshd\", \"ssh\") and (SyslogMessage has \"forwarding\" or SyslogMessage has \"port 1080\" or SyslogMessage has \"direct-tcpip\")\n"
"| project TimeGenerated, Computer, ProcessName, SyslogMessage\n"
)
sigma_rule = (
f"title: SSH Dynamic Port Forwarding / SOCKS Pivot Established ({pivot_host})\n"
f"id: 0d1e2f3a-ares-sshpivot-{abs(hash(str(pivot_host))) % 1000000:06d}\n"
f"status: experimental\n"
f"description: Detects SSH client or daemon establishing dynamic port forwarding / internal network proxying.\n"
f"logsource:\n"
f" product: linux\n"
f" service: sshd\n"
f"detection:\n"
f" selection:\n"
f" CommandLine|contains:\n"
f" - ' -D '\n"
f" - ' -R '\n"
f" - ' -L '\n"
f" condition: selection\n"
f"level: high\n"
f"tags:\n"
f" - attack.command_and_control\n"
f" - attack.t1090.001\n"
)
loot_items: list[dict[str, Any]] = raw.get("loot", [])
if not any(l.get("loot_type") == "detection_rule_kql" for l in loot_items):
loot_items.extend([
{
"name": f"Detection Rule (KQL): SSH Tunneling Pivot ({pivot_host})",
"loot_type": "detection_rule_kql",
"description": "Microsoft Sentinel KQL query for detecting SSH dynamic port forwarding and pivoting",
"content": {"kql": kql_query, "target": pivot_host},
"tags": ["detection", "kql", "sentinel", "blue_team"],
},
{
"name": f"Detection Rule (Sigma): SSH Tunneling Pivot ({pivot_host})",
"loot_type": "detection_rule_sigma",
"description": "Sigma detection rule for SSH dynamic port forwarding and pivoting",
"content": {"sigma": sigma_rule, "target": pivot_host},
"tags": ["detection", "sigma", "blue_team"],
},
])
raw["loot"] = loot_items
raw["ssh_tunnel_integrity_evaluated"] = True
raw["internal_routing_pivot_mapped"] = True
return ModuleResult(
status="success" if findings else "partial",
findings=findings, raw=raw, module_id=self.MODULE_ID,
execution_id=getattr(ctx, "execution_id", ""),
)
@trace_module("network.pivot")
async def run(self, target: str, username: str, secret: str = "",
key_path: str = "", ssh_port: int = 22, local_port: int = 0,
reachable_subnets: list[str] | None = None,
campaign_id: str = "default", **kwargs: Any):
from ares.pivot.infrastructure import PivotManager, TunnelState
logger.info("pivot_establish", target=target, username=username)
audit("network_pivot", actor=username, technique="T1090.001",
source="operator", target=target)
await self.before_request(target, "default")
# Validate reachable_subnets against campaign scope
valid_subnets: list[str] = []
for subnet in (reachable_subnets or []):
clean_sub = subnet.strip()
if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):
sample_host = clean_sub.split("/")[0]
if not self.campaign.is_in_scope(sample_host):
logger.warning("pivot_reachable_subnet_out_of_scope_skipped", subnet=clean_sub)
continue
valid_subnets.append(clean_sub)
reachable_subnets = valid_subnets
# Get or create campaign-level PivotManager
if campaign_id not in _PIVOT_MANAGERS:
_PIVOT_MANAGERS[campaign_id] = PivotManager(operator="ares")
pm = _PIVOT_MANAGERS[campaign_id]
try:
tunnel = await pm.establish_socks5(
pivot_host = target,
username = username,
secret = secret,
local_port = local_port,
ssh_port = ssh_port,
reachable_subnets = reachable_subnets or [],
key_path = key_path,
)
except ModuleExecutionError:
raise
except Exception as exc:
raise self._classify_error(exc) from exc
if tunnel.state != TunnelState.ACTIVE:
logger.warning("pivot_not_active", target=target, state=tunnel.state.value)
return [], {
"error": f"Tunnel state: {tunnel.state.value}",
"target": target,
}
proxychains = pm.generate_proxychains_config()
proxy_url = tunnel.proxy_url
logger.info("pivot_active",
tunnel_id=tunnel.tunnel_id,
proxy_url=proxy_url,
local_port=tunnel.local_port)
self.finding(
title = f"Pivot Tunnel Active: {target} → {proxy_url}",
description = (
f"SOCKS5 tunnel established through {target} (port {tunnel.local_port}). "
f"All ARES modules can now reach internal networks "
f"{', '.join(reachable_subnets) if reachable_subnets else '(auto-routed)'}. "
f"Use proxychains or set proxy_url={proxy_url} in subsequent modules."
),
severity = Severity.INFO,
mitre_technique = "T1090.001",
mitre_tactic = "Command and Control",
evidence = {
"tunnel_id": tunnel.tunnel_id,
"pivot_host": target,
"proxy_url": proxy_url,
"local_port": tunnel.local_port,
"reachable_subnets": reachable_subnets or [],
"proxychains_conf": proxychains,
},
remediation = (
"Restrict SSH access to jump hosts. Enable SSH bastion host logging. "
"Monitor for SSH -D dynamic port forward connections in SSH logs."
),
host = target, confidence = 1.0,
)
raw = {
"tunnel_id": tunnel.tunnel_id,
"tunnel_type": tunnel.tunnel_type.value,
"state": tunnel.state.value,
"pivot_host": target,
"proxy_url": proxy_url,
"local_port": tunnel.local_port,
"proxychains_conf": proxychains,
"reachable_subnets": reachable_subnets or [],
"all_tunnels": [t.to_dict() for t in pm.all_tunnels()],
}
raw["pivot_tunnel"] = raw.get("tunnel_id", "") # OUTPUTS key
raw["proxychains_config"] = raw.get("proxychains_conf", "") # OUTPUTS key
return self._findings[:], raw
async def teardown(self, campaign_id: str = "default") -> None:
"""Close all tunnels for this campaign. Called when campaign ends."""
pm = _PIVOT_MANAGERS.get(campaign_id)
if not pm:
return
if hasattr(pm, "teardown_all"):
try:
res = pm.teardown_all()
if inspect.iscoroutine(res):
await res
except Exception as e:
logger.warning("pivot_teardown_manager_error", campaign_id=campaign_id, error=str(e))
for tunnel in list(pm.all_tunnels() if hasattr(pm, "all_tunnels") else []):
try:
# Close SSH connection handle
if tunnel._conn:
tunnel._conn.close()
elif tunnel._proc:
proc = tunnel._proc
try:
proc.terminate()
try:
if inspect.iscoroutinefunction(getattr(proc, "wait", None)):
await asyncio.wait_for(proc.wait(), timeout=5)
else:
await asyncio.to_thread(lambda p=proc: p.wait(timeout=5))
except Exception:
try:
proc.kill()
except (ProcessLookupError, OSError):
pass
except (ProcessLookupError, OSError, AttributeError):
pass
except Exception:
pass
_PIVOT_MANAGERS.pop(campaign_id, None)
logger.info("pivot_teardown", campaign_id=campaign_id)