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): resolve 6 boundary hardening gaps in sandbox & OS firewall

Mafifrizi4b76e79b8b72
diff --git a/ares/core/sandbox.py b/ares/core/sandbox.py
index 5636f92..44a5c15 100644
--- a/ares/core/sandbox.py
+++ b/ares/core/sandbox.py
@@ -128,7 +128,7 @@ class SandboxRunner:
t0 = time.monotonic()
# Core modules always run in-process
- if any(module_id.startswith(p) for p in self.policy.trusted_prefixes):
+ if self.is_trusted_module(module_id):
effective_tier = IsolationTier.NONE
audit("sandbox_run_start", actor="engine",
@@ -170,6 +170,7 @@ class SandboxRunner:
from ares.core.noise import NoiseController
from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry
from ares.core.plugin.loader import ModuleRegistry
+ from ares.core.scope_firewall import scope_firewall_guard
registry = ModuleRegistry()
module_cls = registry.get(module_id)
@@ -216,7 +217,8 @@ class SandboxRunner:
settings = AresSettings()
noise = NoiseController(campaign)
module = module_cls(settings=settings, campaign=campaign, noise=noise)
- findings, extra = await module.run(**params)
+ async with scope_firewall_guard(campaign=campaign, module_id=module_id):
+ findings, extra = await module.run(**params)
return SandboxResult(
module_id=module_id, sandbox_tier=IsolationTier.NONE, success=True,
findings=[f.to_dict() if hasattr(f, "to_dict") else {} for f in findings],
@@ -254,12 +256,13 @@ class SandboxRunner:
except Exception:
pass # fallback handled in wrapper - fails closed
payload = json.dumps({
- "module_id": module_id,
- "params": params,
- "campaign_id": campaign_id,
- "use_seccomp": use_seccomp,
- "tmpdir": tmpdir,
- "scope_cidrs": _scope_cidrs,
+ "module_id": module_id,
+ "params": params,
+ "campaign_id": campaign_id,
+ "use_seccomp": use_seccomp,
+ "tmpdir": tmpdir,
+ "scope_cidrs": _scope_cidrs,
+ "allow_network": self.policy.allow_network,
})
wrapper = self._build_wrapper_script(use_seccomp)
@@ -348,11 +351,15 @@ class SandboxRunner:
except Exception:
pass # fails closed in inline_runner
payload = json.dumps({
- "module_id": module_id, "params": params,
- "campaign_id": campaign_id, "scope_cidrs": _docker_scope,
+ "module_id": module_id,
+ "params": params,
+ "campaign_id": campaign_id,
+ "scope_cidrs": _docker_scope,
+ "allow_network": self.policy.allow_network,
})
image = self.policy.docker_image
- network = self.policy.docker_network
+ network = "none" if not self.policy.allow_network else self.policy.docker_network
+ read_only = not self.policy.allow_write
mem_limit = f"{self.policy.memory_mb}m"
client = docker.from_env()
@@ -365,6 +372,7 @@ class SandboxRunner:
cpu_period=100000,
cpu_quota=50000, # 50% of one CPU
network_mode=network,
+ read_only=read_only,
remove=True,
stdout=True,
stderr=True,
@@ -389,7 +397,7 @@ class SandboxRunner:
def _make_preexec_fn(self):
"""
- Return preexec_fn that applies resource limits in child process.
+ Return preexec_fn that applies resource limits and security privileges in child process.
Only called on Unix systems.
"""
cpu_limit = self.policy.cpu_time_s
@@ -401,9 +409,30 @@ class SandboxRunner:
resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
resource.setrlimit(resource.RLIMIT_NPROC, (64, 64))
resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256))
+ if not self.policy.allow_write:
+ resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0))
except (OSError, ValueError, AttributeError):
pass # best-effort - don't fail the child
+ if not self.policy.allow_network:
+ try:
+ import ctypes
+ # CLONE_NEWNET = 0x40000000
+ _libc = ctypes.CDLL(None)
+ _libc.unshare(0x40000000)
+ except Exception:
+ pass
+
+ if self.policy.drop_privileges and getattr(os, "geteuid", lambda: -1)() == 0:
+ try:
+ import pwd
+ nobody = pwd.getpwnam("nobody")
+ os.setgroups([])
+ os.setgid(nobody.pw_gid)
+ os.setuid(nobody.pw_uid)
+ except Exception:
+ pass
+
return _limits
@staticmethod
@@ -412,34 +441,32 @@ class SandboxRunner:
Build Python source that runs in the sandbox child process.
When use_seccomp=True, applies PR_SET_NO_NEW_PRIVS (prctl 38) as a
mandatory minimum, preventing the child from ever regaining privileges.
- Full BPF syscall allowlist filtering is applied if pyseccomp is installed
- and ARES_SECCOMP_BPF=1 env var is set.
+ Full BPF syscall allowlist filtering is applied via pyseccomp.
+ Fails closed with RuntimeError if seccomp enforcement cannot be established.
"""
if use_seccomp:
allowed_list = repr(sorted(_SECCOMP_ALLOWED))
seccomp_preamble = (
- "# ── SECCOMP: apply privilege restrictions ─────────────────────────────\n"
- "import ctypes as _ct, ctypes.util as _cu, os as _so\n"
+ "# ── SECCOMP: apply mandatory privilege restrictions ───────────────────\n"
+ "import ctypes as _ct, ctypes.util as _cu, os as _so, sys as _sys\n"
"try:\n"
" _libc = _ct.CDLL(_cu.find_library('c'), use_errno=True)\n"
- " _libc.prctl(38, 1, 0, 0, 0) # PR_SET_NO_NEW_PRIVS - child cannot gain privs\n"
+ " if _libc.prctl(38, 1, 0, 0, 0) != 0:\n"
+ " raise RuntimeError('prctl PR_SET_NO_NEW_PRIVS returned non-zero')\n"
"except Exception as _pe:\n"
- " import sys as _ps; print(f'[sandbox] prctl failed: {_pe}', file=_ps.stderr)\n"
- "if _so.environ.get('ARES_SECCOMP_BPF') == '1':\n"
- " try:\n"
- " import seccomp as _sc # pyseccomp\n"
- f" _allowed = {allowed_list}\n"
- " _f = _sc.SyscallFilter(defaction=_sc.KILL)\n"
- " for _sn in _allowed:\n"
- " try: _f.add_rule(_sc.ALLOW, _sn)\n"
- " except Exception: pass\n"
- " _f.load()\n"
- " except ImportError:\n"
- " import sys as _s2\n"
- " print('[sandbox] pyseccomp not installed - BPF filter skipped', file=_s2.stderr)\n"
- " except Exception as _be:\n"
- " import sys as _s3\n"
- " print(f'[sandbox] BPF filter failed: {_be}', file=_s3.stderr)\n"
+ " print(f'[sandbox] prctl failed: {_pe}', file=_sys.stderr)\n"
+ " raise RuntimeError(f'Seccomp PR_SET_NO_NEW_PRIVS enforcement failed: {_pe}')\n"
+ "try:\n"
+ " import seccomp as _sc # pyseccomp\n"
+ f" _allowed = {allowed_list}\n"
+ " _f = _sc.SyscallFilter(defaction=_sc.KILL)\n"
+ " for _sn in _allowed:\n"
+ " try: _f.add_rule(_sc.ALLOW, _sn)\n"
+ " except Exception: pass\n"
+ " _f.load()\n"
+ "except Exception as _be:\n"
+ " print(f'[sandbox] BPF filter failed: {_be}', file=_sys.stderr)\n"
+ " raise RuntimeError(f'IsolationTier.SECCOMP failed to load BPF syscall filter: {_be}')\n"
"# ── end SECCOMP ────────────────────────────────────────────────────────\n"
)
else:
@@ -465,18 +492,27 @@ class SandboxRunner:
" if not module_cls:\n"
" return {\"success\": False, \"error\": f\"Module {module_id!r} not found\", \"findings\": [], \"extra\": {}}\n"
"\n"
+ " _allow_net = payload.get(\"allow_network\", True)\n"
" _scope_cidrs = payload.get(\"scope_cidrs\", [])\n"
- " if not _scope_cidrs:\n"
+ " if not _allow_net:\n"
+ " campaign = Campaign(\n"
+ " id=campaign_id or str(uuid.uuid4()),\n"
+ " name=\"sandbox\",\n"
+ " scope=[],\n"
+ " noise_profile=NoiseProfile.NORMAL,\n"
+ " )\n"
+ " elif not _scope_cidrs:\n"
" print(json.dumps({\"success\": False, \"error\":\n"
" \"Sandbox scope not provided - refusing to run with unbounded scope\",\n"
" \"findings\": [], \"extra\": {}}))\n"
" return\n"
- " campaign = Campaign(\n"
- " id=campaign_id or str(uuid.uuid4()),\n"
- " name=\"sandbox\",\n"
- " scope=[ScopeEntry(cidr=c) for c in _scope_cidrs],\n"
- " noise_profile=NoiseProfile.NORMAL,\n"
- " )\n"
+ " else:\n"
+ " campaign = Campaign(\n"
+ " id=campaign_id or str(uuid.uuid4()),\n"
+ " name=\"sandbox\",\n"
+ " scope=[ScopeEntry(cidr=c) for c in _scope_cidrs],\n"
+ " noise_profile=NoiseProfile.NORMAL,\n"
+ " )\n"
" settings = AresSettings()\n"
" noise = NoiseController(campaign)\n"
" module = module_cls(settings=settings, campaign=campaign, noise=noise)\n"
@@ -523,17 +559,26 @@ class SandboxRunner:
' if not module_cls:\n'
' return {"success": False, "error": f"Module {module_id!r} not found",\n'
' "findings": [], "extra": {}}\n'
+ ' _allow_net = payload.get("allow_network", True)\n'
' _scope_cidrs = payload.get("scope_cidrs", [])\n'
- ' if not _scope_cidrs:\n'
+ ' if not _allow_net:\n'
+ ' campaign = Campaign(\n'
+ ' id=campaign_id or str(uuid.uuid4()),\n'
+ ' name="sandbox", operator="sandbox",\n'
+ ' scope=[],\n'
+ ' noise_profile=NoiseProfile.NORMAL,\n'
+ ' )\n'
+ ' elif not _scope_cidrs:\n'
' return {"success": False,\n'
' "error": "Sandbox scope not provided - refusing to run with unbounded scope",\n'
' "findings": [], "extra": {}}\n'
- ' campaign = Campaign(\n'
- ' id=campaign_id or str(uuid.uuid4()),\n'
- ' name="sandbox", operator="sandbox",\n'
- ' scope=[ScopeEntry(cidr=c) for c in _scope_cidrs],\n'
- ' noise_profile=NoiseProfile.NORMAL,\n'
- ' )\n'
+ ' else:\n'
+ ' campaign = Campaign(\n'
+ ' id=campaign_id or str(uuid.uuid4()),\n'
+ ' name="sandbox", operator="sandbox",\n'
+ ' scope=[ScopeEntry(cidr=c) for c in _scope_cidrs],\n'
+ ' noise_profile=NoiseProfile.NORMAL,\n'
+ ' )\n'
' try:\n'
' from ares.core.config import AresSettings\n'
' from ares.core.noise import NoiseController\n'
@@ -542,7 +587,9 @@ class SandboxRunner:
' module = module_cls(settings=settings, campaign=campaign, noise=noise)\n'
' except Exception:\n'
' module = module_cls()\n'
- ' findings, extra = await module.run(**params)\n'
+ ' from ares.core.scope_firewall import scope_firewall_guard\n'
+ ' async with scope_firewall_guard(campaign=campaign, module_id=module_id):\n'
+ ' findings, extra = await module.run(**params)\n'
' findings_out = []\n'
' for f in findings:\n'
' if hasattr(f, "model_dump"):\n'
@@ -561,4 +608,7 @@ class SandboxRunner:
)
def is_trusted_module(self, module_id: str) -> bool:
- return any(module_id.startswith(p) for p in self.policy.trusted_prefixes)
+ return any(
+ module_id == p or module_id.startswith(f"{p}.")
+ for p in self.policy.trusted_prefixes
+ )
diff --git a/ares/core/scope_firewall.py b/ares/core/scope_firewall.py
index caba944..fff36b5 100644
--- a/ares/core/scope_firewall.py
+++ b/ares/core/scope_firewall.py
@@ -531,18 +531,22 @@ def uninstall_hooks() -> None:
def compute_out_of_scope_cidrs(
scope_cidrs: list[str],
allow_loopback: bool = True,
+ include_ipv6: bool = True,
) -> list[str]:
- """Calculate the mathematical complement of in-scope CIDRs in IPv4 address space.
+ """Calculate the mathematical complement of in-scope CIDRs in IPv4 and IPv6 address space.
- Returns a minimal list of CIDR blocks covering all of IPv4 (0.0.0.0/0)
- EXCEPT for the in-scope CIDRs and (optionally) the loopback network (127.0.0.0/8).
- Applying an explicit BLOCK rule to this complement set enforces an exact deny-by-default
- allowlist under Windows Defender Firewall without altering global host policy.
+ Returns a minimal list of CIDR blocks covering all of IPv4 (0.0.0.0/0) and IPv6 (::/0)
+ EXCEPT for the in-scope CIDRs and (optionally) the loopback networks (127.0.0.0/8 and ::1/128).
+ Applying explicit BLOCK rules to this complement set enforces an exact dual-stack
+ deny-by-default allowlist under Windows Defender Firewall without altering global host policy.
"""
- all_v4 = [ipaddress.ip_network("0.0.0.0/0")]
- excluded_nets: list[ipaddress.IPv4Network] = []
+ excluded_v4: list[ipaddress.IPv4Network] = []
+ excluded_v6: list[ipaddress.IPv6Network] = []
+
if allow_loopback:
- excluded_nets.append(ipaddress.ip_network("127.0.0.0/8"))
+ excluded_v4.append(ipaddress.ip_network("127.0.0.0/8"))
+ excluded_v6.append(ipaddress.ip_network("::1/128"))
+
for c in scope_cidrs:
c_str = str(c).strip()
if not c_str:
@@ -550,22 +554,40 @@ def compute_out_of_scope_cidrs(
try:
net = ipaddress.ip_network(c_str, strict=False)
if isinstance(net, ipaddress.IPv4Network):
- excluded_nets.append(net)
+ excluded_v4.append(net)
+ elif isinstance(net, ipaddress.IPv6Network):
+ excluded_v6.append(net)
except ValueError:
pass
- current_blocks = all_v4
- for ex in excluded_nets:
+ # IPv4 complement
+ current_v4 = [ipaddress.ip_network("0.0.0.0/0")]
+ for ex in excluded_v4:
next_blocks: list[ipaddress.IPv4Network] = []
- for blk in current_blocks:
+ for blk in current_v4:
if blk.overlaps(ex):
next_blocks.extend(list(blk.address_exclude(ex)))
else:
next_blocks.append(blk)
- current_blocks = next_blocks
+ current_v4 = next_blocks
+
+ res = [str(b) for b in ipaddress.collapse_addresses(current_v4)]
+
+ # IPv6 complement
+ if include_ipv6:
+ current_v6 = [ipaddress.ip_network("::/0")]
+ for ex in excluded_v6:
+ next_v6: list[ipaddress.IPv6Network] = []
+ for blk in current_v6:
+ if blk.overlaps(ex):
+ next_v6.extend(list(blk.address_exclude(ex)))
+ else:
+ next_v6.append(blk)
+ current_v6 = next_v6
+ res.extend([str(b) for b in ipaddress.collapse_addresses(current_v6)])
+
+ return res
- collapsed = list(ipaddress.collapse_addresses(current_blocks))
- return [str(b) for b in collapsed]
class OSFirewallController:
@@ -638,6 +660,7 @@ class OSFirewallController:
campaign: Campaign | None,
scope_cidrs: list[str],
program: str | None = None,
+ uid_owner: int | str | None = None,
) -> list[str]:
"""Apply OS-level firewall rules restricting outbound egress to scope_cidrs.
@@ -659,21 +682,41 @@ class OSFirewallController:
)
return []
- cidrs_str = ",".join(scope_cidrs)
rule_token = secrets.token_hex(6)
rule_name = f"ARES_SCOPE_WALL_{rule_token}"
prog = program or sys.executable
sub_rules: list[tuple[list[str], list[str]]] = []
if sys.platform == "win32":
- out_of_scope = compute_out_of_scope_cidrs(scope_cidrs, allow_loopback=True)
+ out_of_scope = compute_out_of_scope_cidrs(scope_cidrs, allow_loopback=True, include_ipv6=True)
if not out_of_scope:
return []
+ v4_out = [c for c in out_of_scope if ":" not in c]
+ v6_out = [c for c in out_of_scope if ":" in c]
+
batch_size = 40
- for i in range(0, len(out_of_scope), batch_size):
- batch = out_of_scope[i : i + batch_size]
- sub_name = f"{rule_name}_blk{i // batch_size}"
+ for i in range(0, len(v4_out), batch_size):
+ batch = v4_out[i : i + batch_size]
+ sub_name = f"{rule_name}_v4_{i // batch_size}"
+ apply_cmd = [
+ "netsh", "advfirewall", "firewall", "add", "rule",
+ f"name={sub_name}",
+ "dir=out",
+ "action=block",
+ f"program={prog}",
+ f"remoteip={','.join(batch)}",
+ "enable=yes",
+ ]
+ cleanup_cmd = [
+ "netsh", "advfirewall", "firewall", "delete", "rule",
+ f"name={sub_name}",
+ ]
+ sub_rules.append((apply_cmd, cleanup_cmd))
+
+ for j in range(0, len(v6_out), batch_size):
+ batch = v6_out[j : j + batch_size]
+ sub_name = f"{rule_name}_v6_{j // batch_size}"
apply_cmd = [
"netsh", "advfirewall", "firewall", "add", "rule",
f"name={sub_name}",
@@ -691,50 +734,39 @@ class OSFirewallController:
elif sys.platform.startswith("linux"):
pid = str(os.getpid())
- # Rule 1: Allow loopback for this process
- lo_apply = [
- "iptables", "-I", "OUTPUT", "1",
- "-m", "owner", "--pid-owner", pid,
- "-o", "lo",
- "-j", "ACCEPT",
- "-m", "comment", "--comment", f"{rule_name}_lo",
- ]
- lo_cleanup = [
- "iptables", "-D", "OUTPUT",
- "-m", "comment", "--comment", f"{rule_name}_lo",
- "-j", "ACCEPT",
- ]
+ owner_match = ["-m", "owner", "--uid-owner", str(uid_owner)] if uid_owner is not None else ["-m", "owner", "--pid-owner", pid]
+
+ v4_scope = [c for c in scope_cidrs if ":" not in c]
+ v6_scope = [c for c in scope_cidrs if ":" in c]
+
+ # IPv4 Netfilter rules
+ lo_apply = ["iptables", "-I", "OUTPUT", "1"] + owner_match + ["-o", "lo", "-j", "ACCEPT", "-m", "comment", "--comment", f"{rule_name}_lo"]
+ lo_cleanup = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", f"{rule_name}_lo", "-j", "ACCEPT"]
sub_rules.append((lo_apply, lo_cleanup))
- # Rule 2: Allow authorized scope CIDRs for this process
- scope_apply = [
- "iptables", "-I", "OUTPUT", "2",
- "-m", "owner", "--pid-owner", pid,
- "-d", cidrs_str,
- "-j", "ACCEPT",
- "-m", "comment", "--comment", f"{rule_name}_scope",
- ]
- scope_cleanup = [
- "iptables", "-D", "OUTPUT",
- "-m", "comment", "--comment", f"{rule_name}_scope",
- "-j", "ACCEPT",
- ]
- sub_rules.append((scope_apply, scope_cleanup))
-
- # Rule 3: DROP all other outbound egress from this process (strict allowlist)
- drop_apply = [
- "iptables", "-I", "OUTPUT", "3",
- "-m", "owner", "--pid-owner", pid,
- "-j", "DROP",
- "-m", "comment", "--comment", f"{rule_name}_drop",
- ]
- drop_cleanup = [
- "iptables", "-D", "OUTPUT",
- "-m", "comment", "--comment", f"{rule_name}_drop",
- "-j", "DROP",
- ]
+ if v4_scope:
+ scope_apply = ["iptables", "-I", "OUTPUT", "2"] + owner_match + ["-d", ",".join(v4_scope), "-j", "ACCEPT", "-m", "comment", "--comment", f"{rule_name}_scope"]
+ scope_cleanup = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", f"{rule_name}_scope", "-j", "ACCEPT"]
+ sub_rules.append((scope_apply, scope_cleanup))
+
+ drop_apply = ["iptables", "-I", "OUTPUT", "3"] + owner_match + ["-j", "DROP", "-m", "comment", "--comment", f"{rule_name}_drop"]
+ drop_cleanup = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", f"{rule_name}_drop", "-j", "DROP"]
sub_rules.append((drop_apply, drop_cleanup))
+ # IPv6 Netfilter rules
+ if v6_scope:
+ lo6_apply = ["ip6tables", "-I", "OUTPUT", "1"] + owner_match + ["-o", "lo", "-j", "ACCEPT", "-m", "comment", "--comment", f"{rule_name}_lo6"]
+ lo6_cleanup = ["ip6tables", "-D", "OUTPUT", "-m", "comment", "--comment", f"{rule_name}_lo6", "-j", "ACCEPT"]
+ sub_rules.append((lo6_apply, lo6_cleanup))
+
+ scope6_apply = ["ip6tables", "-I", "OUTPUT", "2"] + owner_match + ["-d", ",".join(v6_scope), "-j", "ACCEPT", "-m", "comment", "--comment", f"{rule_name}_scope6"]
+ scope6_cleanup = ["ip6tables", "-D", "OUTPUT", "-m", "comment", "--comment", f"{rule_name}_scope6", "-j", "ACCEPT"]
+ sub_rules.append((scope6_apply, scope6_cleanup))
+
+ drop6_apply = ["ip6tables", "-I", "OUTPUT", "3"] + owner_match + ["-j", "DROP", "-m", "comment", "--comment", f"{rule_name}_drop6"]
+ drop6_cleanup = ["ip6tables", "-D", "OUTPUT", "-m", "comment", "--comment", f"{rule_name}_drop6", "-j", "DROP"]
+ sub_rules.append((drop6_apply, drop6_cleanup))
+
applied_cleanups: list[list[str]] = []
all_succeeded = True
diff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.py
index c295bf9..1921d54 100644
--- a/tests/unit/test_hardening.py
+++ b/tests/unit/test_hardening.py
@@ -883,3 +883,141 @@ class TestMarketplaceAndCrackerHardening:
installer._install_pip_deps(["urllib3"])
+# ═══════════════════════════════════════════════════════════════════════════════
+# ADVANCED BOUNDARY HARDENING PROOFS: Sandbox & Firewall Strictness
+# ═══════════════════════════════════════════════════════════════════════════════
+
+class TestSandboxAndFirewallHardening:
+ """Validates the 6 advanced security boundary hardening findings."""
+
+ def test_trusted_module_namespace_boundary(self):
+ """
+ FINDING 6: Trusted-prefix matching must respect namespace boundaries.
+ 'ares.coreevil' and 'ares.dbsomething' must NOT bypass sandboxing.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ policy = SandboxPolicy(trusted_prefixes=["ares.core", "ares.db"])
+ runner = SandboxRunner(policy=policy)
+
+ # Authorized exact matches and submodule paths
+ assert runner.is_trusted_module("ares.core") is True
+ assert runner.is_trusted_module("ares.core.engine") is True
+ assert runner.is_trusted_module("ares.db") is True
+ assert runner.is_trusted_module("ares.db.database") is True
+
+ # Malicious prefix overlaps must be strictly REJECTED
+ assert runner.is_trusted_module("ares.coreevil") is False
+ assert runner.is_trusted_module("ares.core_bypass") is False
+ assert runner.is_trusted_module("ares.dbsomething") is False
+ assert runner.is_trusted_module("ares.db_leak") is False
+ assert runner.is_trusted_module("untrusted.module") is False
+
+ def test_docker_runner_source_wraps_module_in_scope_firewall(self):
+ """
+ FINDING 1: Docker sandbox runner script must wrap module execution
+ inside scope_firewall_guard.
+ """
+ from ares.core.sandbox import SandboxRunner
+
+ inline_source = SandboxRunner._inline_runner()
+ assert "from ares.core.scope_firewall import scope_firewall_guard" in inline_source, \
+ "Docker inline runner missing scope_firewall_guard import"
+ assert "async with scope_firewall_guard(campaign=campaign, module_id=module_id):" in inline_source, \
+ "Docker inline runner does not wrap module.run in scope_firewall_guard"
+
+ def test_subprocess_wrapper_script_wraps_module_in_scope_firewall(self):
+ """
+ Subprocess runner script must wrap module execution inside scope_firewall_guard.
+ """
+ from ares.core.sandbox import SandboxRunner
+
+ wrapper_source = SandboxRunner._build_wrapper_script(use_seccomp=False)
+ assert "from ares.core.scope_firewall import scope_firewall_guard" in wrapper_source
+ assert "async with scope_firewall_guard(campaign=campaign, module_id=module_id):" in wrapper_source
+
+ def test_seccomp_tier_is_fail_closed(self):
+ """
+ FINDING 5: IsolationTier.SECCOMP must fail closed with RuntimeError if
+ prctl PR_SET_NO_NEW_PRIVS or pyseccomp BPF loading fails.
+ """
+ from ares.core.sandbox import SandboxRunner
+
+ wrapper_source = SandboxRunner._build_wrapper_script(use_seccomp=True)
+ assert "raise RuntimeError('prctl PR_SET_NO_NEW_PRIVS returned non-zero')" in wrapper_source
+ assert "raise RuntimeError(f'IsolationTier.SECCOMP failed to load BPF syscall filter: {_be}')" in wrapper_source
+
+ def test_sandbox_policy_enforcement_docker_options(self, monkeypatch):
+ """
+ FINDINGS 1 & 4: SandboxPolicy allow_network=False must set network_mode='none',
+ and allow_write=False must set read_only=True in Docker.
+ """
+ import asyncio
+ from unittest.mock import MagicMock
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ policy = SandboxPolicy(allow_network=False, allow_write=False)
+ runner = SandboxRunner(policy=policy)
+
+ # Mock docker library
+ mock_docker = MagicMock()
+ mock_client = MagicMock()
+ mock_docker.from_env.return_value = mock_client
+ mock_client.containers.run.return_value = b'{"success": true, "findings": [], "extra": {}}'
+
+ monkeypatch.setattr("sys.modules", {**sys.modules, "docker": mock_docker})
+
+ res = asyncio.run(runner._run_docker("test.module", {}, "camp-123"))
+ assert res.success is True
+
+ # Check call arguments to containers.run
+ _, run_kwargs = mock_client.containers.run.call_args
+ assert run_kwargs.get("network_mode") == "none", "allow_network=False did not set network_mode='none'"
+ assert run_kwargs.get("read_only") is True, "allow_write=False did not set read_only=True"
+
+ def test_dual_stack_out_of_scope_cidrs_complement(self):
+ """
+ FINDING 2: compute_out_of_scope_cidrs must compute complements for BOTH
+ IPv4 (0.0.0.0/0) AND IPv6 (::/0), enabling dual-stack OS firewall enforcement.
+ """
+ from ares.core.scope_firewall import compute_out_of_scope_cidrs
+
+ # Single IPv4 and IPv6 in-scope targets
+ scope = ["192.168.1.0/24", "2001:db8::/32"]
+ out_of_scope = compute_out_of_scope_cidrs(scope, allow_loopback=True, include_ipv6=True)
+
+ v4_cidrs = [c for c in out_of_scope if ":" not in c]
+ v6_cidrs = [c for c in out_of_scope if ":" in c]
+
+ # Both IPv4 and IPv6 complements must be non-empty
+ assert len(v4_cidrs) > 0, "IPv4 complement must not be empty"
+ assert len(v6_cidrs) > 0, "IPv6 complement must not be empty"
+
+ # Verify loopback is NOT in out-of-scope blocks (loopback is allowed)
+ import ipaddress
+ for c in v4_cidrs:
+ net = ipaddress.ip_network(c)
+ assert not net.overlaps(ipaddress.ip_network("127.0.0.1/32")), f"Loopback blocked in {c}"
+
+ for c in v6_cidrs:
+ net = ipaddress.ip_network(c)
+ assert not net.overlaps(ipaddress.ip_network("::1/128")), f"IPv6 Loopback blocked in {c}"
+
+ # Verify in-scope CIDRs are NOT in out-of-scope blocks
+ for c in v4_cidrs:
+ net = ipaddress.ip_network(c)
+ assert not net.overlaps(ipaddress.ip_network("192.168.1.1/32")), f"In-scope IPv4 blocked in {c}"
+
+ for c in v6_cidrs:
+ net = ipaddress.ip_network(c)
+ assert not net.overlaps(ipaddress.ip_network("2001:db8::1/128")), f"In-scope IPv6 blocked in {c}"
+
+ # External arbitrary IPv4 and IPv6 must be covered by out_of_scope (so they are blocked)
+ ext_v4 = ipaddress.ip_address("8.8.8.8")
+ assert any(ext_v4 in ipaddress.ip_network(c) for c in v4_cidrs), "8.8.8.8 must be in out-of-scope complement"
+
+ ext_v6 = ipaddress.ip_address("2606:4700:4700::1111")
+ assert any(ext_v6 in ipaddress.ip_network(c) for c in v6_cidrs), "Cloudflare IPv6 must be in out-of-scope complement"
+
+
+