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(security): remediate ARES-SEC-01 through ARES-SEC-07 security and governance invariants

Mafifrizi86ca67e711a8
diff --git a/ares/api/server.py b/ares/api/server.py
index f1a1736..dd9dde7 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -781,11 +781,14 @@ app.add_middleware(
async def _require_campaign_access(
- campaign: dict,
+ campaign: Any,
actor: AuthenticatedUser,
) -> None:
"""Raise 404 (not 403) if actor cannot access campaign - avoids campaign enumeration."""
- if actor.role != "team_lead" and campaign.get("operator") != actor.username:
+ if actor.role == "team_lead":
+ return
+ operator = campaign.get("operator") if isinstance(campaign, dict) else getattr(campaign, "operator", None)
+ if operator != actor.username:
raise HTTPException(404, "Campaign not found")
@@ -1449,6 +1452,19 @@ async def create_api_key(
db: AresDatabase = Depends(get_db),
) -> dict[str, str]:
"""Create API key for CI/CD automation. Key is shown ONCE - save it."""
+ # Privilege escalation defense: callers cannot mint API keys with scopes exceeding their role
+ allowed_scopes = {"read"}
+ if actor.role in ("operator", "team_lead"):
+ allowed_scopes.add("write")
+ if actor.role == "team_lead":
+ allowed_scopes.add("admin")
+
+ if body.scopes not in allowed_scopes:
+ raise HTTPException(
+ status_code=403,
+ detail=f"Role '{actor.role}' is not authorized to create API keys with '{body.scopes}' scope.",
+ )
+
user = await db.get_user(actor.username)
if not user:
raise HTTPException(404, "User not found")
@@ -2836,6 +2852,7 @@ async def assess_module_feasibility_endpoint(
campaign = await db.get_campaign(body.campaign_id)
if not campaign:
raise HTTPException(404, "Campaign not found")
+ await _require_campaign_access(campaign, actor)
params = dict(body.params)
if body.target and not params.get("target"):
diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.py
index cdbb204..91f2c9a 100644
--- a/ares/cli/typer_main.py
+++ b/ares/cli/typer_main.py
@@ -3424,16 +3424,32 @@ def mcp_stdio_cmd() -> None:
@mcp_app.command("sse")
def mcp_sse_cmd(
- host: str = typer.Option("0.0.0.0", "--host", "-h", help="Host address to bind"),
+ host: str = typer.Option("127.0.0.1", "--host", "-h", help="Host address to bind (default: 127.0.0.1)"),
port: int = typer.Option(8001, "--port", "-p", help="Port to listen on"),
api_key: Optional[str] = typer.Option(None, "--api-key", "-k", help="Optional Bearer API Key for network authentication"),
) -> None:
"""Run the ARES MCP Server over HTTP with Server-Sent Events (SSE)."""
+ import secrets
import uvicorn
from ares.cli.mcp_cli_utils import warn_cli_secret_exposure
from ares.mcp import AresMcpServer, create_sse_app
- if api_key:
+ is_loopback = host in ("127.0.0.1", "localhost", "::1")
+ if not is_loopback and not api_key:
+ api_key = secrets.token_urlsafe(32)
+ console.print(
+ Panel(
+ f"[bold red]SECURITY NOTICE:[/] Binding MCP SSE server to external interface [yellow]{host}[/] "
+ f"without an explicit --api-key.\n"
+ f"Generated ephemeral API key:\n\n"
+ f" [bold green]{api_key}[/]\n\n"
+ f"Clients must provide this key via 'Authorization: Bearer <key>' or 'x-ares-api-key' header.",
+ title="[bold yellow]MCP Network Authentication Generated[/]",
+ border_style="yellow",
+ box=box.ROUNDED,
+ )
+ )
+ elif api_key:
warn_cli_secret_exposure()
server = AresMcpServer()
@@ -3441,7 +3457,7 @@ def mcp_sse_cmd(
console.print(Panel(
f"[bold green]ARES MCP Server (SSE Mode)[/]\n\n"
f" [cyan]Endpoint:[/] http://{host}:{port}/sse\n"
- f" [cyan]Auth:[/] {'Protected by API Key' if api_key else 'Open / Localhost Only'}\n"
+ f" [cyan]Auth:[/] {'Protected by API Key' if api_key else 'Loopback Only (127.0.0.1)'}\n"
f" [cyan]Clients:[/] Open-WebUI, LibreChat, Remote Agents, Docker\n\n"
f"Press [yellow]Ctrl+C[/] to stop the server.",
title="ares mcp sse",
diff --git a/ares/mcp/security.py b/ares/mcp/security.py
index 824996f..a5f068a 100644
--- a/ares/mcp/security.py
+++ b/ares/mcp/security.py
@@ -140,33 +140,46 @@ class McpScopeGate:
if not target or not scope_rules:
return False
+ # Extract host if target includes port notation (e.g. "10.0.0.1:445" or "dc01.corp.local:88")
+ target_host = target
+ if ":" in target and not target.startswith("["):
+ parts = target.split(":")
+ if len(parts) == 2:
+ target_host = parts[0].strip()
+
for rule in scope_rules:
rule = rule.strip().lower()
if not rule:
continue
# Exact match (hostname or IP)
- if target == rule:
+ if target == rule or target_host == rule:
return True
# CIDR Subnet Match
if "/" in rule:
try:
net = ipaddress.ip_network(rule, strict=False)
- tgt_ip = ipaddress.ip_address(target)
- if tgt_ip in net:
- return True
+ for candidate in (target, target_host):
+ try:
+ tgt_ip = ipaddress.ip_address(candidate)
+ if tgt_ip in net:
+ return True
+ except ValueError:
+ pass
except ValueError:
pass
- # Wildcard or Domain Suffix Match (*.corp.local or corp.local)
+ # Wildcard or Domain Suffix Match (*.corp.local, .corp.local, or corp.local)
if rule.startswith("*."):
domain_suffix = rule[2:]
- if target == domain_suffix or target.endswith("." + domain_suffix):
- return True
elif rule.startswith("."):
domain_suffix = rule[1:]
- if target == domain_suffix or target.endswith(rule):
+ else:
+ domain_suffix = rule
+
+ for candidate in (target, target_host):
+ if candidate == domain_suffix or candidate.endswith("." + domain_suffix):
return True
return False
@@ -228,9 +241,18 @@ class SecretMasker:
"credential", "creds", "session_key", "masterkey", "privatekey",
}
+ _PRIVATE_KEY_BLOCK_REGEX = re.compile(
+ r"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----"
+ )
+
@classmethod
def mask(cls, data: Any) -> Any:
- """Recursively mask sensitive values in dictionaries and structures."""
+ """Recursively mask sensitive values in dictionaries, strings, and structures."""
+ if isinstance(data, str):
+ if "-----BEGIN " in data and "PRIVATE KEY-----" in data:
+ return cls._PRIVATE_KEY_BLOCK_REGEX.sub("[REDACTED_PRIVATE_KEY_BLOCK]", data)
+ return data
+
if isinstance(data, dict):
masked: dict[str, Any] = {}
for k, v in data.items():
diff --git a/ares/mcp/tools.py b/ares/mcp/tools.py
index fd3eeab..cba26c5 100644
--- a/ares/mcp/tools.py
+++ b/ares/mcp/tools.py
@@ -267,11 +267,36 @@ class McpToolRegistry:
if self.db and hasattr(self.db, "get_campaign"):
try:
camp = await self.db.get_campaign(campaign_id)
- if camp and "scope" in camp:
- return camp["scope"]
+ if not camp:
+ raise McpSecurityViolation(f"Campaign '{campaign_id}' not found in database.")
+
+ raw_scope = camp.get("scope_json") or camp.get("scope")
+ if raw_scope:
+ parsed = json.loads(raw_scope) if isinstance(raw_scope, str) else raw_scope
+ if isinstance(parsed, list):
+ extracted_rules = []
+ for item in parsed:
+ if isinstance(item, str):
+ extracted_rules.append(item)
+ elif isinstance(item, dict) and "cidr" in item:
+ extracted_rules.append(item["cidr"])
+ if extracted_rules:
+ return extracted_rules
+
+ raw_targets = camp.get("targets_json") or camp.get("targets")
+ if raw_targets:
+ parsed_tgt = json.loads(raw_targets) if isinstance(raw_targets, str) else raw_targets
+ if isinstance(parsed_tgt, list) and parsed_tgt:
+ return [t for t in parsed_tgt if isinstance(t, str)]
+
+ return [] # Fail-closed: campaign exists but has zero authorized scope
+ except McpSecurityViolation:
+ raise
except Exception as exc:
logger.warning("mcp_fetch_campaign_scope_failed", campaign_id=campaign_id, error=str(exc))
- # Default safety fallback: internal lab subnets only
+ raise McpSecurityViolation(f"Failed to resolve scope for campaign '{campaign_id}': {exc}")
+
+ # Default fallback only when DB is not bound (standalone mock/demo mode)
return ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "*.corp.local", "*.lab.local", "localhost", "127.0.0.1"]
async def _handle_list_campaigns(self, args: dict[str, Any]) -> CallToolResult:
@@ -285,18 +310,30 @@ class McpToolRegistry:
for c in raw_campaigns[:limit]:
c_status = c.get("status", "active")
if status_filter == "all" or c_status == status_filter:
+ scope = c.get("scope")
+ if not scope and c.get("scope_json"):
+ try:
+ scope = json.loads(str(c["scope_json"]))
+ except Exception:
+ scope = []
+ targets = c.get("targets")
+ if not targets and c.get("targets_json"):
+ try:
+ targets = json.loads(str(c["targets_json"]))
+ except Exception:
+ targets = []
items.append({
"id": c.get("id"),
"name": c.get("name"),
"client": c.get("client"),
"status": c_status,
- "scope": c.get("scope", []),
- "targets_count": len(c.get("targets", [])),
+ "scope": scope or [],
+ "targets_count": len(targets or []),
})
except Exception as e:
logger.warning("DB query failed: %s", e)
- if not items:
+ if not items and not self.db:
items = [{
"id": "camp_default_01",
"name": "Enterprise Internal Purple-Team Engagement",
@@ -313,12 +350,13 @@ class McpToolRegistry:
async def _handle_get_campaign_status(self, args: dict[str, Any]) -> CallToolResult:
campaign_id = args["campaign_id"]
+ scope = await self._get_campaign_scope(campaign_id)
status_data = {
"campaign_id": campaign_id,
"status": "active",
"findings_summary": {"critical": 2, "high": 5, "medium": 8, "low": 12, "info": 4},
"active_phase": "Lateral Movement & Domain Enumeration",
- "scope": await self._get_campaign_scope(campaign_id),
+ "scope": scope,
"circuit_breaker_state": self.circuit_breaker.state.value,
}
clean_data = McpTaintSanitizer.sanitize(status_data)
@@ -331,37 +369,47 @@ class McpToolRegistry:
min_severity = args.get("min_severity", "info").lower()
host_filter = args.get("host")
- sample_findings = [
- {
- "id": "find_kerb_01",
- "campaign_id": campaign_id,
- "title": "Service Principal Name (SPN) Accounts Vulnerable to Kerberoasting",
- "severity": "high",
- "cvss_score": 7.5,
- "host": "dc01.corp.local",
- "mitre_technique": "T1558.003",
- "description": "High-privilege service account 'svc_mssql' requested Kerberos ticket with weak RC4 encryption.",
- "remediation": "Enforce AES-only Kerberos encryption and apply strong 25+ character service account passwords.",
- },
- {
- "id": "find_smb_02",
- "campaign_id": campaign_id,
- "title": "SMB Signing Not Required on Domain Controller",
- "severity": "critical",
- "cvss_score": 8.8,
- "host": "dc02.corp.local",
- "mitre_technique": "T1557.001",
- "description": "SMB signing is disabled or optional, permitting NTLM relay attacks to escalate to Domain Admin.",
- "remediation": "Enable and require SMB signing via Group Policy (GPO: Microsoft network server: Digitally sign communications).",
- },
- ]
+ findings = []
+ if self.db and hasattr(self.db, "get_findings"):
+ try:
+ raw_findings = await self.db.get_findings(campaign_id)
+ if isinstance(raw_findings, list):
+ findings = raw_findings
+ except Exception as exc:
+ logger.warning("mcp_fetch_findings_failed", campaign_id=campaign_id, error=str(exc))
+
+ if not findings and not self.db:
+ findings = [
+ {
+ "id": "find_kerb_01",
+ "campaign_id": campaign_id,
+ "title": "Service Principal Name (SPN) Accounts Vulnerable to Kerberoasting",
+ "severity": "high",
+ "cvss_score": 7.5,
+ "host": "dc01.corp.local",
+ "mitre_technique": "T1558.003",
+ "description": "High-privilege service account 'svc_mssql' requested Kerberos ticket with weak RC4 encryption.",
+ "remediation": "Enforce AES-only Kerberos encryption and apply strong 25+ character service account passwords.",
+ },
+ {
+ "id": "find_smb_02",
+ "campaign_id": campaign_id,
+ "title": "SMB Signing Not Required on Domain Controller",
+ "severity": "critical",
+ "cvss_score": 8.8,
+ "host": "dc02.corp.local",
+ "mitre_technique": "T1557.001",
+ "description": "SMB signing is disabled or optional, permitting NTLM relay attacks to escalate to Domain Admin.",
+ "remediation": "Enable and require SMB signing via Group Policy (GPO: Microsoft network server: Digitally sign communications).",
+ },
+ ]
severity_ranks = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0}
min_rank = severity_ranks.get(min_severity, 0)
filtered = [
- f for f in sample_findings
- if severity_ranks.get(f["severity"].lower(), 0) >= min_rank
+ f for f in findings
+ if severity_ranks.get(str(f.get("severity", "")).lower(), 0) >= min_rank
and (not host_filter or f.get("host") == host_filter)
]
diff --git a/ares/mcp/transport/sse.py b/ares/mcp/transport/sse.py
index 181912a..1ae8100 100644
--- a/ares/mcp/transport/sse.py
+++ b/ares/mcp/transport/sse.py
@@ -30,6 +30,11 @@ class SseSession:
self.created_at = asyncio.get_event_loop().time()
+from urllib.parse import urlparse
+
+_ALLOWED_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "testclient"})
+
+
def create_sse_app(
server: AresMcpServer,
api_key: str | None = None,
@@ -39,8 +44,43 @@ def create_sse_app(
sessions: dict[str, SseSession] = {}
def _verify_auth(request: Request) -> bool:
+ # Cross-Origin Drive-by Protection:
+ # Browser-initiated cross-site requests are strictly rejected
+ sec_fetch_site = request.headers.get("sec-fetch-site", "").strip().lower()
+ if sec_fetch_site == "cross-site":
+ return False
+
if not api_key:
+ # 1. Network Layer: Only loopback clients (localhost / 127.0.0.1 / ::1 / testclient) are allowed
+ client_host = request.client.host if request.client else ""
+ if client_host not in _ALLOWED_LOOPBACK_HOSTS:
+ return False
+
+ # 2. Anti-DNS Rebinding: Host header must match loopback
+ host_header = request.headers.get("host", "").strip()
+ if host_header:
+ if host_header.startswith("["):
+ host_name = host_header.split("]")[0].lstrip("[").lower()
+ else:
+ host_name = host_header.split(":")[0].strip().lower()
+ if host_name not in _ALLOWED_LOOPBACK_HOSTS:
+ return False
+
+ # 3. Anti-CSRF / Drive-By Cross-Origin Protection:
+ # If Origin header is present, verify it is strictly loopback
+ origin = request.headers.get("origin")
+ if origin:
+ try:
+ parsed = urlparse(origin)
+ origin_host = (parsed.hostname or "").lower()
+ if origin_host not in _ALLOWED_LOOPBACK_HOSTS:
+ return False
+ except Exception:
+ return False
+
return True
+
+ # When api_key is configured:
# Check Authorization: Bearer <token> or X-ARES-API-Key or query param
auth_header = request.headers.get("authorization", "")
if auth_header.startswith("Bearer "):
diff --git a/ares/modules/credential/pass_spray.py b/ares/modules/credential/pass_spray.py
index 2f2ea25..eeab55e 100644
--- a/ares/modules/credential/pass_spray.py
+++ b/ares/modules/credential/pass_spray.py
@@ -699,6 +699,9 @@ class PassSprayModule(BaseModule[PassSprayParams, ModuleResult]):
locked_accounts.append(user)
lockout_detected = True
logger.warning("pass_spray_lockout", user=user, target=target)
+ cb = getattr(self, "CIRCUIT_BREAKER", None)
+ if cb is not None and isinstance(cb, LockoutCircuitBreaker):
+ cb._trip_for_account(user, "Account lockout detected during password spray")
break
elif result in ("success", "must_change"):
valid_creds.append({
diff --git a/ares/sdk/contracts/declarative.py b/ares/sdk/contracts/declarative.py
index c036034..c2bdfd2 100644
--- a/ares/sdk/contracts/declarative.py
+++ b/ares/sdk/contracts/declarative.py
@@ -80,7 +80,15 @@ def module_contract(
try:
res = await original_execute(self, c)
if cb is not None:
- cb.record_success()
+ from ares.sdk.resilience.circuit_breaker import LockoutCircuitBreaker, CircuitBreakerState
+ if isinstance(cb, LockoutCircuitBreaker):
+ raw_res = getattr(res, "raw", {}) or {}
+ for acc in raw_res.get("locked_accounts", []):
+ cb._trip_for_account(acc, "Module result reported account lockout")
+ if raw_res.get("lockout_detected") and cb.state != CircuitBreakerState.OPEN:
+ cb._trip_for_account("unknown", "Module result reported lockout detected")
+ if cb.state != CircuitBreakerState.OPEN:
+ cb.record_success()
return res
except Exception as exc:
if cb is not None:
diff --git a/ares/sdk/security/permissions.py b/ares/sdk/security/permissions.py
index b78c02f..7790119 100644
--- a/ares/sdk/security/permissions.py
+++ b/ares/sdk/security/permissions.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import abc
from dataclasses import dataclass, field
+import pathlib
from typing import Any
from ares.core.errors import AresError
@@ -51,6 +52,13 @@ class NetworkPermission(SecurityPermission):
def validate_request(self, params: dict[str, Any], context: Any) -> None:
port = params.get("port")
+ if port is None:
+ target = params.get("target") or (getattr(context, "target", "") if context else "")
+ if isinstance(target, str) and ":" in target and not target.startswith("["):
+ parts = target.split(":")
+ if len(parts) == 2 and parts[1].isdigit():
+ port = int(parts[1])
+
if port is not None and self.ports:
try:
port_int = int(port)
@@ -63,6 +71,17 @@ class NetworkPermission(SecurityPermission):
except ValueError:
pass
+ proto = params.get("protocol")
+ if proto is not None and self.protocols:
+ proto_str = str(proto).strip().lower()
+ allowed = [p.strip().lower() for p in self.protocols]
+ if proto_str not in allowed:
+ raise SecurityCapabilityViolation(
+ f"Protocol '{proto_str}' is not authorized for module (Allowed: {self.protocols})",
+ capability=self.name,
+ details={"requested_protocol": proto_str, "allowed_protocols": self.protocols},
+ )
+
@dataclass
class VaultPermission(SecurityPermission):
@@ -76,8 +95,8 @@ class VaultPermission(SecurityPermission):
return "vault"
def validate_request(self, params: dict[str, Any], context: Any) -> None:
- requested_type = params.get("cred_type")
- if requested_type and self.write_types:
+ requested_type = params.get("cred_type") or params.get("write_cred_type")
+ if requested_type is not None:
if requested_type not in self.write_types:
raise SecurityCapabilityViolation(
f"Credential type '{requested_type}' not authorized for storage (Allowed: {self.write_types})",
@@ -85,6 +104,15 @@ class VaultPermission(SecurityPermission):
details={"requested_type": requested_type, "allowed_types": self.write_types},
)
+ read_type = params.get("read_cred_type") or params.get("read_type")
+ if read_type is not None:
+ if read_type not in self.read_types:
+ raise SecurityCapabilityViolation(
+ f"Credential read type '{read_type}' not authorized (Allowed: {self.read_types})",
+ capability=self.name,
+ details={"requested_read_type": read_type, "allowed_read_types": self.read_types},
+ )
+
@dataclass
class FilesystemPermission(SecurityPermission):
@@ -98,10 +126,34 @@ class FilesystemPermission(SecurityPermission):
return "filesystem"
def validate_request(self, params: dict[str, Any], context: Any) -> None:
- output_path = params.get("output_path") or params.get("file_path")
+ output_path = params.get("output_path") or params.get("write_path") or params.get("outfile") or params.get("dest_file") or params.get("dest_path")
+ is_write = bool(output_path) or bool(params.get("write_file", False))
+
+ if is_write and self.read_only:
+ raise SecurityCapabilityViolation(
+ f"Filesystem write operation prohibited: module is configured as read-only",
+ capability=self.name,
+ details={"read_only": True, "attempted_path": str(output_path) if output_path else None},
+ )
+
if output_path and not self.read_only:
- # Enforce path containment
- pass
+ norm_str = str(output_path).replace("\\", "/")
+ parts = [p for p in norm_str.split("/") if p]
+ if ".." in parts:
+ raise SecurityCapabilityViolation(
+ f"Directory traversal detected in path '{output_path}'",
+ capability=self.name,
+ details={"attempted_path": output_path},
+ )
+ if self.allowed_subdirs:
+ allowed = [s.strip().lower().strip("/\\") for s in self.allowed_subdirs if s.strip()]
+ match = any(part.lower() in allowed for part in parts)
+ if not match:
+ raise SecurityCapabilityViolation(
+ f"Filesystem path '{output_path}' is outside of authorized subdirs: {self.allowed_subdirs}",
+ capability=self.name,
+ details={"attempted_path": output_path, "allowed_subdirs": self.allowed_subdirs},
+ )
@dataclass
@@ -116,12 +168,25 @@ class ProcessPermission(SecurityPermission):
return "process"
def validate_request(self, params: dict[str, Any], context: Any) -> None:
- if not self.allow_subprocesses and params.get("spawn_process", False):
+ spawns = params.get("spawn_process", False) or params.get("binary") or params.get("command")
+ if not self.allow_subprocesses and spawns:
raise SecurityCapabilityViolation(
"Subprocess execution is strictly prohibited for this module",
capability=self.name,
)
+ if self.allow_subprocesses and self.allowed_binaries:
+ binary = params.get("binary") or params.get("command")
+ if binary:
+ base = pathlib.Path(str(binary).strip().split()[0]).name.lower()
+ allowed_lower = [pathlib.Path(b).name.lower() for b in self.allowed_binaries]
+ if base not in allowed_lower:
+ raise SecurityCapabilityViolation(
+ f"Binary '{base}' is not authorized for subprocess execution (Allowed: {self.allowed_binaries})",
+ capability=self.name,
+ details={"requested_binary": base, "allowed_binaries": self.allowed_binaries},
+ )
+
class CapabilitySandbox:
"""Evaluates module permissions against execution parameters and runtime context."""
diff --git a/tests/unit/test_cli_doctor.py b/tests/unit/test_cli_doctor.py
index 6654f4f..84d8184 100644
--- a/tests/unit/test_cli_doctor.py
+++ b/tests/unit/test_cli_doctor.py
@@ -561,7 +561,12 @@ def test_python_setup_windows_skips_bash_and_uses_valid_paths(monkeypatch, tmp_p
monkeypatch.setattr(os, "execv", forbidden_execv)
- _run_python_setup(root=tmp_path, platform_name="win32", os_name="nt")
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ )
output = capsys.readouterr().out
assert "ARES Setup" in output
@@ -582,7 +587,12 @@ def test_python_setup_posix_keeps_shell_helper_optional(tmp_path, capsys):
encoding="utf-8",
)
- _run_python_setup(root=tmp_path, platform_name="linux", os_name="posix")
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="linux",
+ os_name="posix",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ )
output = capsys.readouterr().out
assert "Linux" in output
@@ -625,7 +635,12 @@ def test_python_setup_replaces_change_me_placeholders_in_existing_env(tmp_path,
encoding="utf-8",
)
- _run_python_setup(root=tmp_path, platform_name="win32", os_name="nt")
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ )
output = capsys.readouterr().out
assert "Replaced CHANGE_ME placeholders in .env with secure generated keys" in output
@@ -648,7 +663,12 @@ def test_python_setup_replaces_new_256bit_placeholder_in_existing_env(tmp_path,
encoding="utf-8",
)
- _run_python_setup(root=tmp_path, platform_name="win32", os_name="nt")
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ )
output = capsys.readouterr().out
assert "Replaced CHANGE_ME placeholders in .env with secure generated keys" in output
@@ -670,7 +690,12 @@ def test_python_setup_leaves_configured_env_unchanged(tmp_path, capsys):
)
(tmp_path / ".env").write_text(original, encoding="utf-8")
- _run_python_setup(root=tmp_path, platform_name="win32", os_name="nt")
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ )
output = capsys.readouterr().out
assert ".env already exists; leaving it unchanged" in output
@@ -690,7 +715,13 @@ def test_python_setup_force_regenerates_existing_env(tmp_path, capsys):
)
(tmp_path / ".env").write_text(original, encoding="utf-8")
- _run_python_setup(root=tmp_path, platform_name="win32", os_name="nt", force=True)
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ force=True,
+ )
output = capsys.readouterr().out
assert ".env regenerated with fresh secure keys (--force)" in output
@@ -737,7 +768,12 @@ def test_python_setup_cleans_invalid_browser_origin_placeholder(tmp_path, capsys
encoding="utf-8",
)
- _run_python_setup(root=tmp_path, platform_name="win32", os_name="nt")
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 12, 0, "final", 0),
+ )
content = (tmp_path / ".env").read_text(encoding="utf-8")
assert "example.invalid" not in content
diff --git a/tests/unit/test_enterprise_sdk_security.py b/tests/unit/test_enterprise_sdk_security.py
index d574753..764fc61 100644
--- a/tests/unit/test_enterprise_sdk_security.py
+++ b/tests/unit/test_enterprise_sdk_security.py
@@ -279,3 +279,109 @@ async def test_module_contract_enforces_permissions_and_generates_provenance():
module = DemoContractModule(settings=harness.settings, campaign=harness.campaign, noise=harness.noise)
with pytest.raises(SecurityCapabilityViolation):
await module.execute(ctx_bad)
+
+
+def test_filesystem_permission_enforcement():
+ # Read-only blocks write attempts
+ ro_perm = FilesystemPermission(read_only=True)
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ ro_perm.validate_request({"output_path": "loot/file.txt"}, None)
+ assert "configured as read-only" in str(exc_info.value)
+
+ with pytest.raises(SecurityCapabilityViolation):
+ ro_perm.validate_request({"write_file": True}, None)
+
+ # Read-only permits read parameters
+ ro_perm.validate_request({"file_path": "certs/ca.crt"}, None)
+
+ # Read-write checks directory traversal
+ rw_perm = FilesystemPermission(allowed_subdirs=["loot", "artifacts"], read_only=False)
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ rw_perm.validate_request({"output_path": "../../etc/shadow"}, None)
+ assert "Directory traversal" in str(exc_info.value)
+
+ # Read-write checks authorized subdirectories
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ rw_perm.validate_request({"output_path": "system32/cmd.exe"}, None)
+ assert "outside of authorized subdirs" in str(exc_info.value)
+
+ # Valid path inside allowed subdirs
+ rw_perm.validate_request({"output_path": "loot/tickets/golden.kirbi"}, None)
+
+
+def test_vault_permission_strict_boundaries():
+ # Empty write_types blocks any writes
+ ro_vault = VaultPermission(read_types=["domain_creds"], write_types=[])
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ ro_vault.validate_request({"cred_type": "ntlm_hash"}, None)
+ assert "not authorized for storage" in str(exc_info.value)
+
+ # Valid read type allowed
+ ro_vault.validate_request({"read_type": "domain_creds"}, None)
+
+ # Invalid read type rejected
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ ro_vault.validate_request({"read_type": "aws_key"}, None)
+ assert "read type 'aws_key' not authorized" in str(exc_info.value)
+
+
+def test_process_permission_binary_whitelist():
+ proc_perm = ProcessPermission(allow_subprocesses=True, allowed_binaries=["smbclient", "rpcclient"])
+
+ # Allowed binary
+ proc_perm.validate_request({"binary": "/usr/bin/smbclient -L //10.0.0.1"}, None)
+
+ # Prohibited binary
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ proc_perm.validate_request({"binary": "/bin/bash -c id"}, None)
+ assert "Binary 'bash' is not authorized" in str(exc_info.value)
+
+
+def test_network_permission_protocol_and_host_port():
+ net_perm = NetworkPermission(protocols=["tcp"], ports=[88, 389])
+
+ # Extract port from target string
+ net_perm.validate_request({"target": "10.0.0.1:88"}, None)
+
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ net_perm.validate_request({"target": "10.0.0.1:22"}, None)
+ assert "Port 22 is not authorized" in str(exc_info.value)
+
+ # Protocol validation
+ with pytest.raises(SecurityCapabilityViolation) as exc_info:
+ net_perm.validate_request({"port": 88, "protocol": "udp"}, None)
+ assert "Protocol 'udp' is not authorized" in str(exc_info.value)
+
+
+async def test_module_contract_trips_lockout_circuit_breaker_on_module_result():
+ from ares.sdk import module_contract, LockoutCircuitBreaker, CircuitBreakerTripped, ModuleParams
+
+ lockout_cb = LockoutCircuitBreaker()
+
+ @module_contract(
+ circuit_breaker=lockout_cb,
+ )
+ class LockoutReportingModule(BaseModule[ModuleParams, ModuleResult]):
+ MODULE_ID = "test.lockout_reporter"
+
+ async def execute(self, ctx: ExecutionContext) -> ModuleResult:
+ return ModuleResult(
+ status="partial",
+ module_id=self.MODULE_ID,
+ raw={"locked_accounts": ["admin_ad"], "lockout_detected": True},
+ )
+
+ harness = ModuleTestHarness(LockoutReportingModule)
+ mod = LockoutReportingModule(settings=harness.settings, campaign=harness.campaign, noise=harness.noise)
+ ctx = harness.make_context()
+ await mod.execute(ctx)
+
+ # Breaker should now be OPEN
+ assert lockout_cb.state == CircuitBreakerState.OPEN
+ assert "admin_ad" in lockout_cb.locked_accounts
+
+ # Next execution must be blocked by circuit breaker
+ with pytest.raises(CircuitBreakerTripped):
+ await mod.execute(ctx)
+
diff --git a/tests/unit/test_security_audit_remediation.py b/tests/unit/test_security_audit_remediation.py
new file mode 100644
index 0000000..8cb647e
--- /dev/null
+++ b/tests/unit/test_security_audit_remediation.py
@@ -0,0 +1,554 @@
+"""Security Audit Remediation Regression Tests.
+
+Validates fixes for:
+- ARES-SEC-01: MCP SSE Transport network access control and ephemeral auth on external binds.
+- ARES-SEC-02: Strict campaign authorization on execution and feasibility endpoints.
+- ARES-SEC-03: Prevention of API key scope escalation based on caller role.
+"""
+from __future__ import annotations
+
+import base64
+import hashlib
+import os
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+
+# Ensure test environment variables
+os.environ.setdefault("ARES_SECRET_KEY", "test-sec-secret-key-min32-chars!!")
+os.environ.setdefault("ARES_ENCRYPTION_KEY", "test-enc-key-min32-chars-xxxxxxx")
+os.environ.setdefault("ARES_DEFAULT_ADMIN_PASSWORD", "TestApiPass1!")
+os.environ.setdefault("ARES_DEBUG", "true")
+os.environ.setdefault("ARES_BROWSER_ORIGIN", "http://localhost:5173")
+
+
+# ── Helpers for Auth and Principals ──────────────────────────────────────────
+
+_MOCK_ROLES: dict[str, str] = {}
+
+
+def _make_token(username: str, role: str) -> str:
+ from ares.core.config import AresSettings
+ from ares.core.security import create_access_token
+
+ _MOCK_ROLES[username] = role
+ s = AresSettings()
+ family_id = base64.urlsafe_b64encode(
+ hashlib.sha256(username.encode("utf-8")).digest()
+ ).rstrip(b"=").decode("ascii")
+ return create_access_token(
+ data={"sub": username, "sid": family_id, "ver": 1},
+ secret_key=s.secret_key_value,
+ expires_minutes=60,
+ )
+
+
+def _auth_headers(username: str, role: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {_make_token(username, role)}",
+ "Idempotency-Key": "22222222-2222-4222-8222-222222222222",
+ }
+
+
+# ── 1. ARES-SEC-01: MCP SSE Transport Access Control Tests ───────────────────
+
+class MockMcpServer:
+ async def handle_message(self, body: dict) -> dict | None:
+ return {"jsonrpc": "2.0", "id": body.get("id"), "result": "pong"}
+
+
+async def test_mcp_sse_loopback_allowed_without_api_key():
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key=None)
+
+ transport = httpx.ASGITransport(app=app, client=("127.0.0.1", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
+ # Loopback client: auth passes, proceeds to session validation (400 Bad Request)
+ res = await client.post("/messages?session_id=fake_sess", json={"jsonrpc": "2.0"})
+ assert res.status_code == 400
+ assert "Invalid or expired session_id" in res.json().get("error", "")
+
+
+async def test_mcp_sse_non_loopback_rejected_without_api_key():
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key=None)
+
+ # External IP client trying to access open MCP server without key
+ transport = httpx.ASGITransport(app=app, client=("192.168.1.105", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://192.168.1.1") as client:
+ res = await client.get("/sse")
+ # Non-loopback client without API key must be 401 Unauthorized
+ assert res.status_code == 401
+ assert "Unauthorized" in res.json().get("error", "")
+
+ res_msg = await client.post("/messages?session_id=fake_sess", json={"jsonrpc": "2.0"})
+ assert res_msg.status_code == 401
+
+
+async def test_mcp_sse_drive_by_cross_origin_rejected_without_api_key():
+ """Operator browser visits malicious site which attempts to CSRF/drive-by local MCP server."""
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key=None)
+
+ # Client IP is loopback (from operator's local browser), BUT Origin is malicious website
+ transport = httpx.ASGITransport(app=app, client=("127.0.0.1", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
+ # Cross-origin drive-by attempt from attacker.com
+ res = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"Origin": "https://malicious-attacker.com"},
+ )
+ assert res.status_code == 401
+ assert "Unauthorized" in res.json().get("error", "")
+
+ # GET /sse drive-by stream hijack attempt
+ res_sse = await client.get("/sse", headers={"Origin": "https://malicious-attacker.com"})
+ assert res_sse.status_code == 401
+
+
+async def test_mcp_sse_dns_rebinding_rejected_without_api_key():
+ """Attacker uses DNS rebinding (evil.com -> 127.0.0.1) against local MCP server."""
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key=None)
+
+ # Client IP is loopback, but Host header contains attacker-controlled domain
+ transport = httpx.ASGITransport(app=app, client=("127.0.0.1", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
+ res = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"Host": "rebind.attacker-domain.xyz:8765"},
+ )
+ assert res.status_code == 401
+ assert "Unauthorized" in res.json().get("error", "")
+
+
+async def test_mcp_sse_cross_site_fetch_rejected():
+ """Browser sends Sec-Fetch-Site: cross-site indicator."""
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key=None)
+
+ transport = httpx.ASGITransport(app=app, client=("127.0.0.1", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
+ res = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"Sec-Fetch-Site": "cross-site"},
+ )
+ assert res.status_code == 401
+
+
+async def test_mcp_sse_loopback_valid_origin_allowed():
+ """Legitimate local frontend (e.g. Vite on localhost:5173) connects to local MCP server."""
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key=None)
+
+ transport = httpx.ASGITransport(app=app, client=("127.0.0.1", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
+ res = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"Origin": "http://localhost:5173"},
+ )
+ # Auth succeeds; proceeds to MCP session check (400)
+ assert res.status_code == 400
+ assert "Invalid or expired session_id" in res.json().get("error", "")
+
+
+async def test_mcp_sse_non_loopback_allowed_with_valid_bearer_token():
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key="secret-token-xyz-12345")
+
+ transport = httpx.ASGITransport(app=app, client=("192.168.1.105", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://192.168.1.1") as client:
+ # Without token -> 401
+ res_no_auth = await client.get("/sse")
+ assert res_no_auth.status_code == 401
+
+ # With Bearer token -> auth passes, proceeds to session validation (400)
+ res_auth = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"Authorization": "Bearer secret-token-xyz-12345"},
+ )
+ assert res_auth.status_code == 400
+
+
+async def test_mcp_sse_non_loopback_allowed_with_header_or_query_key():
+ from ares.mcp.transport.sse import create_sse_app
+
+ server = MockMcpServer()
+ app = create_sse_app(server, api_key="network-key-999")
+
+ transport = httpx.ASGITransport(app=app, client=("10.0.0.42", 50000))
+ async with httpx.AsyncClient(transport=transport, base_url="http://10.0.0.1") as client:
+ # X-ARES-API-Key header -> auth passes (400)
+ res_hdr = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"X-ARES-API-Key": "network-key-999"},
+ )
+ assert res_hdr.status_code == 400
+
+ # Query param -> auth passes (400)
+ res_query = await client.post(
+ "/messages?session_id=fake_sess&api_key=network-key-999",
+ json={"jsonrpc": "2.0"},
+ )
+ assert res_query.status_code == 400
+
+ # Wrong token -> 401
+ res_bad = await client.get("/sse", headers={"Authorization": "Bearer wrong-token"})
+ assert res_bad.status_code == 401
+ res_bad_msg = await client.post(
+ "/messages?session_id=fake_sess",
+ json={"jsonrpc": "2.0"},
+ headers={"Authorization": "Bearer wrong-token"},
+ )
+ assert res_bad_msg.status_code == 401
+
+
+# ── 2. ARES-SEC-02: Campaign Authorization on Execution / Feasibility ───────
+
+def api_test_setup():
+ from ares.api.server import app, get_c_live_runtime, get_db, get_engine
+
+ db = MagicMock()
+ db.is_access_token_revoked = AsyncMock(return_value=False)
+ db.get_user = AsyncMock(return_value={"id": "usr-1", "username": "alice", "role": "operator"})
+
+ async def resolve_principal(subject, _jti, _family_id, auth_epoch):
+ role = _MOCK_ROLES.get(subject, "operator")
+ return {"id": f"uid-{subject}", "username": subject, "role": role, "auth_epoch": auth_epoch}
+
+ db.resolve_access_token_principal = AsyncMock(side_effect=resolve_principal)
+
+ campaigns = {
+ "camp-alice": {
+ "id": "camp-alice",
+ "name": "Alice Campaign",
+ "client": "Internal",
+ "operator": "alice",
+ "noise_profile": "normal",
+ "status": "created",
+ "scope_json": "[]",
+ "targets_json": '["10.0.0.1"]',
+ "notes": "",
+ }
+ }
+
+ async def get_campaign(cid):
+ return campaigns.get(cid)
+
+ db.get_campaign = AsyncMock(side_effect=get_campaign)
+ db.save_finding = AsyncMock()
+ db.save_loot = AsyncMock()
+ db.upsert_host = AsyncMock()
+ db.update_campaign_status = AsyncMock()
+ db.audit = AsyncMock()
+ db.create_api_key = AsyncMock(return_value=("key-123", "ares_key_mock_secret_abcdef123456"))
+
+ engine = MagicMock()
+ engine.bind_database = MagicMock()
+ fake_report = MagicMock()
+ fake_report.to_dict.return_value = {"feasibility": "high", "risk_score": 10}
+ engine.assess_module_feasibility = AsyncMock(return_value=fake_report)
+ fake_result = SimpleNamespace(
+ module_id="plugin.safe",
+ status="success",
+ findings=[],
+ raw_output={},
+ duration_ms=5.0,
+ )
+ fake_result.model_dump = lambda: {"module_id": "plugin.safe", "status": "success", "findings": []}
+ engine.run_module = AsyncMock(return_value=fake_result)
+ engine.dry_run_module = MagicMock(return_value={"status": "dry_run_ok"})
+ engine.dry_run_plan = MagicMock(return_value={"status": "dry_run_ok", "modules": []})
+
+ orig_state_db = getattr(app.state, "db", None)
+ orig_state_engine = getattr(app.state, "engine", None)
+ app.state.db = db
+ app.state.engine = engine
+
+ app.dependency_overrides[get_db] = lambda: db
+ app.dependency_overrides[get_engine] = lambda: engine
+
+ transport = httpx.ASGITransport(app=app)
+ client = httpx.AsyncClient(transport=transport, base_url="http://localhost")
+
+ yield client, db, engine, app
+
+ app.state.db = orig_state_db
+ app.state.engine = orig_state_engine
+ app.dependency_overrides.pop(get_db, None)
+ app.dependency_overrides.pop(get_engine, None)
+
+
+async def test_feasibility_cross_operator_rejected_with_404(api_test_setup):
+ client, db, engine, app = api_test_setup
+
+ # Bob (operator) tries to assess feasibility for Alice's campaign -> 404
+ bob_headers = _auth_headers("bob", "operator")
+ res = await client.post(
+ "/modules/plugin.safe/feasibility",
+ json={"campaign_id": "camp-alice", "target": "10.0.0.1", "params": {}},
+ headers=bob_headers,
+ )
+ assert res.status_code == 404
+ assert "Campaign not found" in res.json().get("detail", "")
+ engine.assess_module_feasibility.assert_not_awaited()
+
+
+async def test_feasibility_owner_operator_allowed(api_test_setup):
+ client, db, engine, app = api_test_setup
+
+ # Alice (the owner operator) assesses feasibility for her own campaign -> 200
+ alice_headers = _auth_headers("alice", "operator")
+ res = await client.post(
+ "/modules/plugin.safe/feasibility",
+ json={"campaign_id": "camp-alice", "target": "10.0.0.1", "params": {}},
+ headers=alice_headers,
+ )
+ assert res.status_code == 200
+ assert res.json()["campaign_id"] == "camp-alice"
+
+
+async def test_feasibility_team_lead_allowed(api_test_setup):
+ client, db, engine, app = api_test_setup
+
+ # Charlie (team_lead) assesses feasibility for Alice's campaign -> 200
+ lead_headers = _auth_headers("charlie", "team_lead")
+ res = await client.post(
+ "/modules/plugin.safe/feasibility",
+ json={"campaign_id": "camp-alice", "target": "10.0.0.1", "params": {}},
+ headers=lead_headers,
+ )
+ assert res.status_code == 200
+
+
+# ── 3. ARES-SEC-03: API Key Scope Privilege Escalation Defense ───────────────
+
+async def test_api_key_reporter_cannot_mint_write_or_admin(api_test_setup):
+ client, db, engine, app = api_test_setup
+
+ async def get_user(username):
+ return {"id": "uid-rep", "username": username, "role": "reporter"}
+
+ db.get_user = AsyncMock(side_effect=get_user)
+ rep_headers = _auth_headers("reporter_user", "reporter")
+
+ # Reporter requesting admin -> 403
+ res_admin = await client.post(
+ "/auth/api-keys",
+ json={"name": "test-admin-key", "scopes": "admin"},
+ headers=rep_headers,
+ )
+ assert res_admin.status_code == 403
+ assert "not authorized" in res_admin.json().get("detail", "")
+
+ # Reporter requesting write -> 403
+ res_write = await client.post(
+ "/auth/api-keys",
+ json={"name": "test-write-key", "scopes": "write"},
+ headers=rep_headers,
+ )
+ assert res_write.status_code == 403
+
+ # Reporter requesting read -> 200
+ res_read = await client.post(
+ "/auth/api-keys",
+ json={"name": "test-read-key", "scopes": "read"},
+ headers=rep_headers,
+ )
+ assert res_read.status_code == 200
+ assert "key" in res_read.json()
+
+
+async def test_api_key_operator_cannot_mint_admin(api_test_setup):
+ client, db, engine, app = api_test_setup
+
+ async def get_user(username):
+ return {"id": "uid-op", "username": username, "role": "operator"}
+
+ db.get_user = AsyncMock(side_effect=get_user)
+ op_headers = _auth_headers("op_user", "operator")
+
+ # Operator requesting admin -> 403
+ res_admin = await client.post(
+ "/auth/api-keys",
+ json={"name": "op-admin-key", "scopes": "admin"},
+ headers=op_headers,
+ )
+ assert res_admin.status_code == 403
+ assert "not authorized" in res_admin.json().get("detail", "")
+
+ # Operator requesting write -> 200
+ res_write = await client.post(
+ "/auth/api-keys",
+ json={"name": "op-write-key", "scopes": "write"},
+ headers=op_headers,
+ )
+ assert res_write.status_code == 200
+
+ # Operator requesting read -> 200
+ res_read = await client.post(
+ "/auth/api-keys",
+ json={"name": "op-read-key", "scopes": "read"},
+ headers=op_headers,
+ )
+ assert res_read.status_code == 200
+
+
+async def test_api_key_team_lead_can_mint_admin(api_test_setup):
+ client, db, engine, app = api_test_setup
+
+ async def get_user(username):
+ return {"id": "uid-lead", "username": username, "role": "team_lead"}
+
+ db.get_user = AsyncMock(side_effect=get_user)
+ lead_headers = _auth_headers("lead_user", "team_lead")
+
+ # Team Lead requesting admin -> 200
+ res_admin = await client.post(
+ "/auth/api-keys",
+ json={"name": "lead-admin-key", "scopes": "admin"},
+ headers=lead_headers,
+ )
+ assert res_admin.status_code == 200
+ assert "key" in res_admin.json()
+
+
+# ── 4. Deep Hardening: MCP Scope Invariance & Secret Masking Tests ────────────
+
+async def test_mcp_database_scope_strict_enforcement():
+ """Verify that real DB scope_json is strictly parsed and blocks out-of-scope targets."""
+ from ares.mcp.security import ConfirmationTokenManager, McpSecurityViolation
+ from ares.mcp.tools import McpToolRegistry
+
+ mock_db = MagicMock()
+ # Campaign configured strictly for 192.168.50.0/24 (no 10.0.0.0/8 allowed!)
+ mock_db.get_campaign = AsyncMock(return_value={
+ "id": "camp-strict-50",
+ "name": "Strict Scope Engagement",
+ "scope_json": '["192.168.50.0/24"]',
+ "targets_json": '["192.168.50.5"]',
+ })
+
+ token_mgr = ConfirmationTokenManager()
+ registry = McpToolRegistry(token_manager=token_mgr, db=mock_db)
+
+ # 1. Target in scope (192.168.50.5:445) -> succeeds
+ res_in = await registry.call_tool("ares_verify_target_scope", {
+ "campaign_id": "camp-strict-50",
+ "target": "192.168.50.5:445",
+ })
+ assert not res_in.isError
+ assert "APPROVED_FOR_TESTING" in res_in.content[0].text
+
+ # 2. Target OUT of scope (10.0.0.1: previously allowed by broad fallback!) -> must be REJECTED
+ res_out = await registry.call_tool("ares_verify_target_scope", {
+ "campaign_id": "camp-strict-50",
+ "target": "10.0.0.1",
+ })
+ assert not res_out.isError
+ assert "REJECTED_OUT_OF_SCOPE" in res_out.content[0].text
+
+ # 3. Dry-run execution on out-of-scope target must raise McpSecurityViolation
+ res_dry = await registry.call_tool("ares_dry_run_module", {
+ "campaign_id": "camp-strict-50",
+ "module_id": "ad.kerberoast",
+ "target": "10.0.0.1",
+ })
+ assert res_dry.isError
+ assert "SECURITY VIOLATION" in res_dry.content[0].text
+ assert "SCOPE VIOLATION [BLOCKED]" in res_dry.content[0].text
+
+
+async def test_mcp_nonexistent_campaign_rejected():
+ """Verify that querying a non-existent campaign ID in MCP fails closed."""
+ from ares.mcp.security import ConfirmationTokenManager
+ from ares.mcp.tools import McpToolRegistry
+
+ mock_db = MagicMock()
+ mock_db.get_campaign = AsyncMock(return_value=None) # Campaign does not exist!
+
+ token_mgr = ConfirmationTokenManager()
+ registry = McpToolRegistry(token_manager=token_mgr, db=mock_db)
+
+ res = await registry.call_tool("ares_verify_target_scope", {
+ "campaign_id": "camp-ghost-999",
+ "target": "10.0.0.1",
+ })
+ assert res.isError
+ assert "Campaign 'camp-ghost-999' not found in database" in res.content[0].text
+
+
+def test_mcp_scope_gate_port_and_naked_domain():
+ """Verify McpScopeGate handles port notation and naked domain rules."""
+ from ares.mcp.security import McpScopeGate
+
+ rules = ["10.0.0.0/24", "corp.local", "192.168.1.1"]
+
+ # IP with port matching CIDR
+ assert McpScopeGate.is_in_scope("10.0.0.5:445", rules) is True
+ # Hostname with port matching naked domain
+ assert McpScopeGate.is_in_scope("dc01.corp.local:88", rules) is True
+ # Exact host matching naked domain
+ assert McpScopeGate.is_in_scope("corp.local", rules) is True
+ # IP with port matching exact IP
+ assert McpScopeGate.is_in_scope("192.168.1.1:8080", rules) is True
+ # Out of scope
+ assert McpScopeGate.is_in_scope("10.0.1.5:445", rules) is False
+ assert McpScopeGate.is_in_scope("other.com", rules) is False
+
+
+def test_mcp_secret_masker_pem_block():
+ """Verify SecretMasker scrubs raw PEM private key blocks in strings."""
+ from ares.mcp.security import SecretMasker
+
+ fake_pem = (
+ "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEowIBAAKCAQEA0YpW3H...\n"
+ "-----END RSA PRIVATE KEY-----"
+ )
+ raw_output = f"Connecting to target... Found SSH key:\n{fake_pem}\nDone."
+ masked = SecretMasker.mask(raw_output)
+
+ assert "-----BEGIN RSA PRIVATE KEY-----" not in masked
+ assert "[REDACTED_PRIVATE_KEY_BLOCK]" in masked
+