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 scope firewall bypass, marketplace signature, and auth inconsistencies

Mafifrizib9416ee449c2
diff --git a/ares/api/dashboard/app.py b/ares/api/dashboard/app.py
index c14ebda..979faec 100644
--- a/ares/api/dashboard/app.py
+++ b/ares/api/dashboard/app.py
@@ -64,8 +64,12 @@ async def _require_dashboard_auth(
raise HTTPException(status_code=401, detail="Token revoked")
except HTTPException:
raise
- except Exception:
- pass # DB unavailable - still accept if token signature valid
+ except Exception as exc:
+ logger.warning("dashboard_auth_revocation_check_failed", error=str(exc))
+ raise HTTPException(
+ status_code=503,
+ detail="Authentication service temporarily unavailable: cannot verify token revocation status.",
+ )
return
# Check X-API-Key header
@@ -596,10 +600,16 @@ async def api_workers(_auth: None = Depends(_require_dashboard_auth)) -> dict[st
@dashboard_app.websocket("/ws/live")
async def websocket_live(websocket: WebSocket) -> None:
- # Auth via query param token (WebSocket cannot send Authorization header before connect)
+ # Auth via Authorization header first, fallback to query param
from ares.core.config import get_settings
from ares.core.security import decode_access_token
- token = websocket.query_params.get("token")
+ token = None
+ auth_header = websocket.headers.get("authorization")
+ if auth_header and auth_header.lower().startswith("bearer "):
+ token = auth_header[7:].strip()
+ if not token:
+ token = websocket.query_params.get("token")
+
if not token:
await websocket.close(code=4001, reason="Authentication required")
return
@@ -608,6 +618,21 @@ async def websocket_live(websocket: WebSocket) -> None:
if not payload:
await websocket.close(code=4001, reason="Invalid token")
return
+
+ # Check token revocation against shared DB
+ jti = payload.get("jti")
+ if jti:
+ shared_db = getattr(dashboard_app.state, "db", None)
+ if shared_db is not None:
+ try:
+ if await shared_db.is_access_token_revoked(jti):
+ await websocket.close(code=4001, reason="Token revoked")
+ return
+ except Exception as db_exc:
+ logger.warning("dashboard_ws_revocation_check_failed", error=str(db_exc))
+ await websocket.close(code=4003, reason="Revocation check unavailable")
+ return
+
await websocket.accept()
_live_connections.append(websocket)
logger.info("dashboard_ws_connect", total=len(_live_connections))
diff --git a/ares/api/server.py b/ares/api/server.py
index 93c36a3..db755b1 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -1330,11 +1330,13 @@ async def logout_all(
def _validate_password_complexity(v: str) -> str:
- """Enforce password complexity: min 12 chars, upper+lower+digit+special."""
+ """Enforce password complexity: min 12 chars, upper+lower+digit+special, max 72 bytes."""
import re
if len(v) < 12:
raise ValueError("Password must be at least 12 characters")
+ if len(v.encode("utf-8")) > 72:
+ raise ValueError("Password cannot exceed 72 UTF-8 bytes (bcrypt limit)")
if not re.search(r"[A-Z]", v):
raise ValueError("Password must contain at least one uppercase letter")
if not re.search(r"[a-z]", v):
@@ -1348,7 +1350,7 @@ def _validate_password_complexity(v: str) -> str:
class RegisterRequest(BaseModel):
username: str = Field(..., min_length=3, max_length=64)
- password: str = Field(..., min_length=12, max_length=128)
+ password: str = Field(..., min_length=12, max_length=72)
role: str = Field("reporter")
@field_validator("password")
@@ -1388,7 +1390,7 @@ async def register(
class ChangePasswordRequest(BaseModel):
current_password: str
- new_password: str = Field(..., min_length=12, max_length=128)
+ new_password: str = Field(..., min_length=12, max_length=72)
@field_validator("new_password")
@classmethod
diff --git a/ares/core/scope_firewall.py b/ares/core/scope_firewall.py
index 6fd2600..4d18bd2 100644
--- a/ares/core/scope_firewall.py
+++ b/ares/core/scope_firewall.py
@@ -115,6 +115,7 @@ class ScopeFirewall:
# Fast IP lookup cache (bounded to 1024 entries)
self._ip_cache: dict[str, bool] = {}
+ self._pinned_ip_cache: dict[str, str] = {}
self._blocked_attempts: list[dict[str, Any]] = []
@property
@@ -152,64 +153,73 @@ class ScopeFirewall:
return False
- def is_allowed_address(self, address: Any) -> bool:
- """Check if destination address is permitted under campaign scope."""
- host, _ = self._extract_host_and_port(address)
+ def resolve_and_pin_address(self, address: Any) -> tuple[bool, Any]:
+ """Check if destination address is permitted and return pinned address for DNS rebinding protection."""
+ host, port = self._extract_host_and_port(address)
if not host:
- return False
+ return False, address
lowered_host = host.lower()
# 1. Internal loopback IPC protection
if self.allow_loopback_ipc and lowered_host in _LOOPBACK_HOSTS:
- return True
+ return True, address
- # 2. Cloud module domain whitelist
+ # 2. Cloud module domain whitelist (preserves hostname for TLS SNI)
if self._is_cloud_allowed(lowered_host):
- return True
-
- # 3. Check fast IP cache
- if lowered_host in self._ip_cache:
- return self._ip_cache[lowered_host]
+ return True, address
- # 4. Check if host is an IP literal
+ # 3. Check if host is an IP literal
try:
addr = ipaddress.ip_address(lowered_host)
- # Loopback IP check
if self.allow_loopback_ipc and addr.is_loopback:
self._ip_cache[lowered_host] = True
- return True
+ return True, address
in_scope = any(addr in net for net in self._networks)
if len(self._ip_cache) < 1024:
self._ip_cache[lowered_host] = in_scope
- return in_scope
+ return in_scope, address
except ValueError:
pass # Not an IP literal - proceed to hostname verification
+ # 4. Check cached pinned resolution
+ if lowered_host in self._pinned_ip_cache:
+ pinned_ip = self._pinned_ip_cache[lowered_host]
+ if isinstance(address, tuple):
+ if len(address) == 2:
+ return True, (pinned_ip, address[1])
+ elif len(address) > 2:
+ return True, (pinned_ip, address[1], *address[2:])
+ return True, pinned_ip
+
+ if lowered_host in self._ip_cache and not self._ip_cache[lowered_host]:
+ return False, address
+
# 5. Hostname DNS resolution with re-entrancy lock
if _in_firewall_resolution.get():
- # Currently inside DNS resolution; allow query to resolver
- return True
+ return True, address
_token = _in_firewall_resolution.set(True)
try:
- # Resolve hostname using getaddrinfo
results = socket.getaddrinfo(
- lowered_host, None, socket.AF_UNSPEC, socket.SOCK_STREAM
+ lowered_host, port or 0, socket.AF_UNSPEC, socket.SOCK_STREAM
)
if not results:
logger.warning("scope_firewall_dns_empty", host=lowered_host)
- return False
+ if len(self._ip_cache) < 1024:
+ self._ip_cache[lowered_host] = False
+ return False, address
# Strict verification: All resolved IPs must be in scope
- resolved_in_scope = False
+ pinned_ip: str | None = None
for res in results:
raw_ip = res[4][0]
try:
ip_obj = ipaddress.ip_address(raw_ip)
if any(ip_obj in net for net in self._networks):
- resolved_in_scope = True
+ if pinned_ip is None:
+ pinned_ip = raw_ip
else:
logger.warning(
"scope_firewall_dns_resolved_out_of_scope",
@@ -217,31 +227,51 @@ class ScopeFirewall:
resolved_ip=raw_ip,
scope=self.scope_cidrs,
)
- resolved_in_scope = False
- break
+ if len(self._ip_cache) < 1024:
+ self._ip_cache[lowered_host] = False
+ return False, address
except ValueError:
- resolved_in_scope = False
- break
-
- if len(self._ip_cache) < 1024:
- self._ip_cache[lowered_host] = resolved_in_scope
- return resolved_in_scope
+ if len(self._ip_cache) < 1024:
+ self._ip_cache[lowered_host] = False
+ return False, address
+
+ if pinned_ip is not None:
+ if len(self._pinned_ip_cache) < 1024:
+ self._pinned_ip_cache[lowered_host] = pinned_ip
+ if len(self._ip_cache) < 1024:
+ self._ip_cache[lowered_host] = True
+
+ if isinstance(address, tuple):
+ if len(address) == 2:
+ return True, (pinned_ip, address[1])
+ elif len(address) > 2:
+ return True, (pinned_ip, address[1], *address[2:])
+ return True, pinned_ip
+
+ return False, address
except (socket.gaierror, TimeoutError, Exception) as exc:
logger.warning(
"scope_firewall_dns_failed",
host=lowered_host,
error=str(exc)[:100],
)
- # Offline lab / mock environment fallback: allow if explicitly defined in campaign targets/dc/domain
if lowered_host in self._explicit_hosts:
- return True
- return False # Fail closed
+ return True, address
+ return False, address
finally:
_in_firewall_resolution.reset(_token)
- def assert_allowed_address(self, address: Any) -> None:
- """Assert address is in scope; raises ScopeFirewallBlockError if not."""
- if not self.is_allowed_address(address):
+ def is_allowed_address(self, address: Any) -> bool:
+ """Check if destination address is permitted under campaign scope."""
+ allowed, _ = self.resolve_and_pin_address(address)
+ return allowed
+
+ def assert_allowed_address(self, address: Any) -> Any:
+ """Assert address is in scope; raises ScopeFirewallBlockError if not.
+ Returns pinned address for DNS rebinding protection.
+ """
+ allowed, pinned = self.resolve_and_pin_address(address)
+ if not allowed:
host, port = self._extract_host_and_port(address)
self._blocked_attempts.append(
{
@@ -274,11 +304,14 @@ class ScopeFirewall:
module_id=self.module_id,
scope_cidrs=self.scope_cidrs,
)
+ return pinned
# ── Global Socket & Transport Hooks ──────────────────────────────────────────
_orig_socket_connect = socket.socket.connect
+_orig_socket_connect_ex = socket.socket.connect_ex
_orig_socket_sendto = socket.socket.sendto
+_orig_socket_sendmsg = getattr(socket.socket, "sendmsg", None)
_orig_loop_create_connection = asyncio.base_events.BaseEventLoop.create_connection
_hooks_installed: bool = False
@@ -286,19 +319,58 @@ _hooks_installed: bool = False
@functools.wraps(_orig_socket_connect)
def _firewall_socket_connect(self: socket.socket, address: Any) -> None:
fw = _current_firewall.get()
+ target_address = address
if fw is not None and not _in_firewall_resolution.get():
- fw.assert_allowed_address(address)
- return _orig_socket_connect(self, address)
+ pinned = fw.assert_allowed_address(address)
+ if pinned is not None:
+ target_address = pinned
+ return _orig_socket_connect(self, target_address)
+
+
[email protected](_orig_socket_connect_ex)
+def _firewall_socket_connect_ex(self: socket.socket, address: Any) -> int:
+ fw = _current_firewall.get()
+ target_address = address
+ if fw is not None and not _in_firewall_resolution.get():
+ pinned = fw.assert_allowed_address(address)
+ if pinned is not None:
+ target_address = pinned
+ return _orig_socket_connect_ex(self, target_address)
@functools.wraps(_orig_socket_sendto)
def _firewall_socket_sendto(self: socket.socket, data: Any, *args: Any) -> int:
fw = _current_firewall.get()
- if fw is not None and not _in_firewall_resolution.get():
- address = args[-1] if args else None
+ new_args = list(args)
+ if fw is not None and not _in_firewall_resolution.get() and new_args:
+ address = new_args[-1]
if address is not None:
- fw.assert_allowed_address(address)
- return _orig_socket_sendto(self, data, *args)
+ pinned = fw.assert_allowed_address(address)
+ if pinned is not None:
+ new_args[-1] = pinned
+ return _orig_socket_sendto(self, data, *new_args)
+
+
+if _orig_socket_sendmsg is not None:
+
+ @functools.wraps(_orig_socket_sendmsg)
+ def _firewall_socket_sendmsg(
+ self: socket.socket, buffers: Any, *args: Any, **kwargs: Any
+ ) -> int:
+ fw = _current_firewall.get()
+ if fw is not None and not _in_firewall_resolution.get():
+ target_addr = kwargs.get("address")
+ if target_addr is None and len(args) >= 3:
+ target_addr = args[2]
+ if target_addr is not None:
+ pinned = fw.assert_allowed_address(target_addr)
+ if "address" in kwargs:
+ kwargs["address"] = pinned
+ elif len(args) >= 3:
+ args_list = list(args)
+ args_list[2] = pinned
+ args = tuple(args_list)
+ return _orig_socket_sendmsg(self, buffers, *args, **kwargs)
@functools.wraps(_orig_loop_create_connection)
@@ -311,10 +383,15 @@ async def _firewall_loop_create_connection(
**kwargs: Any,
) -> tuple[asyncio.Transport, asyncio.Protocol]:
fw = _current_firewall.get()
+ target_host = host
if fw is not None and not _in_firewall_resolution.get() and host is not None:
- fw.assert_allowed_address((host, port or 0))
+ pinned = fw.assert_allowed_address((host, port or 0))
+ if isinstance(pinned, tuple) and len(pinned) >= 2:
+ target_host = pinned[0]
+ if kwargs.get("ssl") and "server_hostname" not in kwargs and isinstance(host, str):
+ kwargs["server_hostname"] = host
return await _orig_loop_create_connection(
- self, protocol_factory, host=host, port=port, *args, **kwargs
+ self, protocol_factory, host=target_host, port=port, *args, **kwargs
)
@@ -325,7 +402,10 @@ def install_hooks() -> None:
return
socket.socket.connect = _firewall_socket_connect # type: ignore[assignment]
- socket.socket.sendto = _firewall_socket_sendto # type: ignore[assignment]
+ socket.socket.connect_ex = _firewall_socket_connect_ex # type: ignore[assignment]
+ socket.socket.sendto = _firewall_socket_sendto # type: ignore[assignment]
+ if _orig_socket_sendmsg is not None:
+ socket.socket.sendmsg = _firewall_socket_sendmsg # type: ignore[assignment]
asyncio.base_events.BaseEventLoop.create_connection = ( # type: ignore[assignment]
_firewall_loop_create_connection
)
@@ -340,7 +420,10 @@ def uninstall_hooks() -> None:
return
socket.socket.connect = _orig_socket_connect # type: ignore[assignment]
- socket.socket.sendto = _orig_socket_sendto # type: ignore[assignment]
+ socket.socket.connect_ex = _orig_socket_connect_ex # type: ignore[assignment]
+ socket.socket.sendto = _orig_socket_sendto # type: ignore[assignment]
+ if _orig_socket_sendmsg is not None:
+ socket.socket.sendmsg = _orig_socket_sendmsg # type: ignore[assignment]
asyncio.base_events.BaseEventLoop.create_connection = ( # type: ignore[assignment]
_orig_loop_create_connection
)
diff --git a/ares/core/security.py b/ares/core/security.py
index fc4f71b..c34a2cd 100644
--- a/ares/core/security.py
+++ b/ares/core/security.py
@@ -38,14 +38,21 @@ def _get_legacy_salt() -> bytes:
# ── Password hashing ──────────────────────────────────────────────────────────
# NOTE: Use bcrypt directly - passlib 1.7.4 is incompatible with bcrypt >= 4.0
-# which added an explicit 72-byte limit. We truncate + call bcrypt directly.
+# which added an explicit 72-byte limit. We enforce <= 72 bytes explicitly (fail closed).
def hash_password(password: str) -> str:
- pw_bytes = password.encode("utf-8")[:72]
+ pw_bytes = password.encode("utf-8")
+ if len(pw_bytes) > 72:
+ raise ValueError(
+ f"Password length ({len(pw_bytes)} bytes) exceeds bcrypt 72-byte limit. "
+ "Please use a password of 72 UTF-8 bytes or fewer."
+ )
return _bcrypt.hashpw(pw_bytes, _bcrypt.gensalt()).decode("utf-8")
def verify_password(plain: str, hashed: str) -> bool:
- pw_bytes = plain.encode("utf-8")[:72]
+ pw_bytes = plain.encode("utf-8")
+ if len(pw_bytes) > 72:
+ return False
hashed_bytes = hashed.encode("utf-8") if isinstance(hashed, str) else hashed
try:
return _bcrypt.checkpw(pw_bytes, hashed_bytes)
diff --git a/ares/db/execution_lifecycle.py b/ares/db/execution_lifecycle.py
index 67edb00..32a069c 100644
--- a/ares/db/execution_lifecycle.py
+++ b/ares/db/execution_lifecycle.py
@@ -3583,29 +3583,34 @@ class ExecutionLifecycleStore:
return None
try:
from ares.modules.descriptors import (
+ get_descriptor,
prepare_admission_parameters,
- require_descriptor,
)
- descriptor = require_descriptor(intent.module_id)
- if ExecutionLifecycleStore._raw_credential_material_present(
- intent.raw_parameters,
- descriptor.parameter_fields,
- ):
- return None
- canonical, extracted = prepare_admission_parameters(
- intent.module_id, intent.raw_parameters
- )
- values = {key: canonical.values[key] for key in sorted(canonical.values)}
- destination_refs = tuple(
- sorted(
- {
- (item.kind.value, str(item.value).strip().lower())
- for item in extracted
- if str(item.value).strip()
- }
+ descriptor = get_descriptor(intent.module_id)
+ if descriptor is not None:
+ if ExecutionLifecycleStore._raw_credential_material_present(
+ intent.raw_parameters,
+ descriptor.parameter_fields,
+ ):
+ return None
+ canonical, extracted = prepare_admission_parameters(
+ intent.module_id, intent.raw_parameters
+ )
+ values = {key: canonical.values[key] for key in sorted(canonical.values)}
+ destination_refs = tuple(
+ sorted(
+ {
+ (item.kind.value, str(item.value).strip().lower())
+ for item in extracted
+ if str(item.value).strip()
+ }
+ )
)
- )
+ else:
+ # Dynamic / plugin modules without formal Phase 5C descriptor (e.g. RFC-001 modules)
+ values = {key: intent.raw_parameters[key] for key in sorted(intent.raw_parameters)}
+ destination_refs = ()
canonical_json = json.dumps(
values,
sort_keys=True,
diff --git a/ares/marketplace/installer.py b/ares/marketplace/installer.py
index c77efb3..9ef33b8 100644
--- a/ares/marketplace/installer.py
+++ b/ares/marketplace/installer.py
@@ -385,7 +385,7 @@ class ModuleInstaller:
"success": True,
"version": manifest.version,
"path": str(manifest.plugin_dir) if manifest.plugin_dir else "",
- "verified": verify_signature,
+ "verified": manifest.verified,
"module_id": manifest.module_id,
"name": manifest.name,
}
@@ -504,9 +504,52 @@ class ModuleInstaller:
urllib.request.urlretrieve(url, str(local))
except Exception as e:
raise ConnectionError(f"Failed to download {url}: {e}") from e
- # Verify BEFORE installing - if hash fails, file never touches plugin dir
+ # Verify BEFORE installing - fail-closed cryptographic check
+ is_cryptographically_verified = False
if verify_signature and local.exists():
- # Read manifest from tmp file to get sha256 without installing
+ # 1. Try to fetch detached signature (.sig) if available
+ sig_file = local.with_suffix(local.suffix + ".sig")
+ try:
+ import httpx
+ with httpx.Client(follow_redirects=False, timeout=10) as client:
+ sig_resp = client.get(f"{url}.sig")
+ if sig_resp.status_code == 200 and sig_resp.content:
+ sig_file.write_bytes(sig_resp.content)
+ except Exception:
+ pass
+
+ # If detached .sig exists, verify via Ed25519 subsystem
+ if sig_file.exists():
+ try:
+ from ares.core.signing import ModuleVerifier, SigningPolicy
+ verifier = ModuleVerifier(policy=SigningPolicy.REQUIRE_SIGNED)
+ v_res = verifier.verify_file(local)
+ if v_res.blocked or not v_res.trusted:
+ raise ValueError(
+ f"Module from {url} failed cryptographic signature verification: "
+ f"{v_res.error or 'untrusted signature'}. File was NOT installed."
+ )
+ is_cryptographically_verified = True
+ logger.info("marketplace_sig_verified", url=url, key_id=v_res.key_id)
+ except ValueError:
+ raise
+ except Exception as sig_err:
+ logger.warning("marketplace_sig_check_error", error=str(sig_err))
+
+ # 2. Try to fetch sidecar manifest.json if present
+ sidecar_manifest = local.parent / "manifest.json"
+ if not sidecar_manifest.exists() and "/" in url:
+ try:
+ manifest_url = url.rsplit("/", 1)[0] + "/manifest.json"
+ import httpx
+ with httpx.Client(follow_redirects=False, timeout=10) as client:
+ m_resp = client.get(manifest_url)
+ if m_resp.status_code == 200 and m_resp.content:
+ sidecar_manifest.write_bytes(m_resp.content)
+ except Exception:
+ pass
+
+ # Read manifest from tmp file or sidecar to check sha256
_tmp_manifest = self._read_manifest_from_file(local)
if _tmp_manifest and _tmp_manifest.get("sha256"):
import hashlib
@@ -519,16 +562,19 @@ class ModuleInstaller:
f"got {actual_hash[:16]}... "
"File was NOT installed. Use verify_signature=False to override (not recommended)."
)
- else:
- logger.warning(
- "marketplace_no_signature: module has no sha256 in manifest "
- " - cannot verify integrity. Set verify_signature=False to silence.",
- url=url,
+ is_cryptographically_verified = True
+
+ # Fail-closed: verify_signature=True requires an authentic signature or manifest hash
+ if not is_cryptographically_verified:
+ raise ValueError(
+ f"Module from {url} has no cryptographic signature (.sig) or manifest SHA-256 hash. "
+ "Refusing to install unverified module under verify_signature=True (fail-closed). "
+ "Provide a valid signature/manifest, or explicitly pass verify_signature=False to override."
)
+
manifest = self._install_single_file(local, source_url=url, force=force)
- # Post-install: set verified flag if hash matched above
- if verify_signature and manifest.sha256:
- manifest.verified = True
+ # Post-install: set verified flag only if cryptographic verification passed
+ manifest.verified = is_cryptographically_verified
return manifest
def _install_github(self, spec: str, force: bool,
@@ -536,19 +582,28 @@ class ModuleInstaller:
"""
spec formats:
github.com/user/repo
- github.com/user/repo/blob/main/module.py
+ github.com/user/[email protected]
+ github.com/user/repo@<commit_sha>
+ github.com/user/repo/blob/<ref>/module.py
"""
spec = spec.replace("github.com/", "")
- parts = spec.split("/")
+ ref = "main"
+ if "@" in spec:
+ spec, ref = spec.split("@", 1)
+ parts = spec.split("/")
if len(parts) >= 2:
user, repo = parts[0], parts[1]
- file_path = "/".join(parts[4:]) if len(parts) > 4 else f"{repo}.py"
- raw_url = f"https://raw.githubusercontent.com/{user}/{repo}/main/{file_path}"
+ if len(parts) > 2 and parts[2] in ("blob", "tree", "commit") and len(parts) > 3:
+ ref = parts[3]
+ file_path = "/".join(parts[4:]) if len(parts) > 4 else f"{repo}.py"
+ else:
+ file_path = "/".join(parts[2:]) if len(parts) > 2 else f"{repo}.py"
+ raw_url = f"https://raw.githubusercontent.com/{user}/{repo}/{ref}/{file_path}"
else:
raise ValueError(f"Invalid GitHub spec: {spec}")
- logger.info("marketplace_github_install", url=raw_url)
+ logger.info("marketplace_github_install", url=raw_url, ref=ref)
return self._install_url(raw_url, force, verify_signature=verify_signature)
def _install_community(self, short_name: str, force: bool) -> ModuleManifest:
diff --git a/tests/unit/test_core_edge_cases.py b/tests/unit/test_core_edge_cases.py
index 4436870..7283bfb 100644
--- a/tests/unit/test_core_edge_cases.py
+++ b/tests/unit/test_core_edge_cases.py
@@ -980,6 +980,21 @@ class TestSecurityBoundaries:
assert verify_password("", h) is False
assert verify_password("correct_password" + "\x00", h) is False # null terminator
+ def test_password_72_byte_limit_no_silent_truncation(self):
+ """Passwords exceeding 72 UTF-8 bytes must raise ValueError, not silently truncate."""
+ from ares.core.security import hash_password, verify_password
+ import pytest
+
+ # 73-character password must raise ValueError on hash
+ long_pass = "A" * 73
+ with pytest.raises(ValueError, match="exceeds bcrypt 72-byte limit"):
+ hash_password(long_pass)
+
+ # verify_password must return False for > 72 bytes
+ valid_hash = hash_password("A" * 70)
+ assert verify_password("A" * 70, valid_hash) is True
+ assert verify_password("A" * 70 + "EXTRA", valid_hash) is False # No collision!
+
def test_api_key_prefix_validation(self):
"""API key verification must reject keys without ares_ prefix."""
# This tests that random strings can't bypass the prefix check
diff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.py
index 0116542..a9aa8cc 100644
--- a/tests/unit/test_hardening.py
+++ b/tests/unit/test_hardening.py
@@ -663,6 +663,61 @@ class TestMarketplaceAndCrackerHardening:
with pytest.raises(ValueError, match="missing hostname"):
installer._install_url("https://", force=False)
+ def test_marketplace_installer_fail_closed_without_signature(self, monkeypatch):
+ """When verify_signature=True, modules without signature or hash must fail-closed."""
+ from ares.marketplace.installer import ModuleInstaller
+ import httpx
+
+ installer = ModuleInstaller()
+
+ # Mock httpx to return sample module content for .py and 404 for .sig / manifest
+ def mock_get(self, url, *args, **kwargs):
+ req = httpx.Request("GET", url)
+ if url.endswith(".py"):
+ return httpx.Response(
+ 200, request=req, content=b"class DummyModule:\n MODULE_ID = 'test.dummy'\n"
+ )
+ return httpx.Response(404, request=req)
+
+ monkeypatch.setattr(httpx.Client, "get", mock_get)
+
+ with pytest.raises(ValueError, match="Refusing to install unverified module under verify_signature=True"):
+ installer._install_url("https://example.com/dummy.py", force=False, verify_signature=True)
+
+ def test_marketplace_accurate_verified_status(self, tmp_path, monkeypatch):
+ """Status returned by install_as_dict must match manifest.verified, not request flag."""
+ from ares.marketplace.installer import ModuleInstaller, ModuleManifest
+
+ installer = ModuleInstaller()
+ mock_manifest = ModuleManifest(
+ module_id="test.dummy",
+ name="test_dummy",
+ version="1.0.0",
+ verified=False, # Unverified
+ )
+ monkeypatch.setattr(installer, "install", lambda *a, **kw: mock_manifest)
+
+ res = installer.install_as_dict("https://example.com/dummy.py", verify_signature=False)
+ assert res["verified"] is False # Must not return True or request flag!
+
+ def test_marketplace_github_spec_supports_immutable_ref(self, monkeypatch):
+ """GitHub spec with @<ref> must resolve to immutable ref in raw URL."""
+ from ares.marketplace.installer import ModuleInstaller
+
+ installer = ModuleInstaller()
+ captured_url = None
+
+ def mock_install_url(url, force, verify_signature):
+ nonlocal captured_url
+ captured_url = url
+ from ares.marketplace.installer import ModuleManifest
+ return ModuleManifest(module_id="test.gh")
+
+ monkeypatch.setattr(installer, "_install_url", mock_install_url)
+
+ installer._install_github("github.com/user/[email protected]", force=False)
+ assert captured_url == "https://raw.githubusercontent.com/user/repo/v2.1.0/repo.py"
+
def test_cracker_worker_cross_platform_tmpdir(self, tmp_path):
import tempfile
from unittest.mock import MagicMock
diff --git a/tests/unit/test_scope_firewall.py b/tests/unit/test_scope_firewall.py
index 802cf49..c28ca72 100644
--- a/tests/unit/test_scope_firewall.py
+++ b/tests/unit/test_scope_firewall.py
@@ -107,6 +107,56 @@ class TestScopeFirewallInterception:
finally:
s.close()
+ @pytest.mark.asyncio
+ async def test_socket_connect_ex_intercepted(self, sample_campaign: Campaign):
+ """Regression test: connect_ex must be intercepted and raise ScopeFirewallBlockError when out-of-scope."""
+ async with scope_firewall_guard(sample_campaign, module_id="lateral.ntlm_relay"):
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ with pytest.raises(ScopeFirewallBlockError) as exc_info:
+ s.connect_ex(("1.1.1.1", 445))
+ assert exc_info.value.target_host == "1.1.1.1"
+ assert exc_info.value.target_port == 445
+ assert exc_info.value.module_id == "lateral.ntlm_relay"
+ finally:
+ s.close()
+
+ @pytest.mark.asyncio
+ async def test_socket_sendmsg_intercepted(self, sample_campaign: Campaign):
+ """Regression test: sendmsg (if available on platform) must be intercepted."""
+ if not hasattr(socket.socket, "sendmsg"):
+ pytest.skip("socket.sendmsg not supported on this platform")
+ async with scope_firewall_guard(sample_campaign, module_id="recon.sendmsg"):
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ with pytest.raises(ScopeFirewallBlockError) as exc_info:
+ s.sendmsg([b"data"], [], 0, ("1.1.1.1", 53))
+ assert exc_info.value.target_host == "1.1.1.1"
+ finally:
+ s.close()
+
+ def test_dns_rebinding_address_pinning(self, sample_campaign: Campaign, monkeypatch):
+ """Verify that DNS resolution pins the validated IP to prevent DNS rebinding."""
+ from ares.core.scope_firewall import ScopeFirewall
+
+ fw = ScopeFirewall(campaign=sample_campaign, module_id="test.rebinding")
+
+ # Mock getaddrinfo to return 10.0.0.99 (in-scope for 10.0.0.0/24)
+ mock_addrinfo = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.99", 80))
+ ]
+ monkeypatch.setattr(socket, "getaddrinfo", lambda *args, **kwargs: mock_addrinfo)
+
+ allowed, pinned = fw.resolve_and_pin_address(("rebind-target.internal", 80))
+ assert allowed is True
+ assert pinned == ("10.0.0.99", 80)
+
+ # Subsequent call should return cached pinned IP without re-querying DNS
+ monkeypatch.setattr(socket, "getaddrinfo", lambda *args, **kwargs: [])
+ allowed2, pinned2 = fw.resolve_and_pin_address(("rebind-target.internal", 80))
+ assert allowed2 is True
+ assert pinned2 == ("10.0.0.99", 80)
+
@pytest.mark.asyncio
async def test_asyncio_create_connection_intercepted(self, sample_campaign: Campaign):
loop = asyncio.get_running_loop()
diff --git a/tests/unit/test_security_critical.py b/tests/unit/test_security_critical.py
index e46cc21..7b233ae 100644
--- a/tests/unit/test_security_critical.py
+++ b/tests/unit/test_security_critical.py
@@ -422,6 +422,28 @@ class TestDashboardAuthentication:
_run(_run_test())
+ def test_dashboard_auth_fails_closed_when_db_error(self, monkeypatch):
+ """When revocation check database fails, request must return 503 (fail closed), not 200."""
+ from ares.db.database import AresDatabase
+
+ async def mock_create(*a, **kw):
+ raise ConnectionError("Database cluster unreachable")
+
+ monkeypatch.setattr(AresDatabase, "create", mock_create)
+
+ async def _run_test():
+ import httpx
+ from ares.api.dashboard.app import dashboard_app
+
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=dashboard_app),
+ base_url="http://localhost",
+ ) as c:
+ r = await c.get("/api/campaigns", headers=_auth("alice", "operator"))
+ assert r.status_code == 503
+
+ _run(_run_test())
+
# ══════════════════════════════════════════════════════════════════════
# TEST CLASS 3 - RBAC ENFORCEMENT PER ROLE