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): harden os-level firewall, dns failure, proxy concurrency, dynamic descriptors, and marketplace authenticity

Mafifrizi31d639d4bbe1
diff --git a/ares/core/scope_firewall.py b/ares/core/scope_firewall.py
index 76c37f1..75177fc 100644
--- a/ares/core/scope_firewall.py
+++ b/ares/core/scope_firewall.py
@@ -27,6 +27,7 @@ import socket
import subprocess
import sys
import threading
+import urllib.request
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, AsyncGenerator, Generator
@@ -291,8 +292,7 @@ class ScopeFirewall:
host=lowered_host,
error=str(exc)[:100],
)
- if lowered_host in self._explicit_hosts:
- return True, address
+ # Fail closed: If DNS resolution fails, the destination IP cannot be verified or pinned.
return False, address
finally:
_in_firewall_resolution.reset(_token)
@@ -349,9 +349,16 @@ _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
+_orig_urllib_getproxies = urllib.request.getproxies
_hooks_installed: bool = False
+def _firewall_getproxies() -> dict[str, str]:
+ if _current_firewall.get() is not None:
+ return {}
+ return _orig_urllib_getproxies()
+
+
@functools.wraps(_orig_socket_connect)
def _firewall_socket_connect(self: socket.socket, address: Any) -> None:
fw = _current_firewall.get()
@@ -445,6 +452,7 @@ def install_hooks() -> None:
asyncio.base_events.BaseEventLoop.create_connection = ( # type: ignore[assignment]
_firewall_loop_create_connection
)
+ urllib.request.getproxies = _firewall_getproxies # type: ignore[assignment]
_hooks_installed = True
logger.debug("scope_firewall_hooks_installed")
@@ -463,6 +471,7 @@ def uninstall_hooks() -> None:
asyncio.base_events.BaseEventLoop.create_connection = ( # type: ignore[assignment]
_orig_loop_create_connection
)
+ urllib.request.getproxies = _orig_urllib_getproxies # type: ignore[assignment]
_hooks_installed = False
logger.debug("scope_firewall_hooks_uninstalled")
@@ -574,19 +583,37 @@ class OSFirewallController:
elif sys.platform.startswith("linux"):
pid = str(os.getpid())
- cmd = [
+ # Rule 1: Allow loopback for this process
+ cmd_lo = [
"iptables", "-I", "OUTPUT", "1",
"-m", "owner", "--pid-owner", pid,
+ "-o", "lo",
+ "-j", "ACCEPT",
+ "-m", "comment", "--comment", rule_name,
+ ]
+ # Rule 2: Allow authorized scope CIDRs for this process
+ cmd_scope = [
+ "iptables", "-I", "OUTPUT", "2",
+ "-m", "owner", "--pid-owner", pid,
"-d", cidrs_str,
"-j", "ACCEPT",
"-m", "comment", "--comment", rule_name,
]
- res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
+ # Rule 3: DROP all other outbound egress from this process (strict allowlist)
+ cmd_drop = [
+ "iptables", "-I", "OUTPUT", "3",
+ "-m", "owner", "--pid-owner", pid,
+ "-j", "DROP",
+ "-m", "comment", "--comment", rule_name,
+ ]
+ subprocess.run(cmd_lo, capture_output=True, text=True, timeout=5)
+ res = subprocess.run(cmd_scope, capture_output=True, text=True, timeout=5)
+ subprocess.run(cmd_drop, capture_output=True, text=True, timeout=5)
if res.returncode == 0:
applied.append(rule_name)
with cls._lock:
cls._active_rules.add(rule_name)
- logger.info("os_firewall_rule_applied", rule=rule_name, cidrs=scope_cidrs, platform="linux")
+ logger.info("os_firewall_rule_applied", rule=rule_name, cidrs=scope_cidrs, platform="linux", mode="strict_pid_allowlist")
else:
logger.warning("os_firewall_rule_failed", rule=rule_name, error=res.stderr.strip())
@@ -611,6 +638,8 @@ class OSFirewallController:
res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
if res.returncode == 0:
removed += 1
+ cmd_drop = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", rule_name, "-j", "DROP"]
+ subprocess.run(cmd_drop, capture_output=True, text=True, timeout=5)
except Exception as exc:
logger.warning("os_firewall_remove_failed", rule=rule_name, error=str(exc))
finally:
@@ -649,6 +678,32 @@ _PROXY_KEYS: tuple[str, ...] = (
"all_proxy",
)
+_proxy_lock = threading.Lock()
+_proxy_guard_count = 0
+_saved_global_proxies: dict[str, str] = {}
+
+
+def _enter_proxy_neutralization() -> None:
+ """Thread-safe, re-entrant proxy neutralization across concurrent/nested tasks."""
+ global _proxy_guard_count
+ with _proxy_lock:
+ if _proxy_guard_count == 0:
+ for k in _PROXY_KEYS:
+ if k in os.environ:
+ _saved_global_proxies[k] = os.environ.pop(k)
+ _proxy_guard_count += 1
+
+
+def _exit_proxy_neutralization() -> None:
+ """Restore proxy environment variables once all active firewall contexts exit."""
+ global _proxy_guard_count
+ with _proxy_lock:
+ _proxy_guard_count = max(0, _proxy_guard_count - 1)
+ if _proxy_guard_count == 0:
+ for k, v in _saved_global_proxies.items():
+ os.environ[k] = v
+ _saved_global_proxies.clear()
+
@contextlib.asynccontextmanager
async def scope_firewall_guard(
@@ -689,7 +744,7 @@ async def scope_firewall_guard(
os_rules = OSFirewallController.apply_rules(campaign, fw.scope_cidrs)
# Neutralize proxy environment variables that could route traffic out-of-scope
- saved_proxies = {k: os.environ.pop(k) for k in _PROXY_KEYS if k in os.environ}
+ _enter_proxy_neutralization()
try:
yield fw
@@ -697,7 +752,7 @@ async def scope_firewall_guard(
_current_firewall.reset(token)
if os_rules:
OSFirewallController.remove_rules(os_rules)
- os.environ.update(saved_proxies)
+ _exit_proxy_neutralization()
@contextlib.contextmanager
@@ -739,7 +794,7 @@ def scope_firewall_sync_guard(
os_rules = OSFirewallController.apply_rules(campaign, fw.scope_cidrs)
# Neutralize proxy environment variables that could route traffic out-of-scope
- saved_proxies = {k: os.environ.pop(k) for k in _PROXY_KEYS if k in os.environ}
+ _enter_proxy_neutralization()
try:
yield fw
@@ -747,4 +802,4 @@ def scope_firewall_sync_guard(
_current_firewall.reset(token)
if os_rules:
OSFirewallController.remove_rules(os_rules)
- os.environ.update(saved_proxies)
+ _exit_proxy_neutralization()
diff --git a/ares/db/execution_lifecycle.py b/ares/db/execution_lifecycle.py
index 6fb30e0..c639d63 100644
--- a/ares/db/execution_lifecycle.py
+++ b/ares/db/execution_lifecycle.py
@@ -3588,44 +3588,30 @@ class ExecutionLifecycleStore:
)
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()
- }
- )
+ if descriptor is None:
+ # C-LIVE generation-11 strictly requires a proven security contract.
+ # Modules lacking a registered descriptor cannot prove their capabilities,
+ # opsec noise, credential policies, or parameter schema, and fail-closed.
+ return 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)}
- extracted_dest_list: list[tuple[str, str]] = []
- for d_key in ("target", "targets", "host", "hosts", "rhost", "rhosts", "dc", "server"):
- if d_key in intent.raw_parameters:
- v = intent.raw_parameters[d_key]
- if isinstance(v, (list, tuple)):
- for item in v:
- if isinstance(item, str) and item.strip():
- extracted_dest_list.append(("host", item.strip().lower()))
- elif isinstance(v, str) and v.strip():
- extracted_dest_list.append(("host", v.strip().lower()))
- for d_key in ("domain", "realm"):
- if d_key in intent.raw_parameters:
- v = intent.raw_parameters[d_key]
- if isinstance(v, str) and v.strip():
- extracted_dest_list.append(("domain", v.strip().lower()))
- destination_refs = tuple(sorted(set(extracted_dest_list)))
+ )
canonical_json = json.dumps(
values,
sort_keys=True,
diff --git a/ares/marketplace/installer.py b/ares/marketplace/installer.py
index f0fffc8..218aa3a 100644
--- a/ares/marketplace/installer.py
+++ b/ares/marketplace/installer.py
@@ -504,77 +504,76 @@ 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 - fail-closed cryptographic check
- is_cryptographically_verified = False
- if verify_signature and local.exists():
- # 1. Try to fetch detached signature (.sig) if available
- sig_file = local.with_suffix(local.suffix + ".sig")
+ # Verification BEFORE installing
+ is_signature_verified = False
+ is_hash_verified = False
+
+ # Check integrity via manifest SHA-256 if sidecar/manifest is 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:
- sig_resp = client.get(f"{url}.sig")
- if sig_resp.status_code == 200 and sig_resp.content:
- sig_file.write_bytes(sig_resp.content)
+ 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
- # 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
- actual_hash = hashlib.sha256(local.read_bytes()).hexdigest()
- expected = _tmp_manifest["sha256"]
- if actual_hash != expected:
- raise ValueError(
- f"Module from {url} failed integrity check BEFORE install: "
- f"expected SHA-256 {expected[:16]}... "
- f"got {actual_hash[:16]}... "
- "File was NOT installed. Use verify_signature=False to override (not recommended)."
- )
- is_cryptographically_verified = True
-
- # Fail-closed: verify_signature=True requires an authentic signature or manifest hash
- if not is_cryptographically_verified:
+ _tmp_manifest = self._read_manifest_from_file(local)
+ if _tmp_manifest and _tmp_manifest.get("sha256"):
+ import hashlib
+ actual_hash = hashlib.sha256(local.read_bytes()).hexdigest()
+ expected = _tmp_manifest["sha256"]
+ if actual_hash != expected:
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."
+ f"Module from {url} failed integrity check BEFORE install: "
+ f"expected SHA-256 {expected[:16]}... "
+ f"got {actual_hash[:16]}... File was NOT installed."
)
+ is_hash_verified = True
+
+ # If detached .sig exists, verify authenticity via Ed25519 subsystem
+ 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 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_signature_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))
+
+ # When verify_signature=True, cryptographic authenticity (Ed25519 signature) is strictly required
+ if verify_signature and not is_signature_verified:
+ raise ValueError(
+ f"Module from {url} has no valid Ed25519 cryptographic signature (.sig). "
+ "Refusing to install unverified module under verify_signature=True (fail-closed). "
+ "An unauthenticated manifest hash from the same origin does not provide cryptographic authenticity. "
+ "Sign the module with a trusted key, or explicitly pass verify_signature=False to override."
+ )
manifest = self._install_single_file(local, source_url=url, force=force)
- # Post-install: set verified flag only if cryptographic verification passed
- manifest.verified = is_cryptographically_verified
+ # Post-install: verified flag is strictly True ONLY if cryptographic Ed25519 signature passed
+ manifest.verified = is_signature_verified
return manifest
def _install_github(self, spec: str, force: bool,
@@ -667,29 +666,40 @@ class ModuleInstaller:
if not deps:
return
- # Allowlist regex - rejects pip flags (--index-url, etc.) and shell injection
+ # Check operator configuration: auto-installing pip deps from marketplace modules
+ # is disabled by default for supply chain isolation.
+ allow_deps = _os.getenv("ARES_MARKETPLACE_INSTALL_DEPS", "0").lower() in ("1", "true", "yes")
+ if not allow_deps:
+ logger.warning(
+ "marketplace_pip_deps_skipped",
+ deps=deps,
+ reason="Automatic dependency installation is disabled by default (ARES_MARKETPLACE_INSTALL_DEPS=0). "
+ "Dependencies must be reviewed and installed manually.",
+ )
+ return
+
+ # Strict validation: Only exact-pinned package specs allowed (e.g. package==1.2.3)
import re
- _DEP_RE = re.compile(
- r"^[a-zA-Z0-9]" # must start with alphanumeric
- r"[a-zA-Z0-9._-]*" # package name chars
- r"(\[[\w,\s]+\])?" # optional extras e.g. [security,async]
- r"(==|>=|<=|~=|!=|>|<)?" # optional version operator
- r"[\w.*]*$" # optional version value
+ _EXACT_DEP_RE = re.compile(
+ r"^[a-zA-Z0-9][a-zA-Z0-9._-]*"
+ r"(\[[a-zA-Z0-9._,-]+\])?"
+ r"==[a-zA-Z0-9._+-]+$"
)
- invalid = [d for d in deps if not _DEP_RE.match(d)]
+ invalid = [d for d in deps if not _EXACT_DEP_RE.match(d)]
if invalid:
raise ValueError(
- f"Dependency validation failed - rejected unsafe dep string(s): {invalid}. "
- "Only PEP 508 package specifiers are allowed (no flags, no URLs, no shell)."
+ f"Supply-chain policy violation: unpinned or unsafe dependency specifications rejected: {invalid}. "
+ "Every marketplace dependency must be strictly pinned with exact version (e.g., 'package==1.2.3') "
+ "to prevent supply-chain drift and dependency hijacking."
)
logger.info("marketplace_installing_deps", deps=deps)
import subprocess
subprocess.run(
- [sys.executable, "-m", "pip", "install", "--quiet",
- "--break-system-packages", *deps],
+ [sys.executable, "-m", "pip", "install", "--quiet", "--no-deps",
+ "--isolated", "--break-system-packages", *deps],
check=True,
- timeout=300, # 5 minutes max - prevents hang on network issues
+ timeout=120,
)
def _infer_manifest_from_file(self, path: Path, source_url: str = "") -> ModuleManifest:
diff --git a/ares/modules/descriptors.py b/ares/modules/descriptors.py
index 67b768d..7728154 100644
--- a/ares/modules/descriptors.py
+++ b/ares/modules/descriptors.py
@@ -12,6 +12,7 @@ import hashlib
import hmac
import json
import re
+import threading
import types
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
@@ -8796,10 +8797,32 @@ FIRST_PARTY_DESCRIPTORS: Mapping[str, ModuleDescriptor] = types.MappingProxyType
)
+_DYNAMIC_DESCRIPTORS: dict[str, ModuleDescriptor] = {}
+_dynamic_lock = threading.Lock()
+
+
+def register_dynamic_descriptor(descriptor: ModuleDescriptor) -> None:
+ """Register a runtime descriptor for an approved dynamic/plugin module."""
+ if not isinstance(descriptor, ModuleDescriptor):
+ raise TypeError("descriptor must be a ModuleDescriptor instance")
+ with _dynamic_lock:
+ _DYNAMIC_DESCRIPTORS[descriptor.module_id] = descriptor
+
+
+def unregister_dynamic_descriptor(module_id: str) -> bool:
+ """Unregister a dynamic descriptor."""
+ with _dynamic_lock:
+ return _DYNAMIC_DESCRIPTORS.pop(module_id, None) is not None
+
+
def get_descriptor(module_id: str) -> ModuleDescriptor | None:
if type(module_id) is not str:
return None
- return FIRST_PARTY_DESCRIPTORS.get(module_id)
+ first_party = FIRST_PARTY_DESCRIPTORS.get(module_id)
+ if first_party is not None:
+ return first_party
+ with _dynamic_lock:
+ return _DYNAMIC_DESCRIPTORS.get(module_id)
def require_descriptor(module_id: str) -> ModuleDescriptor:
@@ -9218,6 +9241,8 @@ __all__ = [
"descriptor_semantic_digest",
"extract_destinations",
"get_descriptor",
+ "register_dynamic_descriptor",
+ "unregister_dynamic_descriptor",
"prepare_admission_parameters",
"readiness_summary",
"require_descriptor",
diff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.py
index 43b1797..c295bf9 100644
--- a/tests/unit/test_hardening.py
+++ b/tests/unit/test_hardening.py
@@ -752,8 +752,8 @@ class TestMarketplaceAndCrackerHardening:
with pytest.raises(ValueError, match="Path traversal detected|Invalid or unsafe module ID"):
installer._install_single_file(fake_file, source_url="https://example.com/test.py", force=True)
- def test_dynamic_module_destination_extracted_in_lifecycle_admission(self):
- """Lifecycle admission must extract target/host for dynamic modules without static descriptors."""
+ def test_dynamic_module_lifecycle_fail_closed_without_descriptor(self):
+ """Dynamic modules without a registered Phase 5C descriptor must fail admission preparation."""
import uuid
from ares.db.execution_lifecycle import AdmissionIntentV3, ExecutionLifecycleStore
@@ -765,7 +765,7 @@ class TestMarketplaceAndCrackerHardening:
outbox_id=None,
publication_key=None,
campaign_id=str(uuid.uuid4()),
- module_id="custom.dynamic_scanner",
+ module_id="custom.unregistered_module",
ingress_code="direct_engine",
operation_id=str(uuid.uuid4()),
evaluation_mode="live",
@@ -775,9 +775,111 @@ class TestMarketplaceAndCrackerHardening:
noise_units=1,
exfiltration_units=0,
)
+ # Without a registered descriptor, preparation returns None (fail-closed INVALID_CONTRACT)
prepared = ExecutionLifecycleStore._prepared_admission(intent)
- assert prepared is not None
- assert ("host", "192.168.1.50") in prepared.destination_refs
- assert ("domain", "corp.local") in prepared.destination_refs
+ assert prepared is None
+
+ def test_dynamic_module_descriptor_registration_and_admission(self):
+ """When a valid descriptor is registered dynamically, admission preparation succeeds and extracts destinations."""
+ import dataclasses
+ import uuid
+
+ from ares.db.execution_lifecycle import AdmissionIntentV3, ExecutionLifecycleStore
+ from ares.modules.descriptors import (
+ FIRST_PARTY_DESCRIPTORS,
+ get_descriptor,
+ register_dynamic_descriptor,
+ unregister_dynamic_descriptor,
+ )
+
+ sample = FIRST_PARTY_DESCRIPTORS["network.port_scan"]
+ dyn_desc = dataclasses.replace(sample, module_id="network.dynamic_scanner")
+ try:
+ register_dynamic_descriptor(dyn_desc)
+ assert get_descriptor("network.dynamic_scanner") is dyn_desc
+
+ intent = AdmissionIntentV3(
+ logical_execution_id=str(uuid.uuid4()),
+ submission_id=str(uuid.uuid4()),
+ attempt_id=str(uuid.uuid4()),
+ outbox_id=None,
+ publication_key=None,
+ campaign_id=str(uuid.uuid4()),
+ module_id="network.dynamic_scanner",
+ ingress_code="direct_engine",
+ operation_id=str(uuid.uuid4()),
+ evaluation_mode="live",
+ raw_parameters={"target": "192.168.1.50", "ports": "80,443", "timeout": 5.0},
+ credential_ids=(),
+ approval_ref=None,
+ noise_units=1,
+ exfiltration_units=0,
+ )
+ prepared = ExecutionLifecycleStore._prepared_admission(intent)
+ assert prepared is not None
+ assert ("host", "192.168.1.50") in prepared.destination_refs
+ finally:
+ unregister_dynamic_descriptor("network.dynamic_scanner")
+ assert get_descriptor("network.dynamic_scanner") is None
+
+ def test_marketplace_manifest_hash_without_ed25519_fails_closed_under_verify_signature(self, monkeypatch):
+ """Under verify_signature=True, an unauthenticated manifest hash from same origin must NOT satisfy verification."""
+ import httpx
+ from ares.marketplace.installer import ModuleInstaller
+
+ installer = ModuleInstaller()
+ sample_code = b"class DummyModule:\n MODULE_ID = 'test.untrusted'\n"
+
+ import hashlib
+ sample_hash = hashlib.sha256(sample_code).hexdigest()
+ manifest_json = f'{{"id": "test.untrusted", "sha256": "{sample_hash}"}}'.encode("utf-8")
+
+ def mock_get(self, url, *args, **kwargs):
+ req = httpx.Request("GET", url)
+ if url.endswith(".py"):
+ return httpx.Response(200, request=req, content=sample_code)
+ elif url.endswith("manifest.json"):
+ return httpx.Response(200, request=req, content=manifest_json)
+ # .sig is missing (404)
+ return httpx.Response(404, request=req)
+
+ monkeypatch.setattr(httpx.Client, "get", mock_get)
+
+ # verify_signature=True must reject module despite matching manifest hash
+ with pytest.raises(ValueError, match="has no valid Ed25519 cryptographic signature"):
+ installer._install_url("https://example.com/untrusted.py", force=False, verify_signature=True)
+
+ def test_marketplace_deps_skipped_by_default_without_operator_flag(self, monkeypatch):
+ """Dependencies must be skipped by default for supply chain isolation unless operator explicitly enables them."""
+ import os
+ from ares.marketplace.installer import ModuleInstaller
+
+ installer = ModuleInstaller()
+ monkeypatch.delenv("ARES_MARKETPLACE_INSTALL_DEPS", raising=False)
+
+ # Calling _install_pip_deps without env flag must not run pip
+ called = False
+
+ def mock_run(*a, **kw):
+ nonlocal called
+ called = True
+
+ import subprocess
+ monkeypatch.setattr(subprocess, "run", mock_run)
+ installer._install_pip_deps(["requests==2.31.0"])
+ assert called is False
+
+ def test_marketplace_deps_rejects_unpinned_versions(self, monkeypatch):
+ """Even when operator enables deps, unpinned or floating versions (>=, >, etc.) must be rejected."""
+ from ares.marketplace.installer import ModuleInstaller
+
+ installer = ModuleInstaller()
+ monkeypatch.setenv("ARES_MARKETPLACE_INSTALL_DEPS", "1")
+
+ with pytest.raises(ValueError, match="Supply-chain policy violation"):
+ installer._install_pip_deps(["requests>=2.0.0"])
+
+ with pytest.raises(ValueError, match="Supply-chain policy violation"):
+ installer._install_pip_deps(["urllib3"])
diff --git a/tests/unit/test_scope_firewall.py b/tests/unit/test_scope_firewall.py
index e7e9a8d..8f6ad32 100644
--- a/tests/unit/test_scope_firewall.py
+++ b/tests/unit/test_scope_firewall.py
@@ -351,10 +351,9 @@ class TestOSFirewallController:
rules = OSFirewallController.apply_rules(sample_campaign, ["172.16.0.0/16"])
assert len(rules) == 1
assert rules[0].startswith("ARES_SCOPE_WALL_")
- cmd = mock_run.call_args[0][0]
- assert cmd[0] == "iptables"
- assert "-d" in cmd
- assert "172.16.0.0/16" in cmd
+ all_cmds = [call[0][0] for call in mock_run.call_args_list]
+ assert any(cmd[0] == "iptables" and "-d" in cmd and "172.16.0.0/16" in cmd for cmd in all_cmds)
+ assert any(cmd[0] == "iptables" and "-j" in cmd and "DROP" in cmd for cmd in all_cmds)
removed = OSFirewallController.remove_rules(rules)
assert removed == 1
@@ -395,6 +394,7 @@ class TestOSFirewallController:
def test_proxy_environment_variables_neutralized_during_guard(self, sample_campaign: Campaign):
import os
+ import urllib.request
os.environ["HTTP_PROXY"] = "http://127.0.0.1:8080"
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:8443"
try:
@@ -403,10 +403,78 @@ class TestOSFirewallController:
# Proxies must be stripped while guard is active
assert "HTTP_PROXY" not in os.environ
assert "HTTPS_PROXY" not in os.environ
- # Proxies must be safely restored upon exit
+ assert urllib.request.getproxies() == {}
+
+ # Nested guard must not clobber outer saved proxies
+ with scope_firewall_sync_guard(sample_campaign) as inner_fw:
+ assert inner_fw is not None
+ assert "HTTP_PROXY" not in os.environ
+
+ # Exiting nested guard must still maintain proxy neutralization while outer guard is alive
+ assert "HTTP_PROXY" not in os.environ
+
+ # Proxies must be safely restored only upon final exit
assert os.environ.get("HTTP_PROXY") == "http://127.0.0.1:8080"
assert os.environ.get("HTTPS_PROXY") == "http://127.0.0.1:8443"
finally:
os.environ.pop("HTTP_PROXY", None)
os.environ.pop("HTTPS_PROXY", None)
+ def test_scope_firewall_dns_failure_fails_closed(self, sample_campaign: Campaign, monkeypatch: pytest.MonkeyPatch):
+ """If DNS resolution fails, the address must fail-closed (False) even if hostname is in explicit_hosts."""
+ fw = ScopeFirewall(campaign=sample_campaign, module_id="test.dns_fail")
+
+ def mock_getaddrinfo(*args, **kwargs):
+ raise socket.gaierror(-2, "Name or service not known")
+
+ monkeypatch.setattr(socket, "getaddrinfo", mock_getaddrinfo)
+ # Attempt to resolve an unresolvable hostname
+ allowed, pinned = fw.resolve_and_pin_address("unresolvable.in-targets.local")
+ assert allowed is False
+
+ def test_os_firewall_linux_strict_allowlist_commands(self, monkeypatch: pytest.MonkeyPatch):
+ """Linux OS firewall must apply lo ACCEPT, scope ACCEPT, and process DROP rules."""
+ from ares.core.scope_firewall import OSFirewallController
+ import subprocess
+ import sys
+
+ commands_executed: list[list[str]] = []
+
+ def mock_run(cmd, *args, **kwargs):
+ commands_executed.append(list(cmd))
+ class MockRes:
+ returncode = 0
+ stdout = ""
+ stderr = ""
+ return MockRes()
+
+ monkeypatch.setattr(subprocess, "run", mock_run)
+ monkeypatch.setattr(OSFirewallController, "is_elevated", lambda: True)
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ rules = OSFirewallController.apply_rules(None, ["10.0.0.0/24"], program="/usr/bin/python3")
+ assert len(rules) == 1
+ rule_name = rules[0]
+
+ # Verify that all 3 rules were applied:
+ # Rule 1: loopback ACCEPT
+ assert any(
+ "-o" in cmd and "lo" in cmd and "-j" in cmd and "ACCEPT" in cmd
+ for cmd in commands_executed
+ )
+ # Rule 2: scope ACCEPT
+ assert any(
+ "-d" in cmd and "10.0.0.0/24" in cmd and "-j" in cmd and "ACCEPT" in cmd
+ for cmd in commands_executed
+ )
+ # Rule 3: DROP other outbound packets (strict allowlist)
+ assert any(
+ "-j" in cmd and "DROP" in cmd
+ for cmd in commands_executed
+ )
+
+ # Now test remove_rules
+ commands_executed.clear()
+ removed = OSFirewallController.remove_rules([rule_name])
+ assert any("iptables" in cmd and "-D" in cmd for cmd in commands_executed)
+