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(accuracy): container host_network weak heuristic replacement (MOD-039)
Mafifrizi3344c99a1c6b
diff --git a/ares/modules/linux/container.py b/ares/modules/linux/container.pyindex beb802f..3b8fa61 100644--- a/ares/modules/linux/container.py+++ b/ares/modules/linux/container.py@@ -324,25 +324,74 @@ class ContainerEscapeModule(BaseModule[ContainerEscapeParams, ModuleResult]):return {"k8s_detected": True, "error": str(e)}async def _check_host_network(self) -> dict[str, Any]:- """Detect --net=host which exposes all host network interfaces."""+ """+ Detect --net=host which exposes all host network interfaces.+ Uses network namespace inode comparison and host network interface detection+ instead of naive open socket count heuristics.+ """try:- with open("/proc/net/tcp") as f:- lines = f.readlines()- # If we see ports like 22, 80, 443 listening - likely host network- host_network = len(lines) > 50 # Heuristic: many open ports = host net- if host_network:+ is_host_net = False+ verified = False+ evidence: dict[str, Any] = {}++ # Check 1: Inode comparison between PID 1 and self network namespace+ try:+ self_net = os.stat("/proc/self/ns/net").st_ino+ init_net = os.stat("/proc/1/ns/net").st_ino+ if self_net == init_net:+ is_host_net = True+ verified = True+ evidence["net_ns_inode_match"] = True+ evidence["net_ns_inode"] = self_net+ except (OSError, PermissionError):+ pass++ # Check 2: Inspect network interfaces via /proc/net/dev or /sys/class/net+ interfaces: list[str] = []+ try:+ if os.path.exists("/proc/net/dev"):+ with open("/proc/net/dev") as f:+ for line in f:+ if ":" in line:+ iface = line.split(":")[0].strip()+ interfaces.append(iface)+ elif os.path.exists("/sys/class/net"):+ interfaces = os.listdir("/sys/class/net")+ except OSError:+ pass++ evidence["interfaces"] = interfaces++ # Standard Docker/K8s container netns typically only has 'lo' and 'eth0'+ # Host netns typically exposes 'docker0', 'cni0', physical NICs ('ens*', 'enp*', 'eno*', 'wlan*')+ host_nic_prefixes = ("ens", "enp", "eno", "eth1", "wlan", "docker0", "cni0", "flannel", "virbr", "bond")+ host_ifaces_found = [i for i in interfaces if any(i.startswith(p) for p in host_nic_prefixes)]+ if host_ifaces_found:+ is_host_net = True+ evidence["host_interfaces_detected"] = host_ifaces_found++ if is_host_net:+ conf = 0.95 if verified else 0.45+ title = (+ "Container Using Host Network Namespace (--net=host)"+ if verified else+ "Potential Container Host Network Namespace Detected"+ )self.finding(- title="Container May Be Using Host Network Namespace",+ title=title,description=(- "Container appears to share the host network namespace (--net=host). "- "This allows sniffing host traffic and binding to privileged ports."+ "Container shares or may share the host network namespace (--net=host). "+ "This allows sniffing host traffic, binding to privileged ports, and reaching host-local services."),- severity=Severity.HIGH,+ severity=Severity.HIGH if verified else Severity.LOW,+ confidence=conf,mitre_technique="T1611",mitre_tactic="Privilege Escalation",- evidence={"open_ports_count": len(lines)},- remediation="Remove --net=host. Use CNI plugins for network isolation.",+ evidence=evidence,+ remediation="Remove --net=host. Use CNI plugins or user-defined bridge networks for network isolation.",)- return {"host_network_suspected": host_network}- except OSError:- return {"error": "could not read /proc/net/tcp"}+ return {"host_network_detected": True, "verified": verified, "evidence": evidence}++ return {"host_network_detected": False, "interfaces": interfaces}+ except Exception as e:+ return {"error": str(e)}diff --git a/tests/unit/modules/test_container_host_network_mod039.py b/tests/unit/modules/test_container_host_network_mod039.pynew file mode 100644index 0000000..2f7c794--- /dev/null+++ b/tests/unit/modules/test_container_host_network_mod039.py@@ -0,0 +1,100 @@+"""+Tests for MOD-039: Container host_network weak heuristic replacement.+Verifies:+1. Container with standard interfaces (lo, eth0) does not produce false positive finding.+2. Verified host network via netns inode comparison produces high confidence finding (0.95).+3. Host interface detection (ens, docker0) produces potential finding with confidence < 0.5.+"""++from unittest.mock import MagicMock, mock_open, patch+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.noise import NoiseController+from ares.modules.linux.container import ContainerEscapeModule+++def _make_module():+ settings = AresSettings(+ ares_secret_key="test-secret-key-32chars-minimum!!",+ ares_encryption_key="test-encryption-key-32chars-min!!",+ )+ campaign = Campaign(+ name="Container-MOD039-Test",+ operator="test_operator",+ scope=[ScopeEntry(cidr="10.0.0.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return ContainerEscapeModule(settings=settings, campaign=campaign, noise=noise)+++async def test_standard_container_no_false_positive():+ """Container with standard lo and eth0 does not trigger host network finding."""+ mod = _make_module()++ mock_dev_data = (+ "Inter-| Receive | Transmit\n"+ " face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n"+ " lo: 12345678 1000 0 0 0 0 0 0 12345678 1000 0 0 0 0 0 0\n"+ " eth0: 98765432 5000 0 0 0 0 0 0 98765432 5000 0 0 0 0 0 0\n"+ )++ with patch("os.stat", side_effect=OSError("Permission denied")), \+ patch("os.path.exists", return_value=True), \+ patch("builtins.open", mock_open(read_data=mock_dev_data)):++ res = await mod._check_host_network()++ assert res["host_network_detected"] is False+ assert len(mod._findings) == 0+++async def test_verified_host_network_netns_inode_match():+ """Netns inode match produces verified host network finding with 0.95 confidence."""+ mod = _make_module()++ mock_stat = MagicMock()+ mock_stat.st_ino = 4026531992++ with patch("os.stat", return_value=mock_stat), \+ patch("os.path.exists", return_value=False):++ res = await mod._check_host_network()++ assert res["host_network_detected"] is True+ assert res["verified"] is True+ assert len(mod._findings) == 1+ finding = mod._findings[0]+ assert "Host Network Namespace" in finding.title+ assert finding.confidence == 0.95+++async def test_host_interfaces_detected_calibrated_confidence():+ """Host interfaces (ens33, docker0) detected produces potential finding with confidence < 0.5."""+ mod = _make_module()++ mock_dev_data = (+ "Inter-| Receive | Transmit\n"+ " face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n"+ " lo: 1000 10 0 0 0 0 0 0 1000 10 0 0 0 0 0 0\n"+ " ens33: 5000 50 0 0 0 0 0 0 5000 50 0 0 0 0 0 0\n"+ "docker0: 2000 20 0 0 0 0 0 0 2000 20 0 0 0 0 0 0\n"+ )++ with patch("os.stat", side_effect=OSError("Permission denied")), \+ patch("os.path.exists", return_value=True), \+ patch("builtins.open", mock_open(read_data=mock_dev_data)):++ res = await mod._check_host_network()++ assert res["host_network_detected"] is True+ assert res["verified"] is False+ assert len(mod._findings) == 1+ finding = mod._findings[0]+ assert "Potential" in finding.title+ assert finding.confidence < 0.5