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): implement Windows complement-CIDR allowlist, transactional Netfilter cleanup, and task-local proxy isolation
Mafifrizi4d1c389b108b
diff --git a/ares/core/sandbox.py b/ares/core/sandbox.pyindex b205ac6..5636f92 100644--- a/ares/core/sandbox.py+++ b/ares/core/sandbox.py@@ -480,7 +480,9 @@ class SandboxRunner:" settings = AresSettings()\n"" noise = NoiseController(campaign)\n"" module = module_cls(settings=settings, campaign=campaign, noise=noise)\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"" return {\n"" \"success\": True,\n"" \"findings\": [f.to_dict() if hasattr(f, \"to_dict\") else {} for f in findings],\n"diff --git a/ares/core/scope_firewall.py b/ares/core/scope_firewall.pyindex 75177fc..caba944 100644--- a/ares/core/scope_firewall.py+++ b/ares/core/scope_firewall.py@@ -350,6 +350,8 @@ _orig_socket_sendto = socket.socket.sendto_orig_socket_sendmsg = getattr(socket.socket, "sendmsg", None)_orig_loop_create_connection = asyncio.base_events.BaseEventLoop.create_connection_orig_urllib_getproxies = urllib.request.getproxies+_orig_requests_get_environ_proxies: Any = None+_orig_httpx_get_environment_proxies: Any = None_hooks_installed: bool = False@@ -359,6 +361,22 @@ def _firewall_getproxies() -> dict[str, str]:return _orig_urllib_getproxies()+def _firewall_requests_get_environ_proxies(url: Any, no_proxy: Any = None) -> dict[str, str]:+ if _current_firewall.get() is not None:+ return {}+ if _orig_requests_get_environ_proxies is not None:+ return _orig_requests_get_environ_proxies(url, no_proxy=no_proxy)+ return {}+++def _firewall_httpx_get_environment_proxies() -> dict[str, Any]:+ if _current_firewall.get() is not None:+ return {}+ if _orig_httpx_get_environment_proxies is not None:+ return _orig_httpx_get_environment_proxies()+ return {}++@functools.wraps(_orig_socket_connect)def _firewall_socket_connect(self: socket.socket, address: Any) -> None:fw = _current_firewall.get()@@ -440,7 +458,7 @@ async def _firewall_loop_create_connection(def install_hooks() -> None:"""Install process-wide socket and event loop interception hooks."""- global _hooks_installed+ global _hooks_installed, _orig_requests_get_environ_proxies, _orig_httpx_get_environment_proxiesif _hooks_installed:return@@ -453,13 +471,30 @@ def install_hooks() -> None:_firewall_loop_create_connection)urllib.request.getproxies = _firewall_getproxies # type: ignore[assignment]++ try:+ import requests.utils+ if _orig_requests_get_environ_proxies is None:+ _orig_requests_get_environ_proxies = requests.utils.get_environ_proxies+ requests.utils.get_environ_proxies = _firewall_requests_get_environ_proxies # type: ignore[assignment]+ except (ImportError, AttributeError):+ pass++ try:+ import httpx._utils+ if _orig_httpx_get_environment_proxies is None:+ _orig_httpx_get_environment_proxies = httpx._utils.get_environment_proxies+ httpx._utils.get_environment_proxies = _firewall_httpx_get_environment_proxies # type: ignore[assignment]+ except (ImportError, AttributeError):+ pass+_hooks_installed = Truelogger.debug("scope_firewall_hooks_installed")def uninstall_hooks() -> None:"""Restore original socket and event loop functions."""- global _hooks_installed+ global _hooks_installed, _orig_requests_get_environ_proxies, _orig_httpx_get_environment_proxiesif not _hooks_installed:return@@ -472,12 +507,67 @@ def uninstall_hooks() -> None:_orig_loop_create_connection)urllib.request.getproxies = _orig_urllib_getproxies # type: ignore[assignment]++ if _orig_requests_get_environ_proxies is not None:+ try:+ import requests.utils+ requests.utils.get_environ_proxies = _orig_requests_get_environ_proxies # type: ignore[assignment]+ except (ImportError, AttributeError):+ pass++ if _orig_httpx_get_environment_proxies is not None:+ try:+ import httpx._utils+ httpx._utils.get_environment_proxies = _orig_httpx_get_environment_proxies # type: ignore[assignment]+ except (ImportError, AttributeError):+ pass+_hooks_installed = Falselogger.debug("scope_firewall_hooks_uninstalled")# ── OS / Kernel Network Firewall Controller ───────────────────────────────────+def compute_out_of_scope_cidrs(+ scope_cidrs: list[str],+ allow_loopback: bool = True,+) -> list[str]:+ """Calculate the mathematical complement of in-scope CIDRs in IPv4 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.+ """+ all_v4 = [ipaddress.ip_network("0.0.0.0/0")]+ excluded_nets: list[ipaddress.IPv4Network] = []+ if allow_loopback:+ excluded_nets.append(ipaddress.ip_network("127.0.0.0/8"))+ for c in scope_cidrs:+ c_str = str(c).strip()+ if not c_str:+ continue+ try:+ net = ipaddress.ip_network(c_str, strict=False)+ if isinstance(net, ipaddress.IPv4Network):+ excluded_nets.append(net)+ except ValueError:+ pass++ current_blocks = all_v4+ for ex in excluded_nets:+ next_blocks: list[ipaddress.IPv4Network] = []+ for blk in current_blocks:+ if blk.overlaps(ex):+ next_blocks.extend(list(blk.address_exclude(ex)))+ else:+ next_blocks.append(blk)+ current_blocks = next_blocks++ collapsed = list(ipaddress.collapse_addresses(current_blocks))+ return [str(b) for b in collapsed]++class OSFirewallController:"""Controls OS-level / Kernel network packet filtering boundaries.@@ -488,13 +578,22 @@ class OSFirewallController:Operates in dual mode:1. Elevated Mode (Admin/Root): Applies native OS firewall rules restrictingoutbound 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 Interceptorwhile recording audit logs, ensuring zero runtime crashes or elevation side-effects.- Includes fail-safe automatic rule rollback on context exit and process shutdown (`atexit`).+ 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."""_active_rules: set[str] = set()+ _rule_cleanups: dict[str, list[list[str]]] = {}_lock = threading.Lock()@classmethod@@ -548,6 +647,11 @@ class OSFirewallController:return []if not cls.is_elevated():+ if os.environ.get("ARES_REQUIRE_OS_FIREWALL") == "1":+ raise ScopeFirewallBlockError(+ "OS-level firewall enforcement required (ARES_REQUIRE_OS_FIREWALL=1), "+ "but current process lacks administrative/root privileges."+ )logger.info("os_firewall_unprivileged_fallback",platform=sys.platform,@@ -558,93 +662,154 @@ class OSFirewallController:cidrs_str = ",".join(scope_cidrs)rule_token = secrets.token_hex(6)rule_name = f"ARES_SCOPE_WALL_{rule_token}"- applied: list[str] = []prog = program or sys.executable+ sub_rules: list[tuple[list[str], list[str]]] = []- try:- if sys.platform == "win32":- cmd = [+ if sys.platform == "win32":+ out_of_scope = compute_out_of_scope_cidrs(scope_cidrs, allow_loopback=True)+ if not out_of_scope:+ return []++ 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}"+ apply_cmd = ["netsh", "advfirewall", "firewall", "add", "rule",- f"name={rule_name}",+ f"name={sub_name}","dir=out",- "action=allow",+ "action=block",f"program={prog}",- f"remoteip={cidrs_str}",+ f"remoteip={','.join(batch)}","enable=yes",]- res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)- if res.returncode == 0:- applied.append(rule_name)- with cls._lock:- cls._active_rules.add(rule_name)- logger.info("os_firewall_rule_applied", rule=rule_name, cidrs=scope_cidrs, platform="windows")- else:- logger.warning("os_firewall_rule_failed", rule=rule_name, error=res.stderr.strip() or res.stdout.strip())-- elif sys.platform.startswith("linux"):- pid = str(os.getpid())- # Rule 1: Allow loopback for this process- cmd_lo = [- "iptables", "-I", "OUTPUT", "1",- "-m", "owner", "--pid-owner", pid,- "-o", "lo",- "-j", "ACCEPT",- "-m", "comment", "--comment", rule_name,- ]- # Rule 2: Allow authorized scope CIDRs for this process- cmd_scope = [- "iptables", "-I", "OUTPUT", "2",- "-m", "owner", "--pid-owner", pid,- "-d", cidrs_str,- "-j", "ACCEPT",- "-m", "comment", "--comment", rule_name,+ cleanup_cmd = [+ "netsh", "advfirewall", "firewall", "delete", "rule",+ f"name={sub_name}",]- # Rule 3: DROP all other outbound egress from this process (strict allowlist)- cmd_drop = [- "iptables", "-I", "OUTPUT", "3",- "-m", "owner", "--pid-owner", pid,- "-j", "DROP",- "-m", "comment", "--comment", rule_name,- ]- subprocess.run(cmd_lo, capture_output=True, text=True, timeout=5)- res = subprocess.run(cmd_scope, capture_output=True, text=True, timeout=5)- subprocess.run(cmd_drop, capture_output=True, text=True, timeout=5)+ sub_rules.append((apply_cmd, cleanup_cmd))++ 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",+ ]+ 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",+ ]+ sub_rules.append((drop_apply, drop_cleanup))++ applied_cleanups: list[list[str]] = []+ all_succeeded = True++ for apply_cmd, cleanup_cmd in sub_rules:+ try:+ res = subprocess.run(apply_cmd, capture_output=True, text=True, timeout=5)if res.returncode == 0:- applied.append(rule_name)- with cls._lock:- cls._active_rules.add(rule_name)- logger.info("os_firewall_rule_applied", rule=rule_name, cidrs=scope_cidrs, platform="linux", mode="strict_pid_allowlist")+ applied_cleanups.append(cleanup_cmd)else:- logger.warning("os_firewall_rule_failed", rule=rule_name, error=res.stderr.strip())+ all_succeeded = False+ logger.warning("os_firewall_subrule_failed", rule=rule_name, cmd=apply_cmd, error=res.stderr.strip() or res.stdout.strip())+ break+ except Exception as exc:+ all_succeeded = False+ logger.warning("os_firewall_apply_exception", rule=rule_name, error=str(exc))+ break- except Exception as exc:- logger.warning("os_firewall_apply_exception", error=str(exc))+ if not all_succeeded:+ for cleanup_cmd in reversed(applied_cleanups):+ try:+ subprocess.run(cleanup_cmd, capture_output=True, text=True, timeout=5)+ except Exception:+ pass+ if os.environ.get("ARES_REQUIRE_OS_FIREWALL") == "1":+ raise ScopeFirewallBlockError(+ f"[ScopeFirewall] Transactional OS firewall configuration failed for {rule_name}."+ )+ return []- return applied+ with cls._lock:+ cls._active_rules.add(rule_name)+ cls._rule_cleanups[rule_name] = applied_cleanups++ logger.info(+ "os_firewall_transaction_committed",+ rule=rule_name,+ sub_rules_count=len(applied_cleanups),+ platform=sys.platform,+ )+ return [rule_name]@classmethoddef remove_rules(cls, rule_ids: list[str]) -> int:- """Remove previously created OS firewall rules."""+ """Remove previously created OS firewall rules using exact recorded cleanups."""removed = 0for rule_name in rule_ids:- try:- if sys.platform == "win32":- cmd = ["netsh", "advfirewall", "firewall", "delete", "rule", f"name={rule_name}"]- res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)- if res.returncode == 0:- removed += 1- elif sys.platform.startswith("linux"):- cmd = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", rule_name, "-j", "ACCEPT"]- res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)- if res.returncode == 0:- removed += 1- cmd_drop = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", rule_name, "-j", "DROP"]- subprocess.run(cmd_drop, capture_output=True, text=True, timeout=5)- except Exception as exc:- logger.warning("os_firewall_remove_failed", rule=rule_name, error=str(exc))- finally:- with cls._lock:- cls._active_rules.discard(rule_name)+ with cls._lock:+ cleanups = cls._rule_cleanups.pop(rule_name, None)+ cls._active_rules.discard(rule_name)++ 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+ except Exception as exc:+ logger.warning("os_firewall_cleanup_failed", rule=rule_name, cmd=cleanup_cmd, error=str(exc))+ else:+ try:+ if sys.platform == "win32":+ cmd = ["netsh", "advfirewall", "firewall", "delete", "rule", f"name={rule_name}"]+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)+ if res.returncode == 0:+ removed += 1+ elif sys.platform.startswith("linux"):+ for suffix in ("_lo", "_scope", "_drop", ""):+ comment = f"{rule_name}{suffix}"+ for action in ("ACCEPT", "DROP"):+ cmd = ["iptables", "-D", "OUTPUT", "-m", "comment", "--comment", comment, "-j", action]+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=5)+ if res.returncode == 0:+ removed += 1+ except Exception as exc:+ logger.warning("os_firewall_remove_fallback_failed", rule=rule_name, error=str(exc))if removed > 0:logger.info("os_firewall_rules_removed", count=removed)@@ -684,7 +849,9 @@ _saved_global_proxies: dict[str, str] = {}def _enter_proxy_neutralization() -> None:- """Thread-safe, re-entrant proxy neutralization across concurrent/nested tasks."""+ """Thread-safe proxy neutralization for optional process-global mode."""+ if os.environ.get("ARES_GLOBAL_PROXY_NEUTRALIZE") != "1":+ returnglobal _proxy_guard_countwith _proxy_lock:if _proxy_guard_count == 0:@@ -696,6 +863,8 @@ def _enter_proxy_neutralization() -> None:def _exit_proxy_neutralization() -> None:"""Restore proxy environment variables once all active firewall contexts exit."""+ if os.environ.get("ARES_GLOBAL_PROXY_NEUTRALIZE") != "1":+ returnglobal _proxy_guard_countwith _proxy_lock:_proxy_guard_count = max(0, _proxy_guard_count - 1)diff --git a/ares/marketplace/installer.py b/ares/marketplace/installer.pyindex 218aa3a..4053854 100644--- a/ares/marketplace/installer.py+++ b/ares/marketplace/installer.py@@ -637,13 +637,25 @@ class ModuleInstaller:if not (dest_dir == plugins_base or dest_dir.is_relative_to(plugins_base)):raise ValueError(f"Path traversal detected in module destination: {manifest.id!r}")+ if dest_dir.is_symlink():+ raise ValueError(f"Symlink detected in destination directory: {dest_dir}")dest_dir.mkdir(parents=True, exist_ok=True)safe_filename = Path(file_path.name).namedest_file = (dest_dir / safe_filename).resolve()if not (dest_file == dest_dir or dest_file.is_relative_to(dest_dir)):raise ValueError(f"Path traversal detected in module filename: {file_path.name!r}")+ if dest_file.is_symlink():+ raise ValueError(f"Symlink detected at target file destination: {dest_file}")- shutil.copy2(file_path, dest_file)+ # Atomic installation via unique temporary file in the same directory+ import secrets+ tmp_dest = dest_dir / f".tmp_{secrets.token_hex(4)}_{safe_filename}"+ shutil.copy2(file_path, tmp_dest)+ try:+ _os.chmod(tmp_dest, 0o600)+ except OSError:+ pass+ _os.replace(tmp_dest, dest_file)return self._finalize_install(dest_dir, manifest, force)def _finalize_install(self, plugin_dir: Path, manifest: ModuleManifest, force: bool) -> ModuleManifest:diff --git a/tests/unit/test_scope_firewall.py b/tests/unit/test_scope_firewall.pyindex 8f6ad32..3abab83 100644--- a/tests/unit/test_scope_firewall.py+++ b/tests/unit/test_scope_firewall.py@@ -318,6 +318,7 @@ class TestOSFirewallController:assert status["active_rules_count"] == 0def test_windows_elevated_rule_application_and_cleanup(self, sample_campaign: Campaign):+ OSFirewallController._active_rules.clear()with (patch.object(OSFirewallController, "is_elevated", return_value=True),patch("sys.platform", "win32"),@@ -327,20 +328,20 @@ class TestOSFirewallController:rules = OSFirewallController.apply_rules(sample_campaign, ["10.0.0.0/24", "192.168.1.0/24"])assert len(rules) == 1assert rules[0].startswith("ARES_SCOPE_WALL_")- assert mock_run.call_count == 1- cmd = mock_run.call_args[0][0]- assert cmd[0] == "netsh"- assert "advfirewall" in cmd- assert "remoteip=10.0.0.0/24,192.168.1.0/24" in cmd+ assert mock_run.call_count >= 1+ all_cmds = [call[0][0] for call in mock_run.call_args_list]+ assert any(cmd[0] == "netsh" and "action=block" in cmd for cmd in all_cmds)# Verify cleanup+ mock_run.reset_mock()removed = OSFirewallController.remove_rules(rules)- assert removed == 1- del_cmd = mock_run.call_args[0][0]- assert del_cmd[0] == "netsh"- assert f"name={rules[0]}" in del_cmd+ assert removed >= 1+ del_cmds = [call[0][0] for call in mock_run.call_args_list]+ assert any(cmd[0] == "netsh" and "delete" in cmd for cmd in del_cmds)+ assert len(OSFirewallController._active_rules) == 0def test_linux_elevated_rule_application_and_cleanup(self, sample_campaign: Campaign):+ OSFirewallController._active_rules.clear()with (patch.object(OSFirewallController, "is_elevated", return_value=True),patch("sys.platform", "linux"),@@ -356,7 +357,8 @@ class TestOSFirewallController:assert any(cmd[0] == "iptables" and "-j" in cmd and "DROP" in cmd for cmd in all_cmds)removed = OSFirewallController.remove_rules(rules)- assert removed == 1+ assert removed == 3+ assert len(OSFirewallController._active_rules) == 0def test_scope_firewall_guard_wires_os_firewall(self, sample_campaign: Campaign):with (@@ -392,15 +394,26 @@ class TestOSFirewallController:assert fw.is_allowed_address("::ffff:8.8.8.8") is Falseassert fw.is_allowed_address(("::ffff:8.8.8.8", 53)) is False- def test_proxy_environment_variables_neutralized_during_guard(self, sample_campaign: Campaign):+ def test_proxy_environment_variables_neutralized_during_guard(self, sample_campaign: Campaign, monkeypatch: pytest.MonkeyPatch):import osimport urllib.request+ from ares.core.scope_firewall import _firewall_getproxiesos.environ["HTTP_PROXY"] = "http://127.0.0.1:8080"os.environ["HTTPS_PROXY"] = "http://127.0.0.1:8443"try:+ # 1. Task-local isolation mode (default: os.environ is NOT mutated to avoid clobbering concurrent tasks)+ with scope_firewall_sync_guard(sample_campaign) as fw:+ assert fw is not None+ # urllib proxy getter hooked to return {} when inside guard+ assert _firewall_getproxies() == {}+ assert urllib.request.getproxies() == {}+ # Unrelated task looking at os.environ directly is not clobbered+ assert os.environ.get("HTTP_PROXY") == "http://127.0.0.1:8080"++ # 2. Process-global mode (opt-in via ARES_GLOBAL_PROXY_NEUTRALIZE=1)+ monkeypatch.setenv("ARES_GLOBAL_PROXY_NEUTRALIZE", "1")with scope_firewall_sync_guard(sample_campaign) as fw:assert fw is not None- # Proxies must be stripped while guard is activeassert "HTTP_PROXY" not in os.environassert "HTTPS_PROXY" not in os.environassert urllib.request.getproxies() == {}@@ -410,10 +423,9 @@ class TestOSFirewallController:assert inner_fw is not Noneassert "HTTP_PROXY" not in os.environ- # Exiting nested guard must still maintain proxy neutralization while outer guard is aliveassert "HTTP_PROXY" not in os.environ- # Proxies must be safely restored only upon final exit+ # Restored upon exit of global modeassert os.environ.get("HTTP_PROXY") == "http://127.0.0.1:8080"assert os.environ.get("HTTPS_PROXY") == "http://127.0.0.1:8443"finally:@@ -428,10 +440,66 @@ class TestOSFirewallController:raise socket.gaierror(-2, "Name or service not known")monkeypatch.setattr(socket, "getaddrinfo", mock_getaddrinfo)- # Attempt to resolve an unresolvable hostnameallowed, pinned = fw.resolve_and_pin_address("unresolvable.in-targets.local")assert allowed is False+ def test_compute_out_of_scope_cidrs(self):+ """Mathematical complement must cover all of IPv4 except scope and loopback."""+ import ipaddress+ from ares.core.scope_firewall import compute_out_of_scope_cidrs++ scope = ["10.0.0.0/24"]+ comp = compute_out_of_scope_cidrs(scope, allow_loopback=True)+ assert len(comp) > 0++ # In-scope must NOT be in complement+ in_scope = ipaddress.ip_address("10.0.0.45")+ assert not any(in_scope in ipaddress.ip_network(c) for c in comp)++ # Loopback must NOT be in complement+ loopback = ipaddress.ip_address("127.0.0.1")+ assert not any(loopback in ipaddress.ip_network(c) for c in comp)++ # Out-of-scope MUST be in complement+ out_scope = ipaddress.ip_address("8.8.8.8")+ assert any(out_scope in ipaddress.ip_network(c) for c in comp)++ def test_os_firewall_windows_strict_block_complement(self, monkeypatch: pytest.MonkeyPatch):+ """Windows OS firewall must apply explicit block rules for complement CIDRs."""+ from ares.core.scope_firewall import OSFirewallController+ import subprocess+ import sys++ commands_executed: list[list[str]] = []++ def mock_run(cmd, *args, **kwargs):+ commands_executed.append(list(cmd))+ class MockRes:+ returncode = 0+ stdout = ""+ stderr = ""+ return MockRes()++ monkeypatch.setattr(subprocess, "run", mock_run)+ monkeypatch.setattr(OSFirewallController, "is_elevated", lambda: True)+ monkeypatch.setattr(sys, "platform", "win32")++ rules = OSFirewallController.apply_rules(None, ["10.0.0.0/24"], program="python.exe")+ assert len(rules) == 1+ rule_name = rules[0]++ # Verify that an explicit action=block rule was created for python.exe+ assert any(+ "netsh" in cmd and "action=block" in cmd and "program=python.exe" in cmd+ for cmd in commands_executed+ )++ # Verify cleanup+ commands_executed.clear()+ removed = OSFirewallController.remove_rules([rule_name])+ assert removed >= 1+ assert any("delete" in cmd and "rule" in cmd for cmd in commands_executed)+def test_os_firewall_linux_strict_allowlist_commands(self, monkeypatch: pytest.MonkeyPatch):"""Linux OS firewall must apply lo ACCEPT, scope ACCEPT, and process DROP rules."""from ares.core.scope_firewall import OSFirewallController@@ -456,25 +524,68 @@ class TestOSFirewallController:assert len(rules) == 1rule_name = rules[0]- # Verify that all 3 rules were applied:- # Rule 1: loopback ACCEPT+ # Verify that all 3 rules were applied with distinct comments:assert any(- "-o" in cmd and "lo" in cmd and "-j" in cmd and "ACCEPT" in cmd+ "-o" in cmd and "lo" in cmd and "-j" in cmd and "ACCEPT" in cmd and f"{rule_name}_lo" in cmdfor cmd in commands_executed)- # Rule 2: scope ACCEPTassert any(- "-d" in cmd and "10.0.0.0/24" in cmd and "-j" in cmd and "ACCEPT" in cmd+ "-d" in cmd and "10.0.0.0/24" in cmd and "-j" in cmd and "ACCEPT" in cmd and f"{rule_name}_scope" in cmdfor cmd in commands_executed)- # Rule 3: DROP other outbound packets (strict allowlist)assert any(- "-j" in cmd and "DROP" in cmd+ "-j" in cmd and "DROP" in cmd and f"{rule_name}_drop" in cmdfor cmd in commands_executed)- # Now test remove_rules+ # Verify exact cleanupcommands_executed.clear()removed = OSFirewallController.remove_rules([rule_name])- assert any("iptables" in cmd and "-D" in cmd for cmd in commands_executed)+ assert removed == 3+ assert len([c for c in commands_executed if "iptables" in c and "-D" in c]) == 3++ def test_os_firewall_transactional_rollback_on_failure(self, monkeypatch: pytest.MonkeyPatch):+ """If any sub-rule fails during application, all previously applied sub-rules must roll back."""+ from ares.core.scope_firewall import OSFirewallController+ import subprocess+ import sys++ applied_commands: list[list[str]] = []+ cleanup_commands: list[list[str]] = []++ def mock_run(cmd, *args, **kwargs):+ cmd_list = list(cmd)+ # Fail on the 3rd rule (DROP rule)+ if "-j" in cmd_list and "DROP" in cmd_list and "-I" in cmd_list:+ class FailRes:+ returncode = 1+ stdout = ""+ stderr = "iptables: Permission denied on DROP"+ return FailRes()++ if "-D" in cmd_list:+ cleanup_commands.append(cmd_list)+ else:+ applied_commands.append(cmd_list)++ class OkRes:+ returncode = 0+ stdout = ""+ stderr = ""+ return OkRes()++ monkeypatch.setattr(subprocess, "run", mock_run)+ monkeypatch.setattr(OSFirewallController, "is_elevated", lambda: True)+ monkeypatch.setattr(sys, "platform", "linux")++ # Before apply: 0 rules+ assert len(OSFirewallController._active_rules) == 0++ rules = OSFirewallController.apply_rules(None, ["10.0.0.0/24"])+ # Failed transaction must return empty list+ assert rules == []+ # Active rules must remain 0+ assert len(OSFirewallController._active_rules) == 0+ # Previously applied sub-rules (lo and scope) must have been rolled back+ assert len(cleanup_commands) == 2