ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(security): parent-managed UID firewall, active kernel verification, cleanup retention, and canonical path containment
Mafifrizifed309832fbc
diff --git a/ares/core/sandbox.py b/ares/core/sandbox.pyindex b0454f6..49d8626 100644--- a/ares/core/sandbox.py+++ b/ares/core/sandbox.py@@ -297,33 +297,60 @@ class SandboxRunner:wrapper = self._build_wrapper_script(use_seccomp)script_path = os.path.join(tmpdir, "runner.py")- with open(script_path, "w") as f:+ with open(script_path, "w", encoding="utf-8") as f:f.write(wrapper)preexec = self._make_preexec_fn() if os.name != "nt" else None- proc = await asyncio.create_subprocess_exec(- sys.executable, script_path,- stdin=asyncio.subprocess.PIPE,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- preexec_fn=preexec,- cwd=tmpdir,+ # If drop_privileges is requested on Linux while running as root, the parent+ # orchestrator installs the UID-based OS firewall rules before spawning the child,+ # ensuring that the child is restricted by Netfilter the instant it drops privileges.+ parent_uid_firewall = None+ if os.name != "nt" and self.policy.drop_privileges and getattr(os, "geteuid", lambda: -1)() == 0:+ try:+ import pwd+ parent_uid_firewall = pwd.getpwnam("nobody").pw_uid+ except Exception:+ parent_uid_firewall = 65534++ from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+ from ares.core.scope_firewall import scope_firewall_guard++ parent_scope = [ScopeEntry(cidr=c) for c in _scope_cidrs] if self.policy.allow_network else []+ parent_campaign = Campaign(+ id=campaign_id or str(uuid.uuid4()),+ name="sandbox-subprocess-parent",+ scope=parent_scope,+ noise_profile=NoiseProfile.NORMAL,)- try:- stdout_b, stderr_b = await asyncio.wait_for(- proc.communicate(payload.encode()),- timeout=self.policy.timeout_s,- )- except asyncio.TimeoutError:- proc.kill()- await proc.wait()- return SandboxResult(- module_id=module_id, sandbox_tier=IsolationTier.SUBPROCESS,- success=False, error=f"Sandbox timeout ({self.policy.timeout_s}s)",+ async with scope_firewall_guard(+ campaign=parent_campaign,+ enable_os_firewall=(parent_uid_firewall is not None),+ uid_owner=parent_uid_firewall,+ ):+ proc = await asyncio.create_subprocess_exec(+ sys.executable, script_path,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ preexec_fn=preexec,+ cwd=tmpdir,)+ try:+ stdout_b, stderr_b = await asyncio.wait_for(+ proc.communicate(payload.encode()),+ timeout=self.policy.timeout_s,+ )+ except asyncio.TimeoutError:+ proc.kill()+ await proc.wait()+ return SandboxResult(+ module_id=module_id, sandbox_tier=IsolationTier.SUBPROCESS,+ success=False, error=f"Sandbox timeout ({self.policy.timeout_s}s)",+ )+stdout = stdout_b.decode(errors="replace")stderr = stderr_b.decode(errors="replace")@@ -533,20 +560,30 @@ class SandboxRunner:"params = payload[\"params\"]\n""campaign_id = payload.get(\"campaign_id\", \"\")\n""\n# ── Defense-in-depth: Python-level write hooks (when allow_write=False) ──\n"+ "# Classification: DEFENSE-IN-DEPTH for Python stdlib. Complete filesystem sandboxing\n"+ "# requires the DOCKER tier (read_only=True rootfs mount).\n""_allow_write = payload.get(\"allow_write\", False)\n""_tmpdir = payload.get(\"tmpdir\", \"\")\n""if not _allow_write and _tmpdir:\n"" import builtins\n"+ " def _is_contained_in_sandbox(target_path, sandbox_dir):\n"+ " try:\n"+ " real_sandbox = os.path.realpath(sandbox_dir)\n"+ " target_str = str(target_path)\n"+ " if not os.path.exists(target_str):\n"+ " parent = os.path.dirname(target_str) or \".\"\n"+ " real_target = os.path.join(os.path.realpath(parent), os.path.basename(target_str))\n"+ " else:\n"+ " real_target = os.path.realpath(target_str)\n"+ " return os.path.commonpath([real_sandbox, real_target]) == real_sandbox\n"+ " except (ValueError, OSError, TypeError):\n"+ " return False\n"+ "\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"+ " if not _is_contained_in_sandbox(file, _tmpdir):\n"+ " raise PermissionError(f\"[Sandbox] Write prohibited outside sandbox directory: {file}\")\n"" return _orig_open(file, mode, *args, **kwargs)\n"" builtins.open = _sandboxed_open\n""\n"@@ -560,12 +597,8 @@ class SandboxRunner:" 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"+ " if not _is_contained_in_sandbox(path, _tmpdir):\n"+ " raise PermissionError(f\"[Sandbox] os.open write prohibited outside sandbox directory: {path}\")\n"" return _orig_os_open(path, flags, *args, **kwargs)\n"" os.open = _sandboxed_os_open\n""\n"@@ -608,7 +641,7 @@ class SandboxRunner:" module = module_cls(settings=settings, campaign=campaign, noise=noise)\n"" from ares.core.scope_firewall import scope_firewall_guard\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"+ " async with scope_firewall_guard(campaign=campaign, module_id=module_id, enable_os_firewall=False, 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.pyindex 0af1432..5d4de13 100644--- a/ares/core/scope_firewall.py+++ b/ares/core/scope_firewall.py@@ -594,7 +594,9 @@ def compute_out_of_scope_cidrs(class OSFirewallState(str, Enum):UNINITIALIZED = "UNINITIALIZED"APPLYING = "APPLYING"+ VERIFICATION_FAILED = "VERIFICATION_FAILED"VERIFIED_ACTIVE = "VERIFIED_ACTIVE"+ CLEANUP_PENDING = "CLEANUP_PENDING"INACTIVE = "INACTIVE"@@ -617,9 +619,10 @@ class OSFirewallController: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.+ Transitions: UNINITIALIZED -> APPLYING -> (verify in OS) -> VERIFIED_ACTIVE -> INACTIVE.+ If any subrule fails or fails OS verification, all applied rules in that transaction are rolled+ back immediately in reverse order. If cleanup of any rule fails, the rule is retained in+ state tracking, transitioning to CLEANUP_PENDING rather than falsely claiming INACTIVE."""_active_rules: set[str] = set()@@ -648,6 +651,7 @@ class OSFirewallController:active_count = len(cls._active_rules)rule_list = sorted(list(cls._active_rules))state_val = cls._state.value+ cleanup_pending = cls._state == OSFirewallState.CLEANUP_PENDINGengine = ("Windows Defender Firewall (netsh)"@@ -660,11 +664,46 @@ class OSFirewallController:"elevated": elevated,"state": state_val,"os_level_active": elevated and active_count > 0 and cls._state == OSFirewallState.VERIFIED_ACTIVE,+ "cleanup_pending": cleanup_pending,"active_rules_count": active_count,"active_rules": rule_list,"fallback_mode": "In-Process Transport Socket Interception",}+ @classmethod+ def _verify_subrules(cls, sub_rules: list[tuple[list[str], list[str]]]) -> bool:+ """Query kernel/OS packet filter directly to verify that all applied rules exist in kernel state."""+ for apply_cmd, _ in sub_rules:+ try:+ if sys.platform == "win32":+ sub_name = None+ for arg in apply_cmd:+ if arg.startswith("name="):+ sub_name = arg.split("=", 1)[1]+ break+ if not sub_name:+ return False+ check_cmd = ["netsh", "advfirewall", "firewall", "show", "rule", f"name={sub_name}"]+ res = subprocess.run(check_cmd, capture_output=True, text=True, timeout=5)+ if res.returncode != 0 or "no rules match" in res.stdout.lower():+ logger.warning("os_firewall_verification_failed_windows", sub_rule=sub_name, output=res.stdout.strip())+ return False+ elif sys.platform.startswith("linux"):+ bin_name = apply_cmd[0]+ # apply_cmd format: [bin, "-I", "OUTPUT", pos, *spec]+ if len(apply_cmd) >= 4 and apply_cmd[1] == "-I":+ check_cmd = [bin_name, "-C", apply_cmd[2]] + apply_cmd[4:]+ else:+ check_cmd = [bin_name, "-C", "OUTPUT"] + apply_cmd[3:]+ res = subprocess.run(check_cmd, capture_output=True, text=True, timeout=5)+ if res.returncode != 0:+ logger.warning("os_firewall_verification_failed_linux", cmd=check_cmd, error=res.stderr.strip() or res.stdout.strip())+ return False+ except Exception as exc:+ logger.warning("os_firewall_verification_exception", error=str(exc))+ return False+ return True+@classmethoddef apply_rules(cls,@@ -807,19 +846,53 @@ class OSFirewallController:breakif not all_succeeded or len(applied_cleanups) != len(sub_rules):+ failed_rollbacks = []for cleanup_cmd in reversed(applied_cleanups):try:- subprocess.run(cleanup_cmd, capture_output=True, text=True, timeout=5)+ cres = subprocess.run(cleanup_cmd, capture_output=True, text=True, timeout=5)+ if cres.returncode != 0:+ failed_rollbacks.append(cleanup_cmd)except Exception:- pass+ failed_rollbacks.append(cleanup_cmd)with cls._lock:- cls._state = OSFirewallState.INACTIVE if not cls._active_rules else OSFirewallState.VERIFIED_ACTIVE+ if failed_rollbacks:+ cls._rule_cleanups[rule_name] = failed_rollbacks+ cls._active_rules.add(rule_name)+ cls._state = OSFirewallState.CLEANUP_PENDING+ else:+ cls._state = OSFirewallState.INACTIVE if not cls._active_rules else OSFirewallState.VERIFIED_ACTIVEif os.environ.get("ARES_REQUIRE_OS_FIREWALL") == "1":raise ScopeFirewallBlockError(f"[ScopeFirewall] Transactional OS firewall configuration failed for {rule_name}.")return []+ # Explicit Verification Phase: Query actual kernel/OS firewall state directly+ verified = cls._verify_subrules(sub_rules)+ if not verified:+ logger.error("os_firewall_verification_failed_rolling_back", rule=rule_name)+ failed_rollbacks = []+ for cleanup_cmd in reversed(applied_cleanups):+ try:+ cres = subprocess.run(cleanup_cmd, capture_output=True, text=True, timeout=5)+ if cres.returncode != 0:+ failed_rollbacks.append(cleanup_cmd)+ except Exception:+ failed_rollbacks.append(cleanup_cmd)+ with cls._lock:+ cls._state = OSFirewallState.VERIFICATION_FAILED+ if failed_rollbacks:+ cls._rule_cleanups[rule_name] = failed_rollbacks+ cls._active_rules.add(rule_name)+ cls._state = OSFirewallState.CLEANUP_PENDING+ else:+ 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] OS firewall verification failed for {rule_name}; rolled back."+ )+ return []+with cls._lock:cls._active_rules.add(rule_name)cls._rule_cleanups[rule_name] = applied_cleanups@@ -835,23 +908,38 @@ class OSFirewallController:@classmethoddef remove_rules(cls, rule_ids: list[str]) -> int:- """Remove previously created OS firewall rules using exact recorded cleanups."""+ """Remove previously created OS firewall rules using exact recorded cleanups.++ State invariant: Rules and cleanup commands are ONLY removed from internal+ tracking after cleanup has succeeded in the OS. If any cleanup command fails,+ the rule is retained, state becomes CLEANUP_PENDING, and retry remains possible.+ """removed = 0- for rule_name in rule_ids:+ with cls._lock:+ rules_to_process = list(rule_ids)++ for rule_name in rules_to_process: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+ cleanups = list(cls._rule_cleanups.get(rule_name, []))+ failed_cleanups: list[list[str]] = []if cleanups:for cleanup_cmd in reversed(cleanups):try:res = subprocess.run(cleanup_cmd, capture_output=True, text=True, timeout=5)if res.returncode == 0:removed += 1+ else:+ failed_cleanups.append(cleanup_cmd)+ logger.warning(+ "os_firewall_cleanup_failed",+ rule=rule_name,+ cmd=cleanup_cmd,+ error=res.stderr.strip() or res.stdout.strip(),+ )except Exception as exc:- logger.warning("os_firewall_cleanup_failed", rule=rule_name, cmd=cleanup_cmd, error=str(exc))+ failed_cleanups.append(cleanup_cmd)+ logger.warning("os_firewall_cleanup_exception", rule=rule_name, cmd=cleanup_cmd, error=str(exc))else:try:if sys.platform == "win32":@@ -859,6 +947,8 @@ class OSFirewallController:res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)if res.returncode == 0:removed += 1+ else:+ failed_cleanups.append(cmd)elif sys.platform.startswith("linux"):for suffix in ("_lo", "_scope", "_drop", ""):comment = f"{rule_name}{suffix}"@@ -870,13 +960,31 @@ class OSFirewallController:except Exception as exc:logger.warning("os_firewall_remove_fallback_failed", rule=rule_name, error=str(exc))+ with cls._lock:+ if failed_cleanups:+ cls._rule_cleanups[rule_name] = failed_cleanups+ cls._active_rules.add(rule_name)+ cls._state = OSFirewallState.CLEANUP_PENDING+ logger.warning(+ "os_firewall_rule_cleanup_incomplete_retained",+ rule=rule_name,+ remaining_commands=len(failed_cleanups),+ )+ else:+ cls._rule_cleanups.pop(rule_name, None)+ cls._active_rules.discard(rule_name)+ if not cls._active_rules:+ cls._state = OSFirewallState.INACTIVE+ elif cls._state != OSFirewallState.CLEANUP_PENDING:+ cls._state = OSFirewallState.VERIFIED_ACTIVE+if removed > 0:logger.info("os_firewall_rules_removed", count=removed)return removed@classmethoddef cleanup_all(cls) -> None:- """Emergency cleanup handler executed at exit to guarantee zero orphaned OS rules."""+ """Emergency cleanup handler executed at exit to retry and guarantee zero orphaned OS rules."""with cls._lock:rules_to_clean = list(cls._active_rules)if rules_to_clean:diff --git a/docs/security-model.md b/docs/security-model.mdindex 2a72b55..6b352b5 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -316,10 +316,22 @@ Strict-Transport-Security: max-age=31536000ARES 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` / `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.+ - **Active Kernel State Verification**: CLI return codes are not treated as proof of enforcement. ARES explicitly queries the live kernel/OS packet filtering state (`iptables -C` / `ip6tables -C` on Linux, `netsh advfirewall firewall show rule` on Windows) to verify that every subrule physically exists before transitioning to `VERIFIED_ACTIVE`. If verification fails, the state transitions to `VERIFICATION_FAILED` and all applied rules are immediately rolled back.+ - **Resilient Cleanup Retention (`CLEANUP_PENDING`)**: In `remove_rules()` and emergency `cleanup_all()` (`atexit`), rules and cleanup commands are never purged from internal tracking upfront. If any cleanup command fails, the rule is retained in state tracking and the controller transitions to `CLEANUP_PENDING` (degraded mode), allowing cleanup retries and never falsely reporting `INACTIVE` while kernel rules may still exist.+ - **Parent-Managed Firewall Lifecycle for Dropped Privileges**: When `drop_privileges=True` is enabled on Linux, the child process running as `nobody` (UID 65534) lacks `CAP_NET_ADMIN` and cannot manipulate host packet filters. The elevated parent orchestrator installs the `--uid-owner <nobody>` Netfilter rules *before* spawning the child, enforcing the boundary physically in the Linux kernel the instant privileges drop, and tears down the rules in `finally` when the child terminates. The child process runs only Layer 2 in-process socket interception without attempting unprivileged OS firewall modifications.+ - **External Binary & Process Descendant Confinement**:+ - *Linux Offline (`allow_network=False`)*: `CLONE_NEWNET` network namespace unshare creates an isolated network namespace with zero external interfaces, inherently confining the child process, all descendants, and any external binaries (e.g. `curl`, `nmap`) executed within it.+ - *Linux Online (`allow_network=True`)*: Parent-managed `--uid-owner <uid>` Netfilter rules match all packets originating from that UID, confining external binaries launched by the sandbox child. Note: This is a host-wide UID boundary that affects all processes executing under that UID on the system.+ - *Windows*: Windows Defender Firewall CLI lacks per-PID and per-UID filtering. Rules are applied via `program=<sys.executable>`. While concurrent Python processes executing the exact same binary are restricted, external binaries (e.g. `curl.exe`, `powershell.exe`) do NOT match `python.exe` and are NOT restricted by the Windows Firewall rule. Operators requiring strict external binary confinement on Windows MUST execute modules inside the `DOCKER` tier.+ - **Windows Executable-Path Matching Collateral Scope**: Rules use `program=<sys.executable>` combined with mathematical complement CIDR block rules. Any concurrent process executing that exact `python.exe` executable during the rule's active lifetime is subject to egress blocking. Fail-safe transactional teardown (`finally` and `atexit` emergency cleanup) ensures rules are removed immediately upon task completion.+ - **Transactional State Machine**: State transitions strictly follow:+ ```text+ UNINITIALIZED -> APPLYING -> (verify in OS) -> VERIFIED_ACTIVE -> INACTIVE+ ↓ ↑+ VERIFICATION_FAILED ───────────────────────┤+ ↓ │+ CLEANUP_PENDING ──────────────────────────┘ (upon successful retry)+ ```2. **In-Process Transport Socket Interceptor (Process Mode)**:- 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.@@ -332,8 +344,10 @@ ARES deploys a strict dual-layer **Scope Firewall** (`ares.core.scope_firewall.S### Sandbox Execution & Filesystem Isolation SemanticsARES 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.+- **`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. Complete OS-level filesystem and external binary isolation is guaranteed exclusively at this tier.+- **`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.+ - **Canonical Path Containment Defense-in-Depth**: Application-level `builtins.open` and `os.open` hooks enforce canonical path containment (`os.path.realpath` + `os.path.commonpath`), strictly rejecting prefix-sibling attacks (e.g. `/tmp/ares-sandbox-123-evil`), symlink escapes, and relative directory traversals.+ - **Technical Classification**: Application-level open hooks are strictly classified as **DEFENSE-IN-DEPTH** for standard Python code. They do not constitute an impenetrable OS filesystem sandbox: native C/C++ extensions, direct syscalls, `os.rename`, `os.replace`, `truncate`, `ftruncate`, or file descriptors opened prior to sandboxing bypass Python-level hooks. Complete filesystem sandboxing requires Docker containers.- **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 Enforcementdiff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.pyindex 6df9f9f..0619cc5 100644--- a/tests/unit/test_hardening.py+++ b/tests/unit/test_hardening.py@@ -1431,6 +1431,252 @@ class TestSecurityBoundariesAndLifecycle:assert "Write prohibited outside sandbox directory" in sourceassert "builtins.open = _sandboxed_open" in sourceassert "os.open = _sandboxed_os_open" in source+ assert "_is_contained_in_sandbox" in source++ def test_canonical_path_containment_in_sandbox_hooks(self, tmp_path):+ """+ FINDING D: Canonical path containment must allow files inside the sandbox+ while strictly rejecting prefix-sibling directories, symlink escapes,+ and relative path directory traversals.+ """+ import os++ sandbox_dir = tmp_path / "ares-sandbox-123"+ sandbox_dir.mkdir()+ sub_dir = sandbox_dir / "sub"+ sub_dir.mkdir()++ # Prefix sibling directory (classic prefix attack)+ evil_sibling = tmp_path / "ares-sandbox-123-evil"+ evil_sibling.mkdir()++ outside_dir = tmp_path / "other"+ outside_dir.mkdir()+ target_outside_file = outside_dir / "secret.txt"+ target_outside_file.write_text("outside data")++ # Symlink inside sandbox pointing outside+ symlink_escape = sandbox_dir / "symlink_outside"+ try:+ os.symlink(str(target_outside_file), str(symlink_escape))+ has_symlink = True+ except (OSError, NotImplementedError):+ has_symlink = False++ # Extract the containment function logic tested in the sandbox wrapper+ def _is_contained_in_sandbox(target_path, sandbox_root):+ try:+ real_sandbox = os.path.realpath(str(sandbox_root))+ target_str = str(target_path)+ if not os.path.exists(target_str):+ parent = os.path.dirname(target_str) or "."+ real_target = os.path.join(os.path.realpath(parent), os.path.basename(target_str))+ else:+ real_target = os.path.realpath(target_str)+ return os.path.commonpath([real_sandbox, real_target]) == real_sandbox+ except (ValueError, OSError, TypeError):+ return False++ # 1. Inside sandbox -> ALLOWED+ assert _is_contained_in_sandbox(sandbox_dir / "file.txt", sandbox_dir) is True+ assert _is_contained_in_sandbox(sub_dir / "file.txt", sandbox_dir) is True++ # 2. Prefix sibling attack -> DENIED+ assert _is_contained_in_sandbox(evil_sibling / "file.txt", sandbox_dir) is False++ # 3. Completely outside directory -> DENIED+ assert _is_contained_in_sandbox(target_outside_file, sandbox_dir) is False++ # 4. Relative directory traversal -> DENIED+ traversal = sandbox_dir / "sub" / ".." / ".." / "other" / "secret.txt"+ assert _is_contained_in_sandbox(traversal, sandbox_dir) is False++ # 5. Symlink escaping sandbox -> DENIED+ if has_symlink:+ assert _is_contained_in_sandbox(symlink_escape, sandbox_dir) is False++ def test_os_firewall_verification_failure_triggers_rollback(self, monkeypatch):+ """+ FINDING B: If CLI command succeeds but kernel state verification fails,+ state transitions through VERIFICATION_FAILED, rolls back rules, and fails closed.+ """+ from ares.core.campaign import Campaign, ScopeEntry+ from ares.core.scope_firewall import OSFirewallController, OSFirewallState, ScopeFirewallBlockError++ campaign = Campaign(name="test-verif-fail", scope=[ScopeEntry(cidr="10.0.0.0/8")])+ monkeypatch.setattr(OSFirewallController, "is_elevated", classmethod(lambda cls: True))+ monkeypatch.setattr("sys.platform", "linux")+ monkeypatch.setenv("ARES_REQUIRE_OS_FIREWALL", "1")++ cleanups_run = []+ def mock_subprocess_run(cmd, *args, **kwargs):+ if "-D" in cmd:+ cleanups_run.append(cmd)+ res = MagicMock()+ res.returncode = 0+ return res++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)+ # Mock _verify_subrules returning False (kernel check failed)+ monkeypatch.setattr(OSFirewallController, "_verify_subrules", classmethod(lambda cls, sub_rules: False))++ OSFirewallController._active_rules.clear()+ with pytest.raises(ScopeFirewallBlockError, match="OS firewall verification failed"):+ OSFirewallController.apply_rules(campaign, ["10.0.0.0/8"])++ assert len(cleanups_run) > 0, "Rollback cleanups must run when verification fails"+ assert len(OSFirewallController._active_rules) == 0+ assert OSFirewallController._state == OSFirewallState.INACTIVE++ def test_os_firewall_cleanup_failure_retains_rule_state_and_sets_cleanup_pending(self, monkeypatch):+ """+ FINDING C & 5: When cleanup fails, rule state must NOT be erased.+ Controller must retain failed cleanups, report CLEANUP_PENDING, and allow retry.+ """+ from ares.core.campaign import Campaign, ScopeEntry+ from ares.core.scope_firewall import OSFirewallController, OSFirewallState++ campaign = Campaign(name="test-cleanup-fail", scope=[ScopeEntry(cidr="10.0.0.0/8")])+ monkeypatch.setattr(OSFirewallController, "is_elevated", classmethod(lambda cls: True))+ monkeypatch.setattr("sys.platform", "linux")++ def mock_ok(cmd, *args, **kwargs):+ res = MagicMock()+ res.returncode = 0+ return res++ monkeypatch.setattr("subprocess.run", mock_ok)+ monkeypatch.setattr(OSFirewallController, "_verify_subrules", classmethod(lambda cls, sub_rules: True))++ OSFirewallController._active_rules.clear()+ rules = OSFirewallController.apply_rules(campaign, ["10.0.0.0/8"])+ assert len(rules) == 1+ rule_name = rules[0]+ assert OSFirewallController._state == OSFirewallState.VERIFIED_ACTIVE++ # Now simulate cleanup failure+ def mock_fail_cleanup(cmd, *args, **kwargs):+ res = MagicMock()+ res.returncode = 1+ res.stderr = "iptables: Device or resource busy"+ return res++ monkeypatch.setattr("subprocess.run", mock_fail_cleanup)++ # Attempt to remove rules+ removed = OSFirewallController.remove_rules(rules)+ assert removed == 0, "Failed cleanups must not count as removed"++ # INVARIANT: Rule state must be RETAINED, state must be CLEANUP_PENDING+ assert rule_name in OSFirewallController._active_rules+ assert rule_name in OSFirewallController._rule_cleanups+ assert OSFirewallController._state == OSFirewallState.CLEANUP_PENDING+ assert OSFirewallController.get_status()["cleanup_pending"] is True+ assert OSFirewallController.get_status()["state"] == "CLEANUP_PENDING"++ # Now simulate cleanup retry succeeding+ monkeypatch.setattr("subprocess.run", mock_ok)+ OSFirewallController.cleanup_all()++ # After successful retry, rule is removed and state is INACTIVE+ assert len(OSFirewallController._active_rules) == 0+ assert rule_name not in OSFirewallController._rule_cleanups+ assert OSFirewallController._state == OSFirewallState.INACTIVE+ assert OSFirewallController.get_status()["cleanup_pending"] is False++ def test_concurrent_firewall_contexts_isolated(self, monkeypatch):+ """+ Concurrency: Multiple concurrent contexts must track independent rules.+ Removing Context A's rule must not erase Context B's rule.+ """+ from ares.core.campaign import Campaign, ScopeEntry+ from ares.core.scope_firewall import OSFirewallController, OSFirewallState++ campaign_a = Campaign(name="camp-a", scope=[ScopeEntry(cidr="10.0.0.0/8")])+ campaign_b = Campaign(name="camp-b", scope=[ScopeEntry(cidr="192.168.1.0/24")])+ monkeypatch.setattr(OSFirewallController, "is_elevated", classmethod(lambda cls: True))+ monkeypatch.setattr("sys.platform", "linux")++ def mock_ok(cmd, *args, **kwargs):+ res = MagicMock()+ res.returncode = 0+ return res++ monkeypatch.setattr("subprocess.run", mock_ok)+ monkeypatch.setattr(OSFirewallController, "_verify_subrules", classmethod(lambda cls, sub_rules: True))++ OSFirewallController._active_rules.clear()+ rules_a = OSFirewallController.apply_rules(campaign_a, ["10.0.0.0/8"])+ rules_b = OSFirewallController.apply_rules(campaign_b, ["192.168.1.0/24"])++ assert len(rules_a) == 1+ assert len(rules_b) == 1+ assert rules_a[0] != rules_b[0]+ assert len(OSFirewallController._active_rules) == 2+ assert OSFirewallController._state == OSFirewallState.VERIFIED_ACTIVE++ # Clean up Context A only+ removed_a = OSFirewallController.remove_rules(rules_a)+ assert removed_a > 0+ assert rules_a[0] not in OSFirewallController._active_rules+ assert rules_b[0] in OSFirewallController._active_rules+ # Still active because Context B is active!+ assert OSFirewallController._state == OSFirewallState.VERIFIED_ACTIVE++ # Clean up Context B+ removed_b = OSFirewallController.remove_rules(rules_b)+ assert removed_b > 0+ assert len(OSFirewallController._active_rules) == 0+ assert OSFirewallController._state == OSFirewallState.INACTIVE++ def test_parent_manages_uid_firewall_for_dropped_privileges(self, monkeypatch):+ """+ FINDING A: In _run_subprocess, when drop_privileges=True on Linux as root,+ the elevated parent wraps child execution with scope_firewall_guard(enable_os_firewall=True, uid_owner=target_uid).+ """+ import asyncio+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier+ import ares.core.sandbox as sandbox_mod++ policy = SandboxPolicy(tier=IsolationTier.SUBPROCESS, drop_privileges=True)+ runner = SandboxRunner(policy=policy)++ monkeypatch.setattr("os.name", "posix")+ monkeypatch.setattr("os.geteuid", lambda: 0, raising=False)++ import ares.core.scope_firewall as scope_fw_mod++ parent_guard_calls = []++ class MockGuardContext:+ def __init__(self, **kwargs):+ parent_guard_calls.append(kwargs)+ async def __aenter__(self):+ return None+ async def __aexit__(self, *args):+ pass++ monkeypatch.setattr(scope_fw_mod, "scope_firewall_guard", MockGuardContext)++ # Mock subprocess execution+ async def mock_create_subprocess(*args, **kwargs):+ mock_proc = MagicMock()+ async def mock_communicate(*args, **kwargs):+ return (b'{"success": true, "findings": [], "extra": {}}', b'')+ mock_proc.communicate = mock_communicate+ mock_proc.returncode = 0+ return mock_proc++ monkeypatch.setattr(asyncio, "create_subprocess_exec", mock_create_subprocess)++ result = asyncio.run(runner._run_subprocess("test.module", {}, "campaign-123"))+ assert result.success is True++ # Verify parent installed OS firewall with uid_owner+ assert len(parent_guard_calls) == 1+ assert parent_guard_calls[0]["enable_os_firewall"] is True+ assert parent_guard_calls[0]["uid_owner"] in (65534, getattr(monkeypatch, "fake_uid", 65534))+