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): enforce fail-closed sandbox boundaries, ContextVar lifecycle, and empty scope semantics

Mafifrizi4e5429e63c76
diff --git a/ares/core/sandbox.py b/ares/core/sandbox.py
index 44a5c15..b0454f6 100644
--- a/ares/core/sandbox.py
+++ b/ares/core/sandbox.py
@@ -1,18 +1,22 @@
"""
ARES Plugin Sandbox - Restricted Module Execution
-Prevents third-party modules from damaging the core engine.
-
-Isolation tiers:
- TIER_0 NONE - core modules, run in-process (trusted)
- TIER_1 SUBPROCESS - separate process, resource limits (default)
- TIER_2 SECCOMP - subprocess + seccomp syscall filter (Linux)
- TIER_3 DOCKER - fully isolated container (maximum isolation)
-
-Resource limits (TIER_1+):
- - CPU: 30 seconds max
- - Memory: 256 MB
- - Files: no write outside /tmp/ares-sandbox-*
- - Net: allowed (modules need network), but audited
+Provides defense-in-depth isolation tiers to protect engine integrity during module execution.
+
+Isolation tiers & security boundaries:
+ TIER_0 NONE - trusted core modules only, run in-process under ScopeFirewall.
+ TIER_1 SUBPROCESS - separate Python process:
+ * Network: allow_network=False enforces Linux network namespace (CLONE_NEWNET)
+ fail-closed, or deny-all ScopeFirewall socket interception.
+ allow_network=True enforces ScopeFirewall egress boundary.
+ * Filesystem: working directory locked to ephemeral temporary directory;
+ Unix RLIMIT_FSIZE=(0,0) inhibits file enlargement; application-level
+ open/write hooks provide defense-in-depth within Python. Note: Subprocess
+ tier does not provide complete OS-level mount namespace isolation.
+ * Privileges: drop_privileges=True drops root (EUID 0) to 'nobody' on Linux
+ fail-closed; unsupported on Windows while elevated (aborts execution).
+ TIER_2 SECCOMP - Linux SUBPROCESS + PR_SET_NO_NEW_PRIVS + BPF syscall allowlist filter.
+ TIER_3 DOCKER - Complete OS container isolation: read-only root filesystem (allow_write=False),
+ network namespace isolation ('none' or 'bridge'), CPU & memory cgroups.
Usage:
sandbox = SandboxRunner(tier=IsolationTier.TIER_1)
@@ -72,16 +76,31 @@ class IsolationTier(str, Enum):
@dataclass
class SandboxPolicy:
- """Security policy applied to sandboxed module execution."""
+ """Security policy applied to sandboxed module execution.
+
+ Semantic definitions by isolation tier:
+ allow_network:
+ - Linux SUBPROCESS: Mandatory network namespace isolation via unshare(CLONE_NEWNET).
+ - Windows SUBPROCESS: Mandatory deny-all egress via ScopeFirewall socket hooks.
+ - DOCKER: Container network mode 'none' (kernel namespace isolation).
+ allow_write:
+ - DOCKER: Read-only container rootfs (read_only=True via container mount options).
+ - SUBPROCESS: Ephemeral sandbox working directory, RLIMIT_FSIZE=(0,0) on Unix, and
+ application-level open/write hooks within Python. NOTE: For complete OS filesystem
+ isolation, IsolationTier.DOCKER is required.
+ drop_privileges:
+ - Linux SUBPROCESS: Drops root (EUID 0) to 'nobody' and verifies non-root UID (mandatory).
+ - Windows SUBPROCESS: Privilege dropping from Administrator is unsupported; execution aborts if elevated.
+ """
tier: IsolationTier = IsolationTier.SUBPROCESS
- cpu_time_s: int = 30 # max CPU seconds (RLIMIT_CPU)
- memory_mb: int = 256 # max virtual memory
+ cpu_time_s: int = 30 # max CPU seconds (RLIMIT_CPU, best-effort)
+ memory_mb: int = 256 # max virtual memory (RLIMIT_AS, best-effort)
timeout_s: int = 300 # wall-clock timeout
- allow_network: bool = True # allow outbound connections
- allow_write: bool = False # allow filesystem writes (outside /tmp)
- drop_privileges: bool = True # drop to nobody on Linux
+ allow_network: bool = True # outbound network allowed within campaign scope
+ allow_write: bool = False # allow filesystem writes
+ drop_privileges: bool = True # drop root privileges to nobody on Linux
docker_image: str = "python:3.11-slim"
- docker_network: str = "bridge" # "none" for no network
+ docker_network: str = "bridge" # container network mode when allow_network=True
# Modules trusted to bypass sandboxing
trusted_prefixes: list[str] = field(default_factory=lambda: ["ares.core", "ares.db"])
@@ -255,6 +274,16 @@ class SandboxRunner:
]
except Exception:
pass # fallback handled in wrapper - fails closed
+ if os.name == "nt" and self.policy.drop_privileges:
+ from ares.core.scope_firewall import OSFirewallController
+ if OSFirewallController.is_elevated():
+ return SandboxResult(
+ module_id=module_id,
+ sandbox_tier=IsolationTier.SUBPROCESS,
+ success=False,
+ error="Privilege dropping (drop_privileges=True) is unsupported on Windows while running as Administrator; execution aborted to prevent unconfined privileged execution.",
+ )
+
payload = json.dumps({
"module_id": module_id,
"params": params,
@@ -263,6 +292,7 @@ class SandboxRunner:
"tmpdir": tmpdir,
"scope_cidrs": _scope_cidrs,
"allow_network": self.policy.allow_network,
+ "allow_write": self.policy.allow_write,
})
wrapper = self._build_wrapper_script(use_seccomp)
@@ -397,41 +427,64 @@ class SandboxRunner:
def _make_preexec_fn(self):
"""
- Return preexec_fn that applies resource limits and security privileges in child process.
+ Return preexec_fn that applies resource limits and mandatory security privileges.
+ Executed in the child process immediately after fork() and before exec().
Only called on Unix systems.
"""
cpu_limit = self.policy.cpu_time_s
mem_bytes = self.policy.memory_mb * 1024 * 1024
+ allow_network = self.policy.allow_network
+ drop_privileges = self.policy.drop_privileges
+ allow_write = self.policy.allow_write
def _limits():
- try:
- resource.setrlimit(resource.RLIMIT_CPU, (cpu_limit, cpu_limit))
- 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:
+ # 1. Best-effort resource limits
+ if resource is not None:
try:
- import ctypes
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_limit, cpu_limit))
+ 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 allow_write:
+ resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0))
+ except (OSError, ValueError, AttributeError):
+ pass # best-effort resource limits
+
+ # 2. MANDATORY SECURITY CONTROL: Network isolation (fail-closed)
+ if not allow_network:
+ import ctypes
+ import ctypes.util
+ libc_name = ctypes.util.find_library("c") or "libc.so.6"
+ try:
+ _libc = ctypes.CDLL(libc_name, use_errno=True)
# 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:
+ ret = _libc.unshare(0x40000000)
+ if ret != 0:
+ errno_val = ctypes.get_errno()
+ raise RuntimeError(
+ f"unshare(CLONE_NEWNET) returned {ret} (errno={errno_val})"
+ )
+ except Exception as exc:
+ raise RuntimeError(
+ f"Mandatory security control failed: allow_network=False requires network namespace isolation: {exc}"
+ )
+
+ # 3. MANDATORY SECURITY CONTROL: Privilege dropping (fail-closed)
+ if 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
+ except Exception as exc:
+ raise RuntimeError(
+ f"Mandatory security control failed: drop_privileges=True failed to drop root to nobody: {exc}"
+ )
+ if getattr(os, "geteuid", lambda: -1)() == 0 or getattr(os, "getuid", lambda: -1)() == 0:
+ raise RuntimeError(
+ "Mandatory security control failed: process retains root privileges (uid/euid == 0) after drop"
+ )
return _limits
@@ -474,11 +527,48 @@ class SandboxRunner:
body = (
seccomp_preamble
- + "\nimport sys, json, asyncio\n\n"
+ + "\nimport sys, json, asyncio, os\n\n"
"payload = json.loads(sys.stdin.read())\n"
"module_id = payload[\"module_id\"]\n"
"params = payload[\"params\"]\n"
"campaign_id = payload.get(\"campaign_id\", \"\")\n"
+ "\n# ── Defense-in-depth: Python-level write hooks (when allow_write=False) ──\n"
+ "_allow_write = payload.get(\"allow_write\", False)\n"
+ "_tmpdir = payload.get(\"tmpdir\", \"\")\n"
+ "if not _allow_write and _tmpdir:\n"
+ " import builtins\n"
+ " _orig_open = builtins.open\n"
+ " _tmpdir_abs = os.path.abspath(_tmpdir)\n"
+ " def _sandboxed_open(file, mode=\"r\", *args, **kwargs):\n"
+ " if any(m in mode for m in (\"w\", \"a\", \"+\", \"x\")):\n"
+ " try:\n"
+ " target_path = os.path.abspath(str(file))\n"
+ " if not target_path.startswith(_tmpdir_abs):\n"
+ " raise PermissionError(f\"[Sandbox] Write prohibited outside sandbox directory: {file}\")\n"
+ " except (TypeError, ValueError):\n"
+ " pass\n"
+ " return _orig_open(file, mode, *args, **kwargs)\n"
+ " builtins.open = _sandboxed_open\n"
+ "\n"
+ " _orig_os_open = os.open\n"
+ " def _sandboxed_os_open(path, flags, *args, **kwargs):\n"
+ " write_flags = (\n"
+ " getattr(os, \"O_WRONLY\", 1) |\n"
+ " getattr(os, \"O_RDWR\", 2) |\n"
+ " getattr(os, \"O_CREAT\", 64) |\n"
+ " getattr(os, \"O_TRUNC\", 512) |\n"
+ " getattr(os, \"O_APPEND\", 1024)\n"
+ " )\n"
+ " if flags & write_flags:\n"
+ " try:\n"
+ " target_path = os.path.abspath(str(path))\n"
+ " if not target_path.startswith(_tmpdir_abs):\n"
+ " raise PermissionError(f\"[Sandbox] os.open write prohibited outside sandbox directory: {path}\")\n"
+ " except (TypeError, ValueError):\n"
+ " pass\n"
+ " return _orig_os_open(path, flags, *args, **kwargs)\n"
+ " os.open = _sandboxed_os_open\n"
+ "\n"
"\nasync def run():\n"
" try:\n"
" from ares.core.config import AresSettings\n"
@@ -517,7 +607,8 @@ class SandboxRunner:
" noise = NoiseController(campaign)\n"
" module = module_cls(settings=settings, campaign=campaign, noise=noise)\n"
" from ares.core.scope_firewall import scope_firewall_guard\n"
- " async with scope_firewall_guard(campaign=campaign, module_id=module_id):\n"
+ " _current_uid = getattr(os, 'getuid', lambda: None)()\n"
+ " async with scope_firewall_guard(campaign=campaign, module_id=module_id, uid_owner=_current_uid):\n"
" findings, extra = await module.run(**params)\n"
" return {\n"
" \"success\": True,\n"
diff --git a/ares/core/scope_firewall.py b/ares/core/scope_firewall.py
index fff36b5..0af1432 100644
--- a/ares/core/scope_firewall.py
+++ b/ares/core/scope_firewall.py
@@ -29,6 +29,7 @@ import sys
import threading
import urllib.request
from contextvars import ContextVar
+from enum import Enum
from typing import TYPE_CHECKING, Any, AsyncGenerator, Generator
from ares.core.errors import ScopeFirewallBlockError
@@ -590,32 +591,40 @@ def compute_out_of_scope_cidrs(
+class OSFirewallState(str, Enum):
+ UNINITIALIZED = "UNINITIALIZED"
+ APPLYING = "APPLYING"
+ VERIFIED_ACTIVE = "VERIFIED_ACTIVE"
+ INACTIVE = "INACTIVE"
+
+
class OSFirewallController:
"""Controls OS-level / Kernel network packet filtering boundaries.
Interacts directly with native OS packet filtering facilities:
- Windows: Windows Defender Firewall (`netsh advfirewall firewall`)
- - Linux: Netfilter (`iptables`)
-
- Operates in dual mode:
- 1. Elevated Mode (Admin/Root): Applies native OS firewall rules restricting
- outbound traffic strictly to authorized campaign scope CIDRs.
- - Windows: Calculates exact mathematical complement of scope CIDRs (excluding loopback)
- and applies explicit program-scoped BLOCK rules. Since Windows Firewall evaluates
- Block before Allow and defaults to outbound Allow, this establishes a true deny-by-default
- egress boundary for the python process without altering global host firewall policies.
- - Linux: Installs a 3-rule per-PID chain (lo ACCEPT, scope ACCEPT, and PID DROP)
- with exact comment tokens for 1:1 transactional teardown.
- 2. Unprivileged Mode: Gracefully yields to the In-Process Transport Socket Interceptor
- while recording audit logs, ensuring zero runtime crashes or elevation side-effects.
-
- Transactional safety:
- Every sub-rule is recorded. If any rule application fails, all previously applied rules
- in that transaction are automatically rolled back, leaving zero orphaned rules.
+ - Linux: Netfilter (`iptables` / `ip6tables`)
+
+ Architectural & Operational Scope:
+ 1. Windows Executable-Path Matching:
+ Windows Defender Firewall rules are applied via `program=<sys.executable>` and remote IP
+ complements. Because Windows Firewall CLI does not support per-PID matching, rules apply
+ to any process executing that exact Python executable during the rule's active lifetime.
+ Transactional teardown (`finally` and `atexit`) ensures zero orphaned rules.
+ 2. Linux UID-Based Matching:
+ Linux rules use `-m owner --uid-owner <uid>` when `uid_owner` is provided (e.g. unprivileged
+ module execution as 'nobody'), or fallback to `-m owner --pid-owner <pid>`.
+ NOTE: `--uid-owner` is a UID-wide firewall boundary affecting all processes sharing that UID,
+ not process-tree or namespace isolation.
+ 3. Transactional Safety & State Machine:
+ Transitions: UNINITIALIZED -> APPLYING -> VERIFIED_ACTIVE -> INACTIVE.
+ If any subrule in a transaction fails, all created rules in that transaction are rolled back
+ immediately in reverse order, leaving zero lingering or partial firewall state.
"""
_active_rules: set[str] = set()
_rule_cleanups: dict[str, list[list[str]]] = {}
+ _state: OSFirewallState = OSFirewallState.UNINITIALIZED
_lock = threading.Lock()
@classmethod
@@ -638,6 +647,7 @@ class OSFirewallController:
with cls._lock:
active_count = len(cls._active_rules)
rule_list = sorted(list(cls._active_rules))
+ state_val = cls._state.value
engine = (
"Windows Defender Firewall (netsh)"
@@ -648,7 +658,8 @@ class OSFirewallController:
"platform": sys.platform,
"engine": engine,
"elevated": elevated,
- "os_level_active": elevated and active_count > 0,
+ "state": state_val,
+ "os_level_active": elevated and active_count > 0 and cls._state == OSFirewallState.VERIFIED_ACTIVE,
"active_rules_count": active_count,
"active_rules": rule_list,
"fallback_mode": "In-Process Transport Socket Interception",
@@ -664,9 +675,12 @@ class OSFirewallController:
) -> list[str]:
"""Apply OS-level firewall rules restricting outbound egress to scope_cidrs.
+ If campaign is None with no scope_cidrs, or campaign.scope is unconfigured (None), returns empty list.
If process is not elevated, logs an audit notice and returns an empty list (safe fallback).
"""
- if not scope_cidrs:
+ if campaign is not None and getattr(campaign, "scope", None) is None:
+ return []
+ if campaign is None and not scope_cidrs:
return []
if not cls.is_elevated():
@@ -682,6 +696,9 @@ class OSFirewallController:
)
return []
+ with cls._lock:
+ cls._state = OSFirewallState.APPLYING
+
rule_token = secrets.token_hex(6)
rule_name = f"ARES_SCOPE_WALL_{rule_token}"
prog = program or sys.executable
@@ -690,6 +707,8 @@ class OSFirewallController:
if sys.platform == "win32":
out_of_scope = compute_out_of_scope_cidrs(scope_cidrs, allow_loopback=True, include_ipv6=True)
if not out_of_scope:
+ with cls._lock:
+ cls._state = OSFirewallState.INACTIVE if not cls._active_rules else OSFirewallState.VERIFIED_ACTIVE
return []
v4_out = [c for c in out_of_scope if ":" not in c]
@@ -739,7 +758,7 @@ class OSFirewallController:
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
+ # IPv4 Netfilter rules: allow loopback, allow scope if any, drop all other from this identity
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))
@@ -749,21 +768,24 @@ class OSFirewallController:
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_pos = "3" if v4_scope else "2"
+ drop_apply = ["iptables", "-I", "OUTPUT", drop_pos] + 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:
+ # IPv6 Netfilter rules: only install if v6_scope is provided or if scope_cidrs is explicitly empty (deny-all)
+ if v6_scope or (campaign is not None and not scope_cidrs):
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))
+ if v6_scope:
+ 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_pos = "3" if v6_scope else "2"
+ drop6_apply = ["ip6tables", "-I", "OUTPUT", drop6_pos] + 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))
@@ -784,12 +806,14 @@ class OSFirewallController:
logger.warning("os_firewall_apply_exception", rule=rule_name, error=str(exc))
break
- if not all_succeeded:
+ if not all_succeeded or len(applied_cleanups) != len(sub_rules):
for cleanup_cmd in reversed(applied_cleanups):
try:
subprocess.run(cleanup_cmd, capture_output=True, text=True, timeout=5)
except Exception:
pass
+ with cls._lock:
+ cls._state = OSFirewallState.INACTIVE if not cls._active_rules else OSFirewallState.VERIFIED_ACTIVE
if os.environ.get("ARES_REQUIRE_OS_FIREWALL") == "1":
raise ScopeFirewallBlockError(
f"[ScopeFirewall] Transactional OS firewall configuration failed for {rule_name}."
@@ -799,6 +823,7 @@ class OSFirewallController:
with cls._lock:
cls._active_rules.add(rule_name)
cls._rule_cleanups[rule_name] = applied_cleanups
+ cls._state = OSFirewallState.VERIFIED_ACTIVE
logger.info(
"os_firewall_transaction_committed",
@@ -816,6 +841,8 @@ class OSFirewallController:
with cls._lock:
cleanups = cls._rule_cleanups.pop(rule_name, None)
cls._active_rules.discard(rule_name)
+ if not cls._active_rules:
+ cls._state = OSFirewallState.INACTIVE
if cleanups:
for cleanup_cmd in reversed(cleanups):
@@ -913,6 +940,7 @@ async def scope_firewall_guard(
module_category: str = "",
enabled: bool | None = None,
enable_os_firewall: bool | None = None,
+ uid_owner: int | str | None = None,
) -> AsyncGenerator[ScopeFirewall | None, None]:
"""Async context manager activating dual-layer scope firewall."""
if enabled is None:
@@ -922,7 +950,10 @@ async def scope_firewall_guard(
"no",
)
- if not enabled or campaign is None or not getattr(campaign, "scope", None):
+ # Distinguish campaign is None vs campaign.scope is None vs campaign.scope == []
+ # If campaign is None or campaign.scope is None: no scope configured -> yield None
+ # If campaign.scope == []: explicit empty scope -> MUST deny all external destinations (fail-closed)
+ if not enabled or campaign is None or getattr(campaign, "scope", None) is None:
yield None
return
@@ -941,19 +972,26 @@ async def scope_firewall_guard(
)
token = _current_firewall.set(fw)
os_rules: list[str] = []
- if enable_os_firewall:
- os_rules = OSFirewallController.apply_rules(campaign, fw.scope_cidrs)
-
- # Neutralize proxy environment variables that could route traffic out-of-scope
- _enter_proxy_neutralization()
-
+ proxy_entered = False
try:
- yield fw
+ try:
+ if enable_os_firewall:
+ os_rules = OSFirewallController.apply_rules(
+ campaign, fw.scope_cidrs, uid_owner=uid_owner
+ )
+ # Neutralize proxy environment variables that could route traffic out-of-scope
+ _enter_proxy_neutralization()
+ proxy_entered = True
+ yield fw
+ finally:
+ try:
+ if proxy_entered:
+ _exit_proxy_neutralization()
+ finally:
+ if os_rules:
+ OSFirewallController.remove_rules(os_rules)
finally:
_current_firewall.reset(token)
- if os_rules:
- OSFirewallController.remove_rules(os_rules)
- _exit_proxy_neutralization()
@contextlib.contextmanager
@@ -963,6 +1001,7 @@ def scope_firewall_sync_guard(
module_category: str = "",
enabled: bool | None = None,
enable_os_firewall: bool | None = None,
+ uid_owner: int | str | None = None,
) -> Generator[ScopeFirewall | None, None, None]:
"""Sync context manager activating dual-layer scope firewall."""
if enabled is None:
@@ -972,7 +1011,7 @@ def scope_firewall_sync_guard(
"no",
)
- if not enabled or campaign is None or not getattr(campaign, "scope", None):
+ if not enabled or campaign is None or getattr(campaign, "scope", None) is None:
yield None
return
@@ -991,16 +1030,23 @@ def scope_firewall_sync_guard(
)
token = _current_firewall.set(fw)
os_rules: list[str] = []
- if enable_os_firewall:
- os_rules = OSFirewallController.apply_rules(campaign, fw.scope_cidrs)
-
- # Neutralize proxy environment variables that could route traffic out-of-scope
- _enter_proxy_neutralization()
-
+ proxy_entered = False
try:
- yield fw
+ try:
+ if enable_os_firewall:
+ os_rules = OSFirewallController.apply_rules(
+ campaign, fw.scope_cidrs, uid_owner=uid_owner
+ )
+ # Neutralize proxy environment variables that could route traffic out-of-scope
+ _enter_proxy_neutralization()
+ proxy_entered = True
+ yield fw
+ finally:
+ try:
+ if proxy_entered:
+ _exit_proxy_neutralization()
+ finally:
+ if os_rules:
+ OSFirewallController.remove_rules(os_rules)
finally:
_current_firewall.reset(token)
- if os_rules:
- OSFirewallController.remove_rules(os_rules)
- _exit_proxy_neutralization()
diff --git a/docs/security-model.md b/docs/security-model.md
index bf329de..2a72b55 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -315,16 +315,27 @@ Strict-Transport-Security: max-age=31536000
ARES deploys a strict dual-layer **Scope Firewall** (`ares.core.scope_firewall.ScopeFirewall` and `OSFirewallController`) to enforce fail-closed scope boundaries:
1. **OS / Kernel-Level Packet Filtering (Elevated Mode)**:
- - When running with administrative privileges (Windows Administrator / Linux root), `OSFirewallController` interacts directly with OS network packet filtering (`netsh advfirewall` on Windows, `iptables` on Linux), establishing outbound firewall rules that physically block network egress outside campaign scope CIDRs.
- - Includes automatic fail-safe rule teardown on context completion and process shutdown (`atexit`).
+ - When running with administrative privileges (Windows Administrator / Linux root), `OSFirewallController` interacts directly with OS network packet filtering (`netsh advfirewall` on Windows, `iptables` / `ip6tables` on Linux), establishing outbound firewall rules that physically block network egress outside campaign scope CIDRs.
+ - **Windows Executable-Path Matching (`program=<sys.executable>`)**: Windows Defender Firewall CLI lacks per-PID packet filtering. Rules are applied using executable-path matching (`program=<sys.executable>`) combined with mathematical complement CIDR block rules. Because rules match the binary path, any concurrent process executing that exact `python.exe` executable during the rule's active lifetime is subject to the egress block rules. Strict transactional lifecycle guarantees (`finally` blocks and `atexit` emergency cleanup) ensure rules are removed immediately upon task completion.
+ - **Linux UID-Based Matching (`--uid-owner`)**: Linux Netfilter rules match packets using `-m owner --uid-owner <uid>` when executing unprivileged sandboxes (e.g. `nobody`), or `--pid-owner <pid>`. Operators should note that `--uid-owner` is a UID-wide boundary affecting all processes running under that UID, rather than isolated process-tree filtering.
+ - **Linux Network Namespace Isolation (`CLONE_NEWNET`)**: When `allow_network=False` is requested in subprocess sandboxes, ARES executes `unshare(CLONE_NEWNET)` fail-closed, creating an isolated network namespace with zero external interfaces that inherently confines the child process and all its descendants.
+ - **Transactional State Machine**: State transitions strictly follow `UNINITIALIZED -> APPLYING -> VERIFIED_ACTIVE -> INACTIVE`. Every subrule application is tracked, and if any rule fails or verification mismatches, all applied rules are immediately rolled back in reverse order, preventing partial or orphaned firewall state.
2. **In-Process Transport Socket Interceptor (Process Mode)**:
- - Hooks low-level socket and event loop connections (`socket.connect`, `socket.sendto`, `asyncio.create_connection`) in Python user space, ensuring fail-closed scope enforcement even when running unprivileged without OS admin rights.
+ - Hooks low-level socket and event loop connections (`socket.connect`, `socket.sendto`, `socket.sendmsg`, `asyncio.create_connection`) in Python user space, ensuring fail-closed scope enforcement even when running unprivileged without OS admin rights.
- **Fail-Closed Egress Blocking**: Any out-of-scope connection attempt is instantly aborted with `ScopeFirewallBlockError` (status 403 Forbidden) and recorded in security audit logs.
- - **ContextVar Task Isolation**: Active exclusively within the attack module execution coroutine. Database pools, API requests, and telemetry tasks bypass the firewall in `< 0.00001ms`.
+ - **Explicit Empty Scope Semantics (`scope=[]` vs `scope=None`)**: `scope=None` represents unconfigured scope; `scope=[]` explicitly activates fail-closed deny-all egress blocking, rejecting all external IPv4 and IPv6 network access while preserving internal loopback IPC.
+ - **ContextVar Task Isolation & Guaranteed Context Restoration**: Active exclusively within the attack module execution coroutine. Structured nested `try...finally` blocks guarantee that the `_current_firewall` ContextVar always restores the exact previous context token (including nested outer guards and setup failures), preventing state leaks across async tasks.
- **DNS Re-entrancy & Rebinding Defense**: Non-blocking hostname resolution checks resolved IPs against scope CIDRs, with an internal lock preventing recursive interception.
- **Loopback & Proactor IPC Safety**: Exempts internal loopback (`127.0.0.1`, `::1`) and Windows Proactor event loop named pipes.
- **Cloud Category Allowlist**: Cloud modules (`MODULE_CATEGORY == "cloud"`) are permitted to access official provider endpoints (`*.microsoftonline.com`, `*.amazonaws.com`, etc.) while blocking untrusted egress.
+### Sandbox Execution & Filesystem Isolation Semantics
+
+ARES provides four isolation tiers (`IsolationTier` in `ares.core.sandbox`) with explicit boundary definitions:
+- **`DOCKER` (Tier 3)**: Full OS container isolation. When `allow_write=False`, the root filesystem is mounted strictly read-only (`read_only=True`). When `allow_network=False`, container network mode is set to `'none'`. CPU and memory quotas are enforced by kernel cgroups.
+- **`SUBPROCESS` (Tier 1 & 2)**: Separate child Python process. Working directory is locked to an ephemeral `ares-sandbox-*` temporary directory. On Unix, `RLIMIT_FSIZE=(0,0)` is applied to inhibit file enlargement, and Python-level `builtins.open` / `os.open` write hooks provide defense-in-depth within the Python runtime. Note: Subprocess tier does not provide complete OS mount namespace isolation; operations like metadata modification or native extensions can bypass Python-level hooks if not running in Docker.
+- **Privilege Dropping (`drop_privileges=True`)**: On Linux, child processes starting as root (`EUID 0`) drop privileges to `nobody` fail-closed (`setgroups([])`, `setgid`, `setuid`), verifying non-root UID before payload execution. On Windows, privilege dropping from Administrator is unsupported and execution is rejected fail-closed to prevent unconfined privileged execution.
+
### CampaignGuardrail & Pre-Flight Scope Enforcement
Every module execution passes through comprehensive pre-flight verification:
diff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.py
index 1921d54..6df9f9f 100644
--- a/tests/unit/test_hardening.py
+++ b/tests/unit/test_hardening.py
@@ -934,7 +934,7 @@ class TestSandboxAndFirewallHardening:
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
+ assert "scope_firewall_guard(campaign=campaign, module_id=module_id" in wrapper_source
def test_seccomp_tier_is_fail_closed(self):
"""
@@ -1020,4 +1020,418 @@ class TestSandboxAndFirewallHardening:
assert any(ext_v6 in ipaddress.ip_network(c) for c in v6_cidrs), "Cloudflare IPv6 must be in out-of-scope complement"
+# ═══════════════════════════════════════════════════════════════════════════════
+# ADVANCED BOUNDARY HARDENING & LIFECYCLE CORRECTNESS TESTS
+# ═══════════════════════════════════════════════════════════════════════════════
+
+class TestSecurityBoundariesAndLifecycle:
+ """
+ Validates fail-closed semantics for:
+ - allow_network=False network namespace isolation
+ - drop_privileges=True root privilege drop
+ - scope=[] empty scope deny-all semantics & loopback
+ - ContextVar nested context restoration & setup failure cleanup
+ - uid_owner parameter forwarding & UID-wide boundary semantics
+ - OSFirewallController transactional state machine & rollback
+ - Defense-in-depth write barrier in subprocess wrapper
+ """
+
+ def test_subprocess_allow_network_false_fails_closed(self, monkeypatch):
+ """
+ FINDING A: allow_network=False must fail-closed if unshare(CLONE_NEWNET) fails.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ policy = SandboxPolicy(allow_network=False)
+ runner = SandboxRunner(policy=policy)
+ preexec = runner._make_preexec_fn()
+ assert preexec is not None
+
+ # Simulate unshare returning failure (-1)
+ mock_libc = MagicMock()
+ mock_libc.unshare.return_value = -1
+
+ mock_cdll = MagicMock(return_value=mock_libc)
+ monkeypatch.setattr("ctypes.CDLL", mock_cdll)
+ monkeypatch.setattr("ctypes.get_errno", lambda: 1) # EPERM
+
+ with pytest.raises(RuntimeError, match="allow_network=False requires network namespace isolation"):
+ preexec()
+
+ # Simulate unshare raising an exception
+ mock_libc.unshare.side_effect = OSError("Permission denied")
+ with pytest.raises(RuntimeError, match="allow_network=False requires network namespace isolation"):
+ preexec()
+
+ # Simulate unshare succeeding (0)
+ mock_libc.unshare.side_effect = None
+ mock_libc.unshare.return_value = 0
+ preexec() # Must not raise
+
+ def test_subprocess_allow_network_true_does_not_unshare(self, monkeypatch):
+ """
+ allow_network=True must not attempt unshare(CLONE_NEWNET).
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ policy = SandboxPolicy(allow_network=True)
+ runner = SandboxRunner(policy=policy)
+ preexec = runner._make_preexec_fn()
+
+ mock_libc = MagicMock()
+ mock_cdll = MagicMock(return_value=mock_libc)
+ monkeypatch.setattr("ctypes.CDLL", mock_cdll)
+
+ preexec()
+ mock_libc.unshare.assert_not_called()
+
+ def test_subprocess_drop_privileges_fails_closed(self, monkeypatch):
+ """
+ FINDING B: drop_privileges=True must abort execution if root fails to drop privileges.
+ """
+ import types
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ policy = SandboxPolicy(drop_privileges=True)
+ runner = SandboxRunner(policy=policy)
+ preexec = runner._make_preexec_fn()
+
+ # Simulate running as root (euid == 0)
+ monkeypatch.setattr(os, "geteuid", lambda: 0, raising=False)
+
+ # Mock pwd
+ mock_nobody = types.SimpleNamespace(pw_uid=65534, pw_gid=65534)
+ mock_pwd = types.ModuleType("pwd")
+ mock_pwd.getpwnam = lambda name: mock_nobody
+ monkeypatch.setattr("sys.modules", {**sys.modules, "pwd": mock_pwd})
+
+ # Failure 1: setuid raises PermissionError
+ monkeypatch.setattr(os, "setgroups", lambda g: None, raising=False)
+ monkeypatch.setattr(os, "setgid", lambda g: None, raising=False)
+
+ def mock_failing_setuid(uid):
+ raise PermissionError("Operation not permitted")
+
+ monkeypatch.setattr(os, "setuid", mock_failing_setuid, raising=False)
+
+ with pytest.raises(RuntimeError, match="drop_privileges=True failed to drop root to nobody"):
+ preexec()
+
+ # Failure 2: setuid returns but geteuid still returns 0 (post-drop verification failure)
+ monkeypatch.setattr(os, "setuid", lambda uid: None, raising=False)
+ with pytest.raises(RuntimeError, match="process retains root privileges"):
+ preexec()
+
+ # Success: setuid succeeds and geteuid returns 65534
+ euid_state = [0]
+ monkeypatch.setattr(os, "geteuid", lambda: euid_state[0], raising=False)
+ monkeypatch.setattr(os, "getuid", lambda: euid_state[0], raising=False)
+
+ def mock_working_setuid(uid):
+ euid_state[0] = uid
+
+ monkeypatch.setattr(os, "setuid", mock_working_setuid, raising=False)
+ preexec() # Must succeed
+
+ def test_subprocess_drop_privileges_non_root_is_safe(self, monkeypatch):
+ """
+ When running as non-root (euid != 0), drop_privileges=True is safe and no-op.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ policy = SandboxPolicy(drop_privileges=True)
+ runner = SandboxRunner(policy=policy)
+ preexec = runner._make_preexec_fn()
+
+ monkeypatch.setattr(os, "geteuid", lambda: 1000, raising=False)
+ preexec() # Must not raise
+
+ def test_windows_elevated_drop_privileges_aborts_execution(self, monkeypatch):
+ """
+ On Windows, if running elevated (Admin) with drop_privileges=True,
+ execution must be aborted fail-closed rather than silently ignored.
+ """
+ import asyncio
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+ from ares.core.scope_firewall import OSFirewallController
+
+ policy = SandboxPolicy(drop_privileges=True)
+ runner = SandboxRunner(policy=policy)
+
+ monkeypatch.setattr("os.name", "nt")
+ monkeypatch.setattr(OSFirewallController, "is_elevated", classmethod(lambda cls: True))
+
+ res = asyncio.run(runner._run_subprocess("test.module", {}, "camp-123"))
+ assert res.success is False
+ assert "drop_privileges=True" in res.error
+ assert "unsupported on Windows" in res.error
+
+ def test_empty_scope_denies_external_network(self):
+ """
+ FINDING D: scope=[] must actively install firewall and block all external destinations.
+ """
+ from ares.core.campaign import Campaign, NoiseProfile
+ from ares.core.scope_firewall import ScopeFirewall, ScopeFirewallBlockError
+
+ # Explicit empty scope (deny-all)
+ campaign = Campaign(name="test-empty", scope=[], noise_profile=NoiseProfile.NORMAL)
+ fw = ScopeFirewall(campaign=campaign)
+
+ # External IPv4 must be blocked
+ with pytest.raises(ScopeFirewallBlockError, match="(?i)BLOCKED"):
+ fw.assert_allowed_address(("8.8.8.8", 443))
+
+ with pytest.raises(ScopeFirewallBlockError, match="(?i)BLOCKED"):
+ fw.assert_allowed_address(("1.1.1.1", 53))
+
+ # External IPv6 must be blocked
+ with pytest.raises(ScopeFirewallBlockError, match="(?i)BLOCKED"):
+ fw.assert_allowed_address(("2001:4860:4860::8888", 53))
+
+ def test_empty_scope_loopback_semantics(self):
+ """
+ scope=[] preserves internal loopback IPC when allow_loopback_ipc=True,
+ and blocks loopback if allow_loopback_ipc=False.
+ """
+ from ares.core.campaign import Campaign, NoiseProfile
+ from ares.core.scope_firewall import ScopeFirewall, ScopeFirewallBlockError
+
+ campaign = Campaign(name="test-empty", scope=[], noise_profile=NoiseProfile.NORMAL)
+ fw = ScopeFirewall(campaign=campaign, allow_loopback_ipc=True)
+
+ # Loopback IPv4 is allowed
+ assert fw.assert_allowed_address(("127.0.0.1", 8080)) is not None
+ assert fw.assert_allowed_address(("localhost", 8080)) is not None
+
+ # Loopback IPv6 is allowed
+ assert fw.assert_allowed_address(("::1", 8080)) is not None
+
+ # When loopback is disabled, even loopback is blocked
+ fw_no_lo = ScopeFirewall(campaign=campaign, allow_loopback_ipc=False)
+ with pytest.raises(ScopeFirewallBlockError, match="(?i)BLOCKED"):
+ fw_no_lo.assert_allowed_address(("127.0.0.1", 8080))
+
+ def test_scope_guard_restores_context_on_setup_failure(self, monkeypatch):
+ """
+ FINDING E: If OS firewall or setup raises an exception, _current_firewall
+ must be reset back to its previous value (None).
+ """
+ import asyncio
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import (
+ scope_firewall_guard,
+ _current_firewall,
+ OSFirewallController,
+ ScopeFirewallBlockError,
+ )
+
+ campaign = Campaign(name="test-camp", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+
+ # Simulate OS firewall failure
+ monkeypatch.setattr(
+ OSFirewallController,
+ "apply_rules",
+ classmethod(lambda cls, *args, **kwargs: (_ for _ in ()).throw(ScopeFirewallBlockError("Setup failed"))),
+ )
+
+ async def _run():
+ with pytest.raises(ScopeFirewallBlockError, match="Setup failed"):
+ async with scope_firewall_guard(campaign=campaign, enable_os_firewall=True):
+ pass
+
+ asyncio.run(_run())
+
+ # CRITICAL ASSERTION: context must not leak
+ assert _current_firewall.get() is None, "ContextVar leaked after setup failure!"
+
+ def test_scope_guard_restores_nested_parent_context(self, monkeypatch):
+ """
+ CRITICAL NESTED-CONTEXT TEST: When inner guard setup fails,
+ _current_firewall must restore the OUTER guard's context, not None!
+ """
+ import asyncio
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import (
+ scope_firewall_guard,
+ _current_firewall,
+ OSFirewallController,
+ ScopeFirewallBlockError,
+ )
+
+ outer_campaign = Campaign(name="outer", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+ inner_campaign = Campaign(name="inner", scope=[ScopeEntry(cidr="192.168.1.0/24")])
+
+ async def _run():
+ async with scope_firewall_guard(campaign=outer_campaign, enable_os_firewall=False) as outer_fw:
+ assert _current_firewall.get() is outer_fw, "Outer context not set"
+
+ # Simulate inner guard setup failure
+ def mock_failing_apply(*args, **kwargs):
+ raise ScopeFirewallBlockError("Inner OS firewall failed")
+
+ monkeypatch.setattr(OSFirewallController, "apply_rules", classmethod(mock_failing_apply))
+
+ with pytest.raises(ScopeFirewallBlockError, match="Inner OS firewall failed"):
+ async with scope_firewall_guard(campaign=inner_campaign, enable_os_firewall=True):
+ pass
+
+ # INVARIANT: Must restore outer_fw, NOT None!
+ assert _current_firewall.get() is outer_fw, \
+ f"Expected outer context {outer_fw}, got {_current_firewall.get()}"
+
+ # Outside outer guard, must be None
+ assert _current_firewall.get() is None
+
+ asyncio.run(_run())
+
+ def test_sync_scope_guard_restores_nested_parent_context(self, monkeypatch):
+ """
+ Sync scope firewall guard must also restore previous outer context on failure.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import (
+ scope_firewall_sync_guard,
+ _current_firewall,
+ OSFirewallController,
+ ScopeFirewallBlockError,
+ )
+
+ outer_campaign = Campaign(name="outer-sync", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+ inner_campaign = Campaign(name="inner-sync", scope=[ScopeEntry(cidr="192.168.1.0/24")])
+
+ with scope_firewall_sync_guard(campaign=outer_campaign, enable_os_firewall=False) as outer_fw:
+ assert _current_firewall.get() is outer_fw
+
+ monkeypatch.setattr(
+ OSFirewallController,
+ "apply_rules",
+ classmethod(lambda cls, *args, **kwargs: (_ for _ in ()).throw(ScopeFirewallBlockError("Inner fail"))),
+ )
+
+ with pytest.raises(ScopeFirewallBlockError):
+ with scope_firewall_sync_guard(campaign=inner_campaign, enable_os_firewall=True):
+ pass
+
+ assert _current_firewall.get() is outer_fw
+
+ assert _current_firewall.get() is None
+
+ def test_uid_owner_is_forwarded_to_os_firewall(self, monkeypatch):
+ """
+ FINDING F: uid_owner parameter must be forwarded through scope_firewall_guard
+ down to OSFirewallController.apply_rules.
+ """
+ import asyncio
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_guard, OSFirewallController
+
+ campaign = Campaign(name="test-uid", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+
+ recorded_uid = []
+ def mock_apply(cls, camp, cidrs, program=None, uid_owner=None):
+ recorded_uid.append(uid_owner)
+ return ["TEST_RULE"]
+
+ monkeypatch.setattr(OSFirewallController, "apply_rules", classmethod(mock_apply))
+ monkeypatch.setattr(OSFirewallController, "remove_rules", classmethod(lambda cls, rules: len(rules)))
+
+ async def _run():
+ async with scope_firewall_guard(campaign=campaign, enable_os_firewall=True, uid_owner=65534):
+ pass
+
+ asyncio.run(_run())
+ assert recorded_uid == [65534], f"uid_owner not forwarded correctly: {recorded_uid}"
+
+ def test_os_firewall_transactional_state_and_rollback(self, monkeypatch):
+ """
+ FINDING G: OSFirewallController state must transition through APPLYING
+ and VERIFIED_ACTIVE. If a subrule fails, it must rollback and set INACTIVE.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import OSFirewallController, OSFirewallState
+
+ campaign = Campaign(name="test-tx", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+ monkeypatch.setattr(OSFirewallController, "is_elevated", classmethod(lambda cls: True))
+ monkeypatch.setattr("sys.platform", "linux")
+
+ executed_cleanups = []
+ call_count = [0]
+
+ def mock_subprocess_run(cmd, *args, **kwargs):
+ call_count[0] += 1
+ cmd_str = " ".join(cmd)
+ # Second apply command fails
+ if "-I" in cmd and call_count[0] == 2:
+ res = MagicMock()
+ res.returncode = 1
+ res.stderr = "iptables: rule insertion failed"
+ res.stdout = ""
+ return res
+ if "-D" in cmd:
+ executed_cleanups.append(cmd)
+ res = MagicMock()
+ res.returncode = 0
+ return res
+
+ monkeypatch.setattr("subprocess.run", mock_subprocess_run)
+
+ # Clear any prior state
+ OSFirewallController._active_rules.clear()
+ OSFirewallController._state = OSFirewallState.UNINITIALIZED
+
+ rules = OSFirewallController.apply_rules(campaign, ["10.0.0.0/8"])
+ assert rules == [], "Failed transaction must return empty list"
+ assert len(executed_cleanups) > 0, "Rollback cleanups must be executed"
+ assert OSFirewallController._state == OSFirewallState.INACTIVE
+ assert len(OSFirewallController._active_rules) == 0
+
+ def test_os_firewall_verified_active_when_all_succeed(self, monkeypatch):
+ """
+ When all subrules succeed, state becomes VERIFIED_ACTIVE and rules are tracked.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import OSFirewallController, OSFirewallState
+
+ campaign = Campaign(name="test-ok", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+ monkeypatch.setattr(OSFirewallController, "is_elevated", classmethod(lambda cls: True))
+ monkeypatch.setattr("sys.platform", "linux")
+
+ cleanups_recorded = []
+ def mock_subprocess_run(cmd, *args, **kwargs):
+ if "-D" in cmd:
+ cleanups_recorded.append(cmd)
+ res = MagicMock()
+ res.returncode = 0
+ return res
+
+ monkeypatch.setattr("subprocess.run", mock_subprocess_run)
+
+ OSFirewallController._active_rules.clear()
+ rules = OSFirewallController.apply_rules(campaign, ["10.0.0.0/8"])
+ assert len(rules) == 1
+ assert OSFirewallController._state == OSFirewallState.VERIFIED_ACTIVE
+ assert OSFirewallController.get_status()["os_level_active"] is True
+
+ # Now remove rules
+ removed = OSFirewallController.remove_rules(rules)
+ assert removed > 0
+ assert OSFirewallController._state == OSFirewallState.INACTIVE
+ assert len(cleanups_recorded) > 0
+
+ def test_allow_write_false_wrapper_defense_in_depth(self):
+ """
+ FINDING C & 5: Wrapper script installs defense-in-depth open/write hooks
+ prohibiting writes outside the dedicated temporary sandbox directory.
+ """
+ from ares.core.sandbox import SandboxRunner
+
+ source = SandboxRunner._build_wrapper_script(use_seccomp=False)
+ assert "_sandboxed_open" in source
+ assert "_sandboxed_os_open" in source
+ assert "Write prohibited outside sandbox directory" in source
+ assert "builtins.open = _sandboxed_open" in source
+ assert "os.open = _sandboxed_os_open" in source
+
+
+