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 strict-mode boundary integrity, non-silent tier requests & RFC 001 docs synchronization

Mafifrizi5271dd14614b
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a87776d..cdd202d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -11,7 +11,7 @@ to get started - from dev environment setup to submitting a pull request.
2. [Development Environment](#development-environment)
3. [Branching Strategy](#branching-strategy)
4. [Commit Conventions](#commit-conventions)
-5. [Priority Research Track: Linux Active Directory](#priority-research-track-linux-active-directory)
+5. [Research Tracks](#research-tracks)
6. [Writing a New Module](#writing-a-new-module)
7. [Testing Requirements](#testing-requirements)
8. [Pull Request Process](#pull-request-process)
@@ -128,19 +128,26 @@ git commit -m "security: narrow DataEncryptor exception catch-all"
---
-## Priority Research Track: Linux Active Directory
+## Research Tracks
-We are actively calling for offensive security researchers and contributors to build cross-platform Active Directory post-exploitation modules targeting Linux domain members (SSSD, Winbind, Kerberos keyrings, and ccache ticket extraction).
+ARES uses formal RFCs to design and coordinate multi-module research efforts.
-See the full technical specification and module contracts:
+### RFC 001: Linux Active Directory Tradecraft ✅ Completed
+
+All 5 modules from the Linux AD post-exploitation research track are fully
+implemented and production-ready in ARES v6.0:
+
+- `linux.sssd_harvest` — SSSD LDB database extraction
+- `linux.ccache_hunt` — Kerberos ticket cache hunting (file + Kernel Keyring)
+- `linux.keytab_abuse` — Machine keytab parsing & Silver Ticket generation
+- `linux.samba_secrets` — Samba/Winbind machine password extraction
+- `credential.ticket_converter` — Bi-directional ccache ↔ kirbi conversion
+
+See the full technical specification:
👉 **[RFC 001: Linux Active Directory Tradecraft](docs/research/linux-active-directory-tradecraft.md)**
-Prioritized modules open for PRs:
-- `linux.sssd_harvest`: SSSD LDB database extraction (`/var/lib/sss/db/`)
-- `linux.ccache_hunt`: Kerberos ticket cache hunter (`/tmp/krb5cc_*`, Kernel Keyring)
-- `linux.keytab_abuse`: Computer account keytab harvesting & Silver Ticket generation
-- `linux.samba_secrets`: Samba/Winbind machine password extraction (`secrets.tdb`)
-- `credential.ticket_converter`: In-memory ccache $\leftrightarrow$ kirbi bidirectional converter
+**Want to propose a new research track?** Open a
+[Module Development discussion](https://github.com/Mafifrizi/ARES/discussions/categories/module-development).
---
diff --git a/ares/core/sandbox.py b/ares/core/sandbox.py
index e7f4bee..a05513a 100644
--- a/ares/core/sandbox.py
+++ b/ares/core/sandbox.py
@@ -103,10 +103,12 @@ class SandboxPolicy:
docker_network: str = "bridge" # container network mode when allow_network=True
# Strict mode & tier integrity controls
- strict_mode: bool = True # enforce fail-closed security invariants across all tiers
- allow_tier_downgrade: bool = False # reject silent fallback from DOCKER to SUBPROCESS when Docker is unavailable
- allow_unconfined_docker_binaries: bool = False # in strict mode, reject DOCKER allow_network=True unless explicitly allowed
- sandbox_uid: int | None = None # dedicated sandbox UID for Linux parent firewall & child privilege drop
+ strict_mode: bool = True # enforce fail-closed security invariants across all tiers
+ allow_tier_downgrade: bool = False # reject silent fallback from DOCKER to SUBPROCESS when Docker is unavailable
+ allow_unconfined_docker_binaries: bool = False # in strict mode, reject DOCKER allow_network=True unless explicitly allowed
+ allow_unconfined_subprocess_binaries: bool = False # in strict mode, reject SUBPROCESS allow_network=True without OS boundary
+ sandbox_uid: int | None = None # dedicated sandbox UID for Linux parent firewall & child privilege drop
+ sandbox_gid: int | None = None # primary GID for sandbox identity (defaults to primary GID of sandbox_uid)
# Modules trusted to bypass sandboxing
trusted_prefixes: list[str] = field(default_factory=lambda: ["ares.core", "ares.db"])
@@ -132,6 +134,22 @@ class SandboxResult:
downgraded: bool = False
downgrade_reason: str = ""
guarantees_lost: list[str] = field(default_factory=list)
+ security_mode: str = "strict"
+ active_boundary: str = ""
+
+
+@dataclass
+class PolicyDecision:
+ """Canonical security policy decision outcome."""
+ allowed: bool
+ effective_tier: IsolationTier
+ requested_tier: IsolationTier
+ downgraded: bool = False
+ downgrade_reason: str = ""
+ guarantees_lost: list[str] = field(default_factory=list)
+ active_boundary: str = ""
+ security_mode: str = "strict"
+ rejection_reason: str = ""
class SandboxRunner:
@@ -143,6 +161,161 @@ class SandboxRunner:
def __init__(self, policy: SandboxPolicy | None = None) -> None:
self.policy = policy or SandboxPolicy()
+ def evaluate_policy(
+ self,
+ module_id: str,
+ tier: IsolationTier | None = None,
+ has_external_binary: bool = False,
+ docker_available: bool = True,
+ has_os_boundary: bool | None = None,
+ ) -> PolicyDecision:
+ """
+ Evaluate canonical security policy decision matrix according to:
+ requested_tier, network policy, external binary capability, OS boundary, and strict mode.
+ """
+ requested = tier or self.policy.tier
+ strict = self.policy.strict_mode
+ sec_mode = "strict" if strict else "compat"
+ is_trusted = self.is_trusted_module(module_id)
+
+ # 1. Trusted core modules
+ if is_trusted:
+ if requested == IsolationTier.NONE:
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=IsolationTier.NONE,
+ requested_tier=requested,
+ active_boundary="transport_hook",
+ security_mode=sec_mode,
+ )
+ elif strict and not self.policy.allow_tier_downgrade:
+ effective = requested
+ else:
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=IsolationTier.NONE,
+ requested_tier=requested,
+ downgraded=True,
+ downgrade_reason="trusted_core_module_runs_in_process",
+ guarantees_lost=[
+ "process_isolation",
+ "filesystem_isolation",
+ "network_namespace_isolation",
+ ],
+ active_boundary="transport_hook",
+ security_mode=sec_mode,
+ )
+ else:
+ effective = requested
+
+ # 2. DOCKER tier
+ if effective == IsolationTier.DOCKER:
+ docker_downgraded = False
+ docker_downgrade_reason = ""
+ docker_guarantees_lost: list[str] = []
+ if not docker_available:
+ if strict and not self.policy.allow_tier_downgrade:
+ return PolicyDecision(
+ allowed=False,
+ effective_tier=IsolationTier.DOCKER,
+ requested_tier=requested,
+ security_mode=sec_mode,
+ active_boundary="none",
+ rejection_reason="Security tier downgrade from DOCKER rejected (allow_tier_downgrade=False): Docker unavailable.",
+ )
+ else:
+ effective = IsolationTier.SUBPROCESS
+ docker_downgraded = True
+ docker_downgrade_reason = "docker_unavailable"
+ docker_guarantees_lost = [
+ "read_only_rootfs_mount_namespace",
+ "container_cgroups",
+ "network_namespace_isolation",
+ ]
+
+ if effective == IsolationTier.DOCKER:
+ if not self.policy.allow_network:
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=IsolationTier.DOCKER,
+ requested_tier=requested,
+ active_boundary="container_network_none",
+ security_mode=sec_mode,
+ )
+ else:
+ if has_external_binary and strict and not self.policy.allow_unconfined_docker_binaries:
+ return PolicyDecision(
+ allowed=False,
+ effective_tier=IsolationTier.DOCKER,
+ requested_tier=requested,
+ security_mode=sec_mode,
+ active_boundary="none",
+ rejection_reason="Docker online mode cannot guarantee scope containment for external binaries in strict mode.",
+ )
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=IsolationTier.DOCKER,
+ requested_tier=requested,
+ active_boundary="container_bridge",
+ security_mode=sec_mode,
+ )
+
+ # 3. SUBPROCESS / SECCOMP tiers
+ if effective in (IsolationTier.SUBPROCESS, IsolationTier.SECCOMP):
+ sub_name = "seccomp_bpf+" if effective == IsolationTier.SECCOMP else ""
+ if not self.policy.allow_network:
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=effective,
+ requested_tier=requested,
+ downgraded=locals().get("docker_downgraded", False),
+ downgrade_reason=locals().get("docker_downgrade_reason", ""),
+ guarantees_lost=locals().get("docker_guarantees_lost", []),
+ active_boundary=f"{sub_name}network_namespace",
+ security_mode=sec_mode,
+ )
+ else:
+ if has_os_boundary is None:
+ has_os_boundary = (
+ os.name != "nt"
+ and self.policy.drop_privileges
+ and getattr(os, "geteuid", lambda: -1)() == 0
+ )
+
+ if has_external_binary and strict and not has_os_boundary and not self.policy.allow_unconfined_subprocess_binaries:
+ return PolicyDecision(
+ allowed=False,
+ effective_tier=effective,
+ requested_tier=requested,
+ downgraded=locals().get("docker_downgraded", False),
+ downgrade_reason=locals().get("docker_downgrade_reason", ""),
+ guarantees_lost=locals().get("docker_guarantees_lost", []),
+ security_mode=sec_mode,
+ active_boundary="none",
+ rejection_reason="Subprocess online mode cannot guarantee scope containment for external binaries without an OS-level boundary.",
+ )
+
+ active_b = f"{sub_name}os_firewall_uid" if has_os_boundary else f"{sub_name}transport_hook"
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=effective,
+ requested_tier=requested,
+ downgraded=locals().get("docker_downgraded", False),
+ downgrade_reason=locals().get("docker_downgrade_reason", ""),
+ guarantees_lost=locals().get("docker_guarantees_lost", []),
+ active_boundary=active_b,
+ security_mode=sec_mode,
+ )
+
+ # 4. NONE tier
+ return PolicyDecision(
+ allowed=True,
+ effective_tier=IsolationTier.NONE,
+ requested_tier=requested,
+ active_boundary="transport_hook",
+ security_mode=sec_mode,
+ )
+
async def run_module(
self,
module_id: str,
@@ -156,19 +329,45 @@ class SandboxRunner:
"""
requested_tier = tier or self.policy.tier
effective_tier = requested_tier
+ is_trusted = self.is_trusted_module(module_id)
+ downgraded = False
+ downgrade_reason = ""
+ guarantees_lost: list[str] = []
t0 = time.monotonic()
- # Core modules always run in-process
- if self.is_trusted_module(module_id):
- effective_tier = IsolationTier.NONE
+ # Core modules handling (Finding C: Truthful tier accounting)
+ if is_trusted:
+ if requested_tier == IsolationTier.NONE:
+ effective_tier = IsolationTier.NONE
+ elif self.policy.strict_mode and not self.policy.allow_tier_downgrade:
+ # In strict mode without downgrade permission, honor the requested sandboxed tier
+ effective_tier = requested_tier
+ else:
+ # Permitted downgrade with truthful accounting
+ effective_tier = IsolationTier.NONE
+ downgraded = True
+ downgrade_reason = "trusted_core_module_runs_in_process"
+ guarantees_lost = [
+ "process_isolation",
+ "filesystem_isolation",
+ "network_namespace_isolation",
+ ]
- audit("sandbox_run_start", actor="engine",
- module=module_id, requested_tier=requested_tier.value,
- tier=effective_tier.value, campaign=campaign_id)
+ audit(
+ "sandbox_run_start",
+ actor="engine",
+ module=module_id,
+ requested_tier=requested_tier.value,
+ tier=effective_tier.value,
+ strict_mode=self.policy.strict_mode,
+ campaign=campaign_id,
+ )
try:
if effective_tier == IsolationTier.NONE:
- result = await self._run_inprocess(module_id, params, campaign_id)
+ result = await self._run_inprocess(
+ module_id, params, campaign_id, requested_tier=requested_tier
+ )
elif effective_tier == IsolationTier.DOCKER:
result = await self._run_docker(
module_id, params, campaign_id, requested_tier=requested_tier
@@ -184,6 +383,7 @@ class SandboxRunner:
result = SandboxResult(
module_id=module_id, sandbox_tier=effective_tier,
requested_tier=requested_tier, effective_tier=effective_tier,
+ security_mode="strict" if self.policy.strict_mode else "compat",
success=False, error=str(exc)[:500],
)
@@ -192,21 +392,43 @@ class SandboxRunner:
result.requested_tier = requested_tier
if not getattr(result, "effective_tier", None):
result.effective_tier = effective_tier
+ if downgraded and not result.downgraded:
+ result.downgraded = True
+ result.downgrade_reason = downgrade_reason
+ result.guarantees_lost = guarantees_lost
result.sandbox_tier = result.effective_tier
+ if not getattr(result, "security_mode", None):
+ result.security_mode = "strict" if self.policy.strict_mode else "compat"
- audit("sandbox_run_complete", actor="engine",
- module=module_id, success=result.success,
- requested_tier=result.requested_tier.value,
- effective_tier=result.effective_tier.value,
- downgraded=result.downgraded,
- tier=result.sandbox_tier.value, wall_time_s=result.wall_time_s)
+ audit(
+ "sandbox_run_complete",
+ actor="engine",
+ module=module_id,
+ success=result.success,
+ requested_tier=result.requested_tier.value,
+ effective_tier=result.effective_tier.value,
+ strict_mode=self.policy.strict_mode,
+ network_policy=self.policy.allow_network,
+ filesystem_policy=self.policy.allow_write,
+ privilege_policy=self.policy.drop_privileges,
+ security_boundary=result.active_boundary,
+ downgraded=result.downgraded,
+ downgrade_reason=result.downgrade_reason,
+ guarantees_lost=result.guarantees_lost,
+ tier=result.sandbox_tier.value,
+ wall_time_s=result.wall_time_s,
+ )
return result
# ── Tier implementations ───────────────────────────────────────────────
async def _run_inprocess(
- self, module_id: str, params: dict[str, Any], campaign_id: str
+ self,
+ module_id: str,
+ params: dict[str, Any],
+ campaign_id: str,
+ requested_tier: IsolationTier = IsolationTier.NONE,
) -> SandboxResult:
"""Direct in-process execution. For trusted core modules only."""
from ares.core.config import AresSettings
@@ -260,13 +482,19 @@ class SandboxRunner:
settings = AresSettings()
noise = NoiseController(campaign)
module = module_cls(settings=settings, campaign=campaign, noise=noise)
- async with scope_firewall_guard(campaign=campaign, module_id=module_id):
+ async with scope_firewall_guard(
+ campaign=campaign,
+ module_id=module_id,
+ strict_mode=self.policy.strict_mode,
+ ):
findings, extra = await module.run(**params)
return SandboxResult(
module_id=module_id,
sandbox_tier=IsolationTier.NONE,
- requested_tier=IsolationTier.NONE,
+ requested_tier=requested_tier,
effective_tier=IsolationTier.NONE,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary="transport_hook",
success=True,
findings=[f.to_dict() if hasattr(f, "to_dict") else {} for f in findings],
extra=extra,
@@ -325,6 +553,7 @@ class SandboxRunner:
"scope_cidrs": _scope_cidrs,
"allow_network": self.policy.allow_network,
"allow_write": self.policy.allow_write,
+ "strict_mode": self.policy.strict_mode,
})
wrapper = self._build_wrapper_script(use_seccomp)
@@ -348,6 +577,39 @@ class SandboxRunner:
except Exception:
parent_uid_firewall = 65534
+ # Strict mode online network limitation for subprocess external binaries without OS boundary
+ if self.policy.strict_mode and self.policy.allow_network:
+ if parent_uid_firewall is None and not self.policy.allow_unconfined_subprocess_binaries:
+ return SandboxResult(
+ module_id=module_id,
+ sandbox_tier=sub_tier,
+ requested_tier=requested_tier,
+ effective_tier=sub_tier,
+ security_mode="strict",
+ active_boundary="none",
+ success=False,
+ error=(
+ "Subprocess online mode cannot guarantee scope containment for external binaries without an OS-level boundary. "
+ "In strict mode, run as root with drop_privileges=True (UID-based OS firewall), use allow_network=False, "
+ "or explicitly set allow_unconfined_subprocess_binaries=True."
+ ),
+ )
+
+ if use_seccomp:
+ if not self.policy.allow_network:
+ active_boundary = "seccomp_bpf+network_namespace"
+ elif parent_uid_firewall is not None:
+ active_boundary = "seccomp_bpf+os_firewall_uid"
+ else:
+ active_boundary = "seccomp_bpf+transport_hook"
+ else:
+ if not self.policy.allow_network:
+ active_boundary = "network_namespace"
+ elif parent_uid_firewall is not None:
+ active_boundary = "os_firewall_uid"
+ else:
+ active_boundary = "transport_hook"
+
from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry
from ares.core.scope_firewall import scope_firewall_guard
@@ -363,6 +625,7 @@ class SandboxRunner:
campaign=parent_campaign,
enable_os_firewall=(parent_uid_firewall is not None),
uid_owner=parent_uid_firewall,
+ strict_mode=self.policy.strict_mode,
):
proc = await asyncio.create_subprocess_exec(
sys.executable, script_path,
@@ -386,6 +649,8 @@ class SandboxRunner:
sandbox_tier=sub_tier,
requested_tier=requested_tier,
effective_tier=sub_tier,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary=active_boundary,
success=False,
error=f"Sandbox timeout ({self.policy.timeout_s}s)",
)
@@ -400,6 +665,8 @@ class SandboxRunner:
sandbox_tier = sub_tier,
requested_tier = requested_tier,
effective_tier = sub_tier,
+ security_mode = "strict" if self.policy.strict_mode else "compat",
+ active_boundary = active_boundary,
success = data.get("success", False),
findings = data.get("findings", []),
extra = data.get("extra", {}),
@@ -413,6 +680,8 @@ class SandboxRunner:
sandbox_tier=sub_tier,
requested_tier=requested_tier,
effective_tier=sub_tier,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary=active_boundary,
success=False,
error="Invalid JSON from sandbox",
stdout=stdout[:500],
@@ -438,6 +707,8 @@ class SandboxRunner:
sandbox_tier=IsolationTier.DOCKER,
requested_tier=requested_tier,
effective_tier=IsolationTier.DOCKER,
+ security_mode="strict",
+ active_boundary="none",
success=False,
error=(
"Docker online mode cannot guarantee scope containment for external binaries inside the container. "
@@ -465,6 +736,8 @@ class SandboxRunner:
sandbox_tier=IsolationTier.DOCKER,
requested_tier=requested_tier,
effective_tier=IsolationTier.DOCKER,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary="none",
success=False,
error="Security tier downgrade from DOCKER to SUBPROCESS rejected (allow_tier_downgrade=False): 'docker' package not installed.",
)
@@ -509,6 +782,8 @@ class SandboxRunner:
sandbox_tier=IsolationTier.DOCKER,
requested_tier=requested_tier,
effective_tier=IsolationTier.DOCKER,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary="none",
success=False,
error=f"Security tier downgrade from DOCKER to SUBPROCESS rejected (allow_tier_downgrade=False): Docker daemon unavailable ({exc}).",
)
@@ -560,11 +835,13 @@ class SandboxRunner:
"campaign_id": campaign_id,
"scope_cidrs": _docker_scope,
"allow_network": self.policy.allow_network,
+ "strict_mode": self.policy.strict_mode,
})
image = self.policy.docker_image
network = "none" if not self.policy.allow_network else self.policy.docker_network
read_only = not self.policy.allow_write
mem_limit = f"{self.policy.memory_mb}m"
+ active_boundary = "container_network_none" if not self.policy.allow_network else "container_bridge"
try:
container = client.containers.run(
@@ -589,6 +866,8 @@ class SandboxRunner:
sandbox_tier=IsolationTier.DOCKER,
requested_tier=requested_tier,
effective_tier=IsolationTier.DOCKER,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary=active_boundary,
success=data.get("success", False),
findings=data.get("findings", []),
extra=data.get("extra", {}),
@@ -599,6 +878,8 @@ class SandboxRunner:
sandbox_tier=IsolationTier.DOCKER,
requested_tier=requested_tier,
effective_tier=IsolationTier.DOCKER,
+ security_mode="strict" if self.policy.strict_mode else "compat",
+ active_boundary=active_boundary,
success=False,
error=str(exc)[:300],
)
@@ -617,6 +898,8 @@ class SandboxRunner:
drop_privileges = self.policy.drop_privileges
allow_write = self.policy.allow_write
target_uid = self.policy.sandbox_uid
+ target_gid = self.policy.sandbox_gid
+ strict_mode = self.policy.strict_mode
_parent_pid = os.getpid()
def _limits():
@@ -657,12 +940,23 @@ class SandboxRunner:
try:
if target_uid is not None:
drop_uid = target_uid
- drop_gid = target_uid
+ if target_gid is not None:
+ drop_gid = target_gid
+ else:
+ try:
+ import pwd
+ drop_gid = pwd.getpwuid(target_uid).pw_gid
+ except Exception as e:
+ if strict_mode:
+ raise RuntimeError(
+ f"Cannot resolve primary GID for UID {target_uid} in strict mode; specify sandbox_gid explicitly: {e}"
+ )
+ drop_gid = target_uid
else:
import pwd
nobody = pwd.getpwnam("nobody")
drop_uid = nobody.pw_uid
- drop_gid = nobody.pw_gid
+ drop_gid = target_gid if target_gid is not None else nobody.pw_gid
os.setgroups([])
os.setgid(drop_gid)
os.setuid(drop_uid)
@@ -780,6 +1074,7 @@ class SandboxRunner:
"\n"
" _allow_net = payload.get(\"allow_network\", True)\n"
" _scope_cidrs = payload.get(\"scope_cidrs\", [])\n"
+ " _strict_mode = payload.get(\"strict_mode\", False)\n"
" if not _allow_net:\n"
" campaign = Campaign(\n"
" id=campaign_id or str(uuid.uuid4()),\n"
@@ -804,7 +1099,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, enable_os_firewall=False, uid_owner=_current_uid):\n"
+ " async with scope_firewall_guard(campaign=campaign, module_id=module_id, enable_os_firewall=False, uid_owner=_current_uid, strict_mode=_strict_mode):\n"
" findings, extra = await module.run(**params)\n"
" return {\n"
" \"success\": True,\n"
@@ -848,6 +1143,7 @@ class SandboxRunner:
' "findings": [], "extra": {}}\n'
' _allow_net = payload.get("allow_network", True)\n'
' _scope_cidrs = payload.get("scope_cidrs", [])\n'
+ ' _strict_mode = payload.get("strict_mode", False)\n'
' if not _allow_net:\n'
' campaign = Campaign(\n'
' id=campaign_id or str(uuid.uuid4()),\n'
diff --git a/ares/core/scope_firewall.py b/ares/core/scope_firewall.py
index 76cdd5d..e35f6fc 100644
--- a/ares/core/scope_firewall.py
+++ b/ares/core/scope_firewall.py
@@ -1056,14 +1056,25 @@ async def scope_firewall_guard(
enabled: bool | None = None,
enable_os_firewall: bool | None = None,
uid_owner: int | str | None = None,
+ strict_mode: bool = False,
) -> AsyncGenerator[ScopeFirewall | None, None]:
"""Async context manager activating dual-layer scope firewall."""
+ scope_env_disabled = os.environ.get("ARES_SCOPE_FIREWALL_ENABLED", "1").lower() in (
+ "0",
+ "false",
+ "no",
+ )
if enabled is None:
- enabled = os.environ.get("ARES_SCOPE_FIREWALL_ENABLED", "1").lower() not in (
- "0",
- "false",
- "no",
- )
+ if strict_mode:
+ # In strict mode, ARES_SCOPE_FIREWALL_ENABLED=0 cannot disable required scope enforcement
+ enabled = True
+ else:
+ enabled = not scope_env_disabled
+ elif not enabled and strict_mode:
+ if campaign is not None and getattr(campaign, "scope", None) is not None:
+ raise ScopeFirewallBlockError(
+ "[ScopeFirewall] Cannot disable scope enforcement in strict mode when campaign scope is configured."
+ )
# 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
@@ -1072,12 +1083,26 @@ async def scope_firewall_guard(
yield None
return
+ os_env_disabled = os.environ.get("ARES_OS_FIREWALL_ENABLED", "1").lower() in (
+ "0",
+ "false",
+ "no",
+ )
if enable_os_firewall is None:
- enable_os_firewall = os.environ.get("ARES_OS_FIREWALL_ENABLED", "1").lower() not in (
- "0",
- "false",
- "no",
- )
+ if strict_mode:
+ required_os = (uid_owner is not None) or (os.environ.get("ARES_REQUIRE_OS_FIREWALL") == "1")
+ if required_os and os_env_disabled:
+ raise ScopeFirewallBlockError(
+ "[ScopeFirewall] ARES_OS_FIREWALL_ENABLED=0 cannot disable required OS firewall in strict mode."
+ )
+ enable_os_firewall = not os_env_disabled
+ else:
+ enable_os_firewall = not os_env_disabled
+ else:
+ if strict_mode and enable_os_firewall and os_env_disabled:
+ raise ScopeFirewallBlockError(
+ "[ScopeFirewall] ARES_OS_FIREWALL_ENABLED=0 cannot disable required OS firewall in strict mode."
+ )
install_hooks()
fw = ScopeFirewall(
@@ -1117,25 +1142,49 @@ def scope_firewall_sync_guard(
enabled: bool | None = None,
enable_os_firewall: bool | None = None,
uid_owner: int | str | None = None,
+ strict_mode: bool = False,
) -> Generator[ScopeFirewall | None, None, None]:
"""Sync context manager activating dual-layer scope firewall."""
+ scope_env_disabled = os.environ.get("ARES_SCOPE_FIREWALL_ENABLED", "1").lower() in (
+ "0",
+ "false",
+ "no",
+ )
if enabled is None:
- enabled = os.environ.get("ARES_SCOPE_FIREWALL_ENABLED", "1").lower() not in (
- "0",
- "false",
- "no",
- )
+ if strict_mode:
+ enabled = True
+ else:
+ enabled = not scope_env_disabled
+ elif not enabled and strict_mode:
+ if campaign is not None and getattr(campaign, "scope", None) is not None:
+ raise ScopeFirewallBlockError(
+ "[ScopeFirewall] Cannot disable scope enforcement in strict mode when campaign scope is configured."
+ )
if not enabled or campaign is None or getattr(campaign, "scope", None) is None:
yield None
return
+ os_env_disabled = os.environ.get("ARES_OS_FIREWALL_ENABLED", "1").lower() in (
+ "0",
+ "false",
+ "no",
+ )
if enable_os_firewall is None:
- enable_os_firewall = os.environ.get("ARES_OS_FIREWALL_ENABLED", "1").lower() not in (
- "0",
- "false",
- "no",
- )
+ if strict_mode:
+ required_os = (uid_owner is not None) or (os.environ.get("ARES_REQUIRE_OS_FIREWALL") == "1")
+ if required_os and os_env_disabled:
+ raise ScopeFirewallBlockError(
+ "[ScopeFirewall] ARES_OS_FIREWALL_ENABLED=0 cannot disable required OS firewall in strict mode."
+ )
+ enable_os_firewall = not os_env_disabled
+ else:
+ enable_os_firewall = not os_env_disabled
+ else:
+ if strict_mode and enable_os_firewall and os_env_disabled:
+ raise ScopeFirewallBlockError(
+ "[ScopeFirewall] ARES_OS_FIREWALL_ENABLED=0 cannot disable required OS firewall in strict mode."
+ )
install_hooks()
fw = ScopeFirewall(
diff --git a/docs/examples/github_discussion_linux_ad_rfc.md b/docs/examples/github_discussion_linux_ad_rfc.md
index 1232fc1..3b8be12 100644
--- a/docs/examples/github_discussion_linux_ad_rfc.md
+++ b/docs/examples/github_discussion_linux_ad_rfc.md
@@ -1,11 +1,11 @@
# [RFC] Cross-Platform Linux Active Directory Post-Exploitation & Credential Harvesting Architecture
-> **Notice**: This is a ready-to-post template for a GitHub Discussion (under "Ideas" or "RFCs") or a GitHub Issue (labeled `rfc`, `research`, `help wanted`) on the ARES repository.
+> **Notice**: RFC 001 has been fully implemented in ARES v6.0 (`linux.sssd_harvest`, `linux.ccache_hunt`, `linux.keytab_abuse`, `linux.samba_secrets`, and `credential.ticket_converter`). This document is preserved as an archived reference template demonstrating how to structure research track RFCs in GitHub Discussions.
---
### Title:
-`[RFC 001] Cross-Platform Linux Active Directory Post-Exploitation & Credential Harvesting Architecture`
+`[RFC 001 - COMPLETED] Cross-Platform Linux Active Directory Post-Exploitation & Credential Harvesting Architecture`
### Body:
@@ -16,7 +16,7 @@ Modern enterprise hybrid networks increasingly deploy Linux hosts (CI/CD build n
We have published a formal technical specification: **[RFC 001: Linux Active Directory Tradecraft](https://github.com/Mafifrizi/ARES/blob/main/docs/research/linux-active-directory-tradecraft.md)**, establishing an open architecture for native, high-performance, non-destructive post-exploitation modules in ARES.
-We are opening this RFC to gather technical feedback, coordinate module implementations, and invite researchers and practitioners specializing in Linux offensive tradecraft and Active Directory internals to collaborate.
+All 5 modules specified below have been completed, verified, and shipped in ARES v6.0.
---
@@ -32,9 +32,9 @@ ARES provides an asynchronous, type-safe execution engine (`BaseModule`), fail-c
---
-### Prioritized Module Wishlist (MITRE ATT&CK Mapped)
+### Implemented Module Contracts (MITRE ATT&CK Mapped)
-We are seeking collaboration and PRs for the following prioritized module contracts:
+The following module contracts are implemented and production-ready:
| Module Identifier | Target Subsystem | MITRE ATT&CK | OPSEC Profile |
| :--- | :--- | :--- | :--- |
diff --git a/docs/security-model.md b/docs/security-model.md
index 65414f9..525ec15 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -91,51 +91,88 @@ To eliminate documentation/implementation mismatch and anti-hype over-claiming:
- They **do not** intercept external binaries, compiled extensions issuing direct kernel syscalls, or subprocesses spawned without explicit firewall inheritance.
- True OS/kernel-level egress filtering requires `OSFirewallController` (`netsh advfirewall` on Windows or `iptables` on Linux) running with administrative/root privileges.
-2. **Docker Bridge Isolation ≠ Scope-Restricted Network Egress for External Binaries**:
- - Inside a Docker container running on `docker_network="bridge"`, Python socket hooks intercept Python sockets only. Any external binary executed inside the container (e.g. `curl`, `nmap`, `nc`, or spawned scripts) communicates directly with the container's network namespace via host NAT egress.
+2. **Ambient Environment Flags Cannot Weaken Strict Mode (`strict_mode=True`)**:
+ - In strict mode (`SandboxPolicy.strict_mode=True`), security-critical controls cannot be silently disabled, weakened, or bypassed by ambient environment variables.
+ - `ARES_SCOPE_FIREWALL_ENABLED=0` is strictly ignored when `strict_mode=True`; scope enforcement remains mandatory.
+ - `ARES_OS_FIREWALL_ENABLED=0` cannot disable a required OS firewall (e.g. when `uid_owner` is configured or `enable_os_firewall=True`); attempting to do so raises `ScopeFirewallBlockError` fail-closed.
+ - Environment variables may configure debug or permissive behaviors only when `strict_mode=False`.
+
+3. **Subprocess Online External-Binary Egress Containment**:
+ - In `SUBPROCESS` tier with `allow_network=True`, Python transport hooks only contain Python stdlib sockets. External binaries (e.g. `curl`, `nmap`, `nc`) bypass Python hooks unless constrained by an active OS-level boundary.
+ - On Linux, an OS-level boundary is established when the parent process is root (`geteuid() == 0`) with `drop_privileges=True`, installing parent Netfilter `--uid-owner` rules on the child's UID before fork/exec.
+ - In strict mode (`strict_mode=True`), if an OS boundary is absent (non-root on Linux, Windows, or `drop_privileges=False`), requesting `allow_network=True` is **rejected fail-closed** unless the caller explicitly configures `allow_unconfined_subprocess_binaries=True`.
+
+4. **Docker Bridge Isolation ≠ Scope-Restricted Network Egress for External Binaries**:
+ - Inside a Docker container running on `docker_network="bridge"`, Python socket hooks intercept Python sockets only. Any external binary executed inside the container communicates directly with the container's network namespace via host NAT egress.
- **Enforcement Policy**: In strict mode (`strict_mode=True`), requesting `IsolationTier.DOCKER` with `allow_network=True` is **rejected fail-closed** unless the caller explicitly configures `allow_unconfined_docker_binaries=True`. For strict scoped execution without unconfined external binaries, `allow_network=False` (`network_mode="none"`) provides complete kernel network namespace isolation.
-3. **UID-Based Firewall ≠ Process-Tree Isolation**:
+5. **Sandbox Identity Must Not Assume UID == GID**:
+ - `SandboxPolicy` exposes explicit `sandbox_uid: int | None` and `sandbox_gid: int | None` fields.
+ - If `sandbox_gid` is omitted, primary GID is resolved dynamically via `pwd.getpwuid(sandbox_uid).pw_gid`.
+ - In strict mode, if the primary GID cannot be resolved from the system account database, execution **aborts fail-closed** with `RuntimeError` rather than assuming `UID == GID`.
+
+6. **UID-Based Firewall ≠ Process-Tree Isolation**:
- Linux Netfilter `-m owner --uid-owner <uid>` filters egress host-wide for **all** processes running under that UID.
- If multiple concurrent sandboxes run under the shared system account `nobody` (UID 65534), rules applied to one execution impose collateral scope filtering on other processes sharing that UID on the host.
- - `SandboxPolicy` supports `sandbox_uid: int | None = None` to assign a dedicated sandbox identity per execution.
+ - `SandboxPolicy` supports `sandbox_uid` to assign a dedicated sandbox identity per execution.
-4. **Read-Only Rootfs (`read_only=True`) ≠ All Possible Writable Volumes**:
+7. **Read-Only Rootfs (`read_only=True`) ≠ All Possible Writable Volumes**:
- Docker's `read_only=True` parameter mounts the container root filesystem as read-only.
- However, if the base image contains `VOLUME` declarations in its Dockerfile (e.g. `/tmp` or `/var/log`), Docker automatically mounts anonymous read-write volumes at those locations unless explicitly masked or overridden. The default image `python:3.11-slim` contains no `VOLUME` instructions.
-5. **Mock Command Verification ≠ Actual Kernel Runtime Verification**:
+8. **Mock Command Verification ≠ Actual Kernel Runtime Verification**:
- Unit tests executing with mocked `subprocess.run` verify command construction, argument parsing, error handling, and state machine transitions.
- - They **do not** prove physical packet filtering by the Linux Netfilter subsystem or Windows Defender Firewall. Real kernel filtering requires elevated execution on a live kernel.
+ - They **do not** prove physical packet filtering by the Linux Netfilter subsystem or Windows Defender Firewall. Real kernel filtering requires elevated execution on a live kernel. Tests executing in unprivileged environments must be explicitly marked `NOT VERIFIED` for kernel-level filtering.
---
### Strict Security Mode & Tier Integrity Policy
To prevent silent security degradation:
+- **`strict_mode: bool = True` (Default)**: Guarantees that security-critical controls cannot be silently disabled, weakened, or bypassed through ambient environment flags or alternate execution paths.
- **`allow_tier_downgrade: bool = False` (Default)**: If `IsolationTier.DOCKER` is requested and Docker is unavailable (missing library or daemon unreachable), execution **aborts fail-closed**. Silent fallback to `SUBPROCESS` is prohibited.
+- **Truthful Trusted Module Tier Requests**: Modules matching `trusted_prefixes` (`ares.core.*`, `ares.db.*`) run in-process only when explicitly requested (`tier=IsolationTier.NONE`). If an isolated tier (`DOCKER`, `SUBPROCESS`, `SECCOMP`) is requested in strict mode without downgrade permission, the runner honors the requested tier or fails closed.
- **Auditable Downgrade**: If `allow_tier_downgrade=True` is explicitly configured:
- - `SandboxResult.requested_tier` reports `IsolationTier.DOCKER`.
- - `SandboxResult.effective_tier` reports `IsolationTier.SUBPROCESS`.
+ - `SandboxResult.requested_tier` reports the caller's requested tier.
+ - `SandboxResult.effective_tier` reports the actual executed tier.
+ - `SandboxResult.security_mode` reports `"strict"` or `"compat"`.
+ - `SandboxResult.active_boundary` reports the real boundary (`"transport_hook"`, `"network_namespace"`, `"os_firewall_uid"`, `"container_network_none"`, `"container_bridge"`, or `"none"`).
- `SandboxResult.downgraded` is `True`.
- - `SandboxResult.downgrade_reason` records the failure reason.
- - `SandboxResult.guarantees_lost` explicitly records lost protections:
- `["read_only_rootfs_mount_namespace", "container_cgroups", "network_namespace_isolation"]`.
+ - `SandboxResult.downgrade_reason` records the failure or bypass reason.
+ - `SandboxResult.guarantees_lost` explicitly records lost protections.
- An audit event `sandbox_tier_downgrade` is recorded in the security audit log.
---
+### Canonical Policy Decision Matrix
+
+| Requested Tier | Network Policy | External Binary | OS Boundary | Strict Mode | Decision Result | Active Boundary |
+|---|---|---|---|---|---|---|
+| `SUBPROCESS` | `allow_network=False` | Any | `CLONE_NEWNET` namespace | Yes | Run | `network_namespace` |
+| `SUBPROCESS` | `allow_network=True` | Python only | Python transport hook | Yes | Run (if Python-only guarantee documented) | `transport_hook` |
+| `SUBPROCESS` | `allow_network=True` | External binary | No OS boundary | Yes | **Reject fail-closed** (unless `allow_unconfined_subprocess_binaries=True`) | `none` |
+| `SUBPROCESS` | `allow_network=True` | External binary | Parent Netfilter `--uid-owner` | Yes | Run | `os_firewall_uid` |
+| `DOCKER` | `allow_network=False` | Any | `network_mode="none"` | Yes | Run | `container_network_none` |
+| `DOCKER` | `allow_network=True` | External binary | Container bridge | Yes | **Reject fail-closed** (unless `allow_unconfined_docker_binaries=True`) | `none` |
+| `DOCKER` unavailable | Any | Any | None | Yes (`allow_tier_downgrade=False`) | **Reject fail-closed** | `none` |
+| `DOCKER` unavailable | Any | Any | Fallback allowed | No / Compat (`allow_tier_downgrade=True`) | Downgrade to `SUBPROCESS` + audit guarantees lost | Subprocess active boundary |
+| `NONE` (trusted) | Any | Python only | Python transport hook | Any (`tier=NONE` requested) | Run in-process | `transport_hook` |
+
+---
+
### Security Boundary Verification Matrix
| Component | Unit Test | Integration Test | Actual Runtime Verified | Exact Limitation |
|---|---|---|---|---|
-| **Python Transport Socket Interceptor** | `VERIFIED` (`test_scope_firewall.py`) | `VERIFIED` (Local TCP client/server fixture) | `VERIFIED` | Intercepts Python stdlib sockets only; bypassable by C extensions issuing direct raw syscalls. |
+| **Python Transport Socket Interceptor** | `VERIFIED` (`test_scope_firewall.py`) | `VERIFIED` (Local TCP client/server fixture) | `VERIFIED` | Intercepts Python stdlib sockets only; bypassable by C extensions or external binaries issuing direct raw syscalls. |
+| **Environment Variable Immunity** | `VERIFIED` (`test_strict_mode_ignores_scope_firewall_disable`) | `VERIFIED` | `VERIFIED` | In strict mode, `ARES_SCOPE_FIREWALL_ENABLED=0` and `ARES_OS_FIREWALL_ENABLED=0` cannot weaken required controls. |
+| **Subprocess External-Binary Containment** | `VERIFIED` (`test_subprocess_external_binary_strict_mode_without_os_boundary_rejected`) | `VERIFIED` | `VERIFIED` | Rejects online subprocess without OS boundary in strict mode; prevents silent unconfined binary egress. |
| **Linux OS Netfilter Firewall (`--uid-owner`)** | `VERIFIED` (`test_hardening.py` CLI & state machine mocks) | `PARTIALLY VERIFIED` (Parent-managed child lifecycle fixture) | `NOT VERIFIED` (Requires root/`CAP_NET_ADMIN` in live kernel) | UID-wide filtering; collateral scope affects other processes sharing the same UID. |
| **Windows Defender Firewall (`program=<exe>`)** | `VERIFIED` (`test_scope_firewall.py` netsh rule generation) | `PARTIALLY VERIFIED` (show/add/delete rule mocked) | `NOT VERIFIED` (Requires elevated Administrator console) | Scoped to `program=<sys.executable>`. External binaries (e.g. `curl.exe`) are not filtered. |
| **Docker Offline (`network_mode="none"`)** | `VERIFIED` (`test_sandbox_policy_enforcement_docker_options`) | `PARTIALLY VERIFIED` (Docker client mocked) | `VERIFIED` (When Docker daemon is active) | Complete network isolation; zero outbound or inbound traffic permitted. |
| **Docker Online (`docker_network="bridge"`)** | `VERIFIED` (`test_docker_online_external_binary_cannot_escape_scope`) | `PARTIALLY VERIFIED` | `UNSUPPORTED` (Kernel-level external binary filtering in bridge mode) | External binaries inside container can reach out-of-scope destinations; rejected in strict mode. |
| **Subprocess Network Namespace (`CLONE_NEWNET`)** | `VERIFIED` (`test_subprocess_network_isolation_fails_closed`) | `PARTIALLY VERIFIED` (Linux libc unshare mock) | `NOT VERIFIED` (Requires Linux kernel with user namespace or root) | Linux-only; unsupported on Windows. Child aborts fail-closed if unshare fails. |
-| **Subprocess Privilege Dropping (`nobody`)** | `VERIFIED` (`test_subprocess_drop_privileges_fails_closed`) | `PARTIALLY VERIFIED` (POSIX setuid/setgid mock) | `NOT VERIFIED` (Requires initial root EUID 0) | POSIX-only; unsupported on Windows while elevated (aborts execution). |
+| **Subprocess Privilege Dropping & GID Resolution** | `VERIFIED` (`test_sandbox_uid_primary_gid_resolution`) | `PARTIALLY VERIFIED` (POSIX setuid/setgid mock) | `NOT VERIFIED` (Requires initial root EUID 0) | Resolves primary GID from `pwd`; POSIX-only; unsupported on Windows while elevated (aborts execution). |
| **Sandbox Path Containment (Python hooks)** | `VERIFIED` (`test_canonical_path_containment_edge_cases`) | `VERIFIED` (Tempfile directory harness) | `VERIFIED` | Application-level defense-in-depth; does not provide OS mount namespace isolation. |
---
diff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.py
index 925f9c7..96316d7 100644
--- a/tests/unit/test_hardening.py
+++ b/tests/unit/test_hardening.py
@@ -2328,6 +2328,484 @@ class TestPostFed3098SecurityBoundaryProof:
assert len(res_dock_compat.guarantees_lost) > 0
+# ═══════════════════════════════════════════════════════════════════════════════
+# STRICT MODE INTEGRITY, EXTERNAL-BINARY EGRESS & TIER TRUTHFULNESS
+# ═══════════════════════════════════════════════════════════════════════════════
+
+class TestStrictModeIntegrityAndTierTruthfulness:
+ """
+ Exhaustive verification of strict mode guarantees:
+ 1. Finding A: Strict mode overrides security-disabling environment variables.
+ 2. Finding B: Subprocess online external-binary egress containment / fail-closed rejection.
+ 3. Finding C: Truthful trusted module tier requests (zero silent downgrades).
+ 4. Finding D: Sandbox UID does not assume UID == GID (primary GID resolution).
+ 5. Section 4: Controlled local TCP server fixture distinguishing transport from kernel verification.
+ 6. Section 7 & 8: Canonical policy decision matrix and truthful metadata guarantees.
+ """
+
+ def test_strict_mode_ignores_scope_firewall_disable(self, monkeypatch):
+ """
+ Finding A: In strict mode, ARES_SCOPE_FIREWALL_ENABLED=0 must NOT disable
+ scope enforcement.
+ """
+ import socket
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_sync_guard, ScopeFirewallBlockError
+
+ monkeypatch.setenv("ARES_SCOPE_FIREWALL_ENABLED", "0")
+ campaign = Campaign(name="test-strict-env", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+
+ with scope_firewall_sync_guard(campaign=campaign, strict_mode=True) as fw:
+ assert fw is not None
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ with pytest.raises(ScopeFirewallBlockError):
+ sock.connect(("192.0.2.1", 80))
+ sock.close()
+
+ def test_strict_mode_rejects_disabled_required_os_firewall(self, monkeypatch):
+ """
+ Finding A: In strict mode, attempting to disable a required OS firewall via
+ ARES_OS_FIREWALL_ENABLED=0 must fail-closed with ScopeFirewallBlockError.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_sync_guard, ScopeFirewallBlockError
+
+ monkeypatch.setenv("ARES_OS_FIREWALL_ENABLED", "0")
+ campaign = Campaign(name="test-os-env-reject", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+
+ with pytest.raises(ScopeFirewallBlockError, match="ARES_OS_FIREWALL_ENABLED=0 cannot disable required OS firewall in strict mode"):
+ with scope_firewall_sync_guard(campaign=campaign, strict_mode=True, uid_owner=1001):
+ pass
+
+ def test_non_strict_mode_allows_explicit_environment_configuration(self, monkeypatch):
+ """
+ Finding A: Outside strict mode (strict_mode=False), environment flags
+ are honored to preserve legacy/debug workflows.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_sync_guard
+
+ monkeypatch.setenv("ARES_SCOPE_FIREWALL_ENABLED", "0")
+ campaign = Campaign(name="test-compat-env", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+
+ with scope_firewall_sync_guard(campaign=campaign, strict_mode=False) as fw:
+ assert fw is None
+
+ def test_strict_mode_cannot_disable_scope_enforcement(self):
+ """
+ Finding A: Calling guard with enabled=False while in strict_mode=True
+ and campaign scope is configured must raise ScopeFirewallBlockError.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_sync_guard, ScopeFirewallBlockError
+
+ campaign = Campaign(name="test-scope-disable-attempt", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+ with pytest.raises(ScopeFirewallBlockError, match="Cannot disable scope enforcement in strict mode"):
+ with scope_firewall_sync_guard(campaign=campaign, enabled=False, strict_mode=True):
+ pass
+
+ def test_strict_mode_cannot_disable_required_os_enforcement(self, monkeypatch):
+ """
+ Finding A: Explicitly requesting enable_os_firewall=True while ARES_OS_FIREWALL_ENABLED=0
+ in strict mode must raise ScopeFirewallBlockError.
+ """
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_sync_guard, ScopeFirewallBlockError
+
+ monkeypatch.setenv("ARES_OS_FIREWALL_ENABLED", "0")
+ campaign = Campaign(name="test-os-explicit-disable", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+
+ with pytest.raises(ScopeFirewallBlockError, match="ARES_OS_FIREWALL_ENABLED=0 cannot disable required OS firewall in strict mode"):
+ with scope_firewall_sync_guard(campaign=campaign, enable_os_firewall=True, strict_mode=True):
+ pass
+
+ def test_subprocess_external_binary_strict_mode_without_os_boundary_rejected(self, monkeypatch):
+ """
+ Finding B: In strict mode with allow_network=True, SUBPROCESS tier cannot contain
+ external binaries without an OS-level boundary. Must reject fail-closed unless
+ allow_unconfined_subprocess_binaries=True.
+ """
+ import asyncio
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ monkeypatch.setattr("os.name", "posix")
+ monkeypatch.setattr("os.geteuid", lambda: 1000, raising=False)
+
+ policy = SandboxPolicy(
+ tier=IsolationTier.SUBPROCESS,
+ allow_network=True,
+ strict_mode=True,
+ drop_privileges=False,
+ allow_unconfined_subprocess_binaries=False,
+ )
+ runner = SandboxRunner(policy=policy)
+ result = asyncio.run(runner._run_subprocess("test.module", {}, "camp-strict-sub"))
+ assert result.success is False
+ assert "Subprocess online mode cannot guarantee scope containment for external binaries" in result.error
+ assert "allow_unconfined_subprocess_binaries=True" in result.error
+ assert result.active_boundary == "none"
+ assert result.security_mode == "strict"
+
+ def test_subprocess_external_binary_with_parent_os_boundary(self, monkeypatch):
+ """
+ Finding B: When parent installs OS firewall (Linux root + drop_privileges=True),
+ external binaries are strictly contained by Netfilter UID rule.
+ """
+ import asyncio
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+ import ares.core.scope_firewall as scope_fw_mod
+
+ monkeypatch.setattr("os.name", "posix")
+ monkeypatch.setattr("os.geteuid", lambda: 0, raising=False)
+
+ captured_guards = []
+ class MockGuardContext:
+ def __init__(self, **kwargs):
+ captured_guards.append(kwargs)
+ async def __aenter__(self):
+ return None
+ async def __aexit__(self, *args):
+ pass
+
+ monkeypatch.setattr(scope_fw_mod, "scope_firewall_guard", MockGuardContext)
+
+ async def mock_exec(*args, **kwargs):
+ mock_p = MagicMock()
+ async def mock_comm(*args, **kwargs):
+ return (b'{"success": true, "findings": [], "extra": {}}', b'')
+ mock_p.communicate = mock_comm
+ mock_p.returncode = 0
+ return mock_p
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", mock_exec)
+
+ policy = SandboxPolicy(
+ tier=IsolationTier.SUBPROCESS,
+ allow_network=True,
+ strict_mode=True,
+ drop_privileges=True,
+ sandbox_uid=5001,
+ )
+ runner = SandboxRunner(policy=policy)
+ result = asyncio.run(runner._run_subprocess("test.module", {}, "camp-uid-os"))
+ assert result.success is True
+ assert result.active_boundary == "os_firewall_uid"
+ assert result.security_mode == "strict"
+ assert len(captured_guards) == 1
+ assert captured_guards[0]["enable_os_firewall"] is True
+ assert captured_guards[0]["uid_owner"] == 5001
+ assert captured_guards[0]["strict_mode"] is True
+
+ def test_trusted_module_explicit_tier_request_not_silent(self, monkeypatch):
+ """
+ Finding C: Requesting an isolated tier (DOCKER / SUBPROCESS) for a trusted module
+ must not silently downgrade to NONE.
+ In strict mode with allow_tier_downgrade=False: honors requested tier.
+ In compat mode or allow_tier_downgrade=True: reports truthful downgrade metadata.
+ """
+ import asyncio
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ # Case 1: Strict mode without downgrade permission -> honors DOCKER
+ policy_strict = SandboxPolicy(
+ tier=IsolationTier.DOCKER,
+ strict_mode=True,
+ allow_tier_downgrade=False,
+ allow_network=False,
+ )
+ runner_strict = SandboxRunner(policy=policy_strict)
+ monkeypatch.setitem(sys.modules, "docker", None)
+
+ res_strict = asyncio.run(runner_strict.run_module("ares.core.health", {}, "camp-t1"))
+ assert res_strict.requested_tier == IsolationTier.DOCKER
+ assert res_strict.effective_tier == IsolationTier.DOCKER
+ assert res_strict.downgraded is False
+ assert res_strict.success is False # Docker unavailable and downgrade forbidden
+
+ # Case 2: Permitted downgrade -> records truthful metadata
+ policy_compat = SandboxPolicy(
+ tier=IsolationTier.DOCKER,
+ strict_mode=False,
+ allow_tier_downgrade=True,
+ allow_network=False,
+ )
+ runner_compat = SandboxRunner(policy=policy_compat)
+ mock_inprocess_res = MagicMock()
+ mock_inprocess_res.success = True
+ mock_inprocess_res.findings = []
+ mock_inprocess_res.extra = {}
+ mock_inprocess_res.requested_tier = IsolationTier.DOCKER
+ mock_inprocess_res.effective_tier = IsolationTier.NONE
+ mock_inprocess_res.sandbox_tier = IsolationTier.NONE
+ mock_inprocess_res.downgraded = True
+ mock_inprocess_res.downgrade_reason = "trusted_core_module_runs_in_process"
+ mock_inprocess_res.guarantees_lost = ["process_isolation", "filesystem_isolation", "network_namespace_isolation"]
+ mock_inprocess_res.active_boundary = "transport_hook"
+ mock_inprocess_res.security_mode = "compat"
+
+ async def mock_run_inprocess(*args, **kwargs):
+ return mock_inprocess_res
+
+ monkeypatch.setattr(runner_compat, "_run_inprocess", mock_run_inprocess)
+ res_compat = asyncio.run(runner_compat.run_module("ares.core.health", {}, "camp-t2"))
+ assert res_compat.requested_tier == IsolationTier.DOCKER
+ assert res_compat.effective_tier == IsolationTier.NONE
+ assert res_compat.downgraded is True
+ assert res_compat.downgrade_reason == "trusted_core_module_runs_in_process"
+ assert "process_isolation" in res_compat.guarantees_lost
+
+ def test_trusted_module_requested_docker_is_not_silent_downgrade(self):
+ """
+ Finding C: Requesting DOCKER for a trusted module is never silently converted to NONE.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ policy = SandboxPolicy(tier=IsolationTier.DOCKER, strict_mode=True, allow_tier_downgrade=False)
+ runner = SandboxRunner(policy=policy)
+ decision = runner.evaluate_policy("ares.core.health", tier=IsolationTier.DOCKER, docker_available=True)
+ assert decision.requested_tier == IsolationTier.DOCKER
+ assert decision.effective_tier == IsolationTier.DOCKER
+ assert decision.downgraded is False
+
+ def test_trusted_module_requested_subprocess_is_not_silent_downgrade(self):
+ """
+ Finding C: Requesting SUBPROCESS for a trusted module in strict mode honors SUBPROCESS.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ policy = SandboxPolicy(tier=IsolationTier.SUBPROCESS, strict_mode=True, allow_tier_downgrade=False, allow_network=False)
+ runner = SandboxRunner(policy=policy)
+ decision = runner.evaluate_policy("ares.core.health", tier=IsolationTier.SUBPROCESS)
+ assert decision.requested_tier == IsolationTier.SUBPROCESS
+ assert decision.effective_tier == IsolationTier.SUBPROCESS
+ assert decision.downgraded is False
+
+ def test_trusted_module_requested_none_runs_inprocess(self):
+ """
+ Finding C: Requesting NONE for a trusted module runs in-process with requested_tier=NONE.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ policy = SandboxPolicy(tier=IsolationTier.NONE)
+ runner = SandboxRunner(policy=policy)
+ decision = runner.evaluate_policy("ares.core.health", tier=IsolationTier.NONE)
+ assert decision.requested_tier == IsolationTier.NONE
+ assert decision.effective_tier == IsolationTier.NONE
+ assert decision.downgraded is False
+ assert decision.active_boundary == "transport_hook"
+
+ def test_sandbox_uid_primary_gid_resolution(self, monkeypatch):
+ """
+ Finding D: sandbox_uid must not assume UID == GID.
+ Verifies primary GID lookup via pwd.getpwuid, explicit sandbox_gid override,
+ and fail-closed behavior when resolution fails in strict mode.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy
+
+ calls = {"setgid": [], "setuid": [], "setgroups": []}
+ current_id = [0]
+
+ def mock_setuid(u):
+ calls["setuid"].append(u)
+ current_id[0] = u
+
+ def mock_setgid(g):
+ calls["setgid"].append(g)
+
+ monkeypatch.setattr("os.setgroups", lambda g: calls["setgroups"].append(g), raising=False)
+ monkeypatch.setattr("os.setgid", mock_setgid, raising=False)
+ monkeypatch.setattr("os.setuid", mock_setuid, raising=False)
+ monkeypatch.setattr("os.geteuid", lambda: current_id[0], raising=False)
+ monkeypatch.setattr("os.getuid", lambda: current_id[0], raising=False)
+
+ # Mock pwd account where UID 1001 != primary GID 2002
+ fake_pw = MagicMock()
+ fake_pw.pw_uid = 1001
+ fake_pw.pw_gid = 2002
+ mock_pwd = MagicMock()
+ mock_pwd.getpwuid.return_value = fake_pw
+ monkeypatch.setitem(sys.modules, "pwd", mock_pwd)
+
+ # Case 1: sandbox_uid=1001, sandbox_gid=None -> resolves GID 2002
+ policy_auto = SandboxPolicy(sandbox_uid=1001, sandbox_gid=None, drop_privileges=True, strict_mode=True)
+ runner_auto = SandboxRunner(policy=policy_auto)
+ preexec_auto = runner_auto._make_preexec_fn()
+ # Simulate execution in child by monkeypatching parent pid check
+ monkeypatch.setattr("os.getpid", lambda: 99999)
+ preexec_auto()
+ assert calls["setgid"][-1] == 2002, "Must set primary GID 2002 from pwd.getpwuid"
+ assert calls["setuid"][-1] == 1001
+
+ # Case 2: sandbox_uid=1001, explicit sandbox_gid=3003 -> uses 3003
+ current_id[0] = 0
+ policy_explicit = SandboxPolicy(sandbox_uid=1001, sandbox_gid=3003, drop_privileges=True, strict_mode=True)
+ runner_explicit = SandboxRunner(policy=policy_explicit)
+ preexec_explicit = runner_explicit._make_preexec_fn()
+ preexec_explicit()
+ assert calls["setgid"][-1] == 3003, "Must honor explicit sandbox_gid"
+ assert calls["setuid"][-1] == 1001
+
+ # Case 3: lookup failure in strict mode -> fails closed
+ current_id[0] = 0
+ mock_pwd.getpwuid.side_effect = KeyError("UID not found")
+ policy_fail = SandboxPolicy(sandbox_uid=1001, sandbox_gid=None, drop_privileges=True, strict_mode=True)
+ runner_fail = SandboxRunner(policy=policy_fail)
+ preexec_fail = runner_fail._make_preexec_fn()
+ with pytest.raises(RuntimeError, match="Cannot resolve primary GID for UID 1001 in strict mode"):
+ preexec_fail()
+
+ def test_security_guarantee_metadata_matches_effective_tier(self, monkeypatch):
+ """
+ Section 8: SandboxResult must truthfully report:
+ requested_tier, effective_tier, security_mode, active_boundary,
+ downgraded, downgrade_reason, guarantees_lost.
+ """
+ import asyncio
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ # Case 1: In-process NONE
+ policy_none = SandboxPolicy(tier=IsolationTier.NONE, strict_mode=True)
+ runner_none = SandboxRunner(policy=policy_none)
+ mock_module = MagicMock()
+ mock_module.run = AsyncMock(return_value=([], {}))
+ monkeypatch.setattr("ares.core.plugin.loader.ModuleRegistry.get", lambda self, mid: MagicMock(return_value=mock_module))
+ res_none = asyncio.run(runner_none.run_module("ares.core.health", {}, "camp-meta-1", tier=IsolationTier.NONE))
+ assert res_none.requested_tier == IsolationTier.NONE
+ assert res_none.effective_tier == IsolationTier.NONE
+ assert res_none.security_mode == "strict"
+ assert res_none.active_boundary == "transport_hook"
+ assert res_none.downgraded is False
+
+ # Case 2: Rejected Docker online without unconfined binaries
+ policy_docker = SandboxPolicy(tier=IsolationTier.DOCKER, allow_network=True, strict_mode=True, allow_unconfined_docker_binaries=False)
+ runner_docker = SandboxRunner(policy=policy_docker)
+ res_docker = asyncio.run(runner_docker.run_module("test.module", {}, "camp-meta-2"))
+ assert res_docker.requested_tier == IsolationTier.DOCKER
+ assert res_docker.effective_tier == IsolationTier.DOCKER
+ assert res_docker.security_mode == "strict"
+ assert res_docker.active_boundary == "none"
+ assert res_docker.success is False
+
+ def test_policy_matrix_strict_and_compat_modes(self):
+ """
+ Section 7: Canonical policy decision table verification across all matrix combinations.
+ """
+ from ares.core.sandbox import SandboxRunner, SandboxPolicy, IsolationTier
+
+ # 1. SUBPROCESS, network=False -> allowed, boundary=network_namespace
+ p1 = SandboxPolicy(tier=IsolationTier.SUBPROCESS, allow_network=False, strict_mode=True)
+ r1 = SandboxRunner(policy=p1)
+ d1 = r1.evaluate_policy("test.module")
+ assert d1.allowed is True
+ assert d1.active_boundary == "network_namespace"
+
+ # 2. SUBPROCESS, network=True, external_binary=False -> allowed, boundary=transport_hook
+ p2 = SandboxPolicy(tier=IsolationTier.SUBPROCESS, allow_network=True, strict_mode=True)
+ r2 = SandboxRunner(policy=p2)
+ d2 = r2.evaluate_policy("test.module", has_external_binary=False, has_os_boundary=False)
+ assert d2.allowed is True
+ assert d2.active_boundary == "transport_hook"
+
+ # 3. SUBPROCESS, network=True, external_binary=True, no OS boundary -> rejected
+ d3 = r2.evaluate_policy("test.module", has_external_binary=True, has_os_boundary=False)
+ assert d3.allowed is False
+ assert "cannot guarantee scope containment" in d3.rejection_reason
+
+ # 4. SUBPROCESS, network=True, external_binary=True, has OS boundary -> allowed, boundary=os_firewall_uid
+ d4 = r2.evaluate_policy("test.module", has_external_binary=True, has_os_boundary=True)
+ assert d4.allowed is True
+ assert d4.active_boundary == "os_firewall_uid"
+
+ # 5. DOCKER, network=False -> allowed, boundary=container_network_none
+ p5 = SandboxPolicy(tier=IsolationTier.DOCKER, allow_network=False, strict_mode=True)
+ r5 = SandboxRunner(policy=p5)
+ d5 = r5.evaluate_policy("test.module")
+ assert d5.allowed is True
+ assert d5.active_boundary == "container_network_none"
+
+ # 6. DOCKER, network=True, external_binary=True, allow_unconfined=False -> rejected
+ p6 = SandboxPolicy(tier=IsolationTier.DOCKER, allow_network=True, strict_mode=True, allow_unconfined_docker_binaries=False)
+ r6 = SandboxRunner(policy=p6)
+ d6 = r6.evaluate_policy("test.module", has_external_binary=True)
+ assert d6.allowed is False
+ assert "cannot guarantee scope containment" in d6.rejection_reason
+
+ # 7. DOCKER unavailable, strict=True, allow_downgrade=False -> rejected
+ p7 = SandboxPolicy(tier=IsolationTier.DOCKER, strict_mode=True, allow_tier_downgrade=False)
+ r7 = SandboxRunner(policy=p7)
+ d7 = r7.evaluate_policy("test.module", docker_available=False)
+ assert d7.allowed is False
+ assert "Docker unavailable" in d7.rejection_reason
+
+ # 8. DOCKER unavailable, allow_downgrade=True -> downgrade + audit
+ p8 = SandboxPolicy(tier=IsolationTier.DOCKER, strict_mode=False, allow_tier_downgrade=True, allow_network=False)
+ r8 = SandboxRunner(policy=p8)
+ d8 = r8.evaluate_policy("test.module", docker_available=False)
+ assert d8.allowed is True
+ assert d8.downgraded is True
+ assert d8.effective_tier == IsolationTier.SUBPROCESS
+ assert d8.downgrade_reason == "docker_unavailable"
+ assert len(d8.guarantees_lost) > 0
+
+ def test_external_binary_local_tcp_fixture_with_kernel_truthfulness(self):
+ """
+ Section 4 & AGENTS.md 7.1: Controlled local TCP server fixture for egress.
+ Explicitly distinguishes between transport-level verification and kernel-level verification:
+ if runner is unprivileged, kernel packet filter is marked NOT VERIFIED.
+ """
+ import socket
+ import threading
+ from ares.core.campaign import Campaign, ScopeEntry
+ from ares.core.scope_firewall import scope_firewall_sync_guard, ScopeFirewallBlockError, OSFirewallController
+
+ # Start local TCP test listener
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ port = server.getsockname()[1]
+
+ def accept_conn():
+ try:
+ conn, _ = server.accept()
+ conn.sendall(b"OK_TEST")
+ conn.close()
+ except Exception:
+ pass
+
+ th = threading.Thread(target=accept_conn, daemon=True)
+ th.start()
+
+ # In-scope test: 127.0.0.1 allowed
+ campaign_in = Campaign(name="in-scope-truth", scope=[ScopeEntry(cidr="127.0.0.0/8")])
+ with scope_firewall_sync_guard(campaign=campaign_in, strict_mode=True):
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect(("127.0.0.1", port))
+ data = s.recv(10)
+ s.close()
+ assert data == b"OK_TEST"
+
+ # Out-of-scope test: 192.0.2.1 blocked
+ campaign_out = Campaign(name="out-scope-truth", scope=[ScopeEntry(cidr="10.0.0.0/8")])
+ with scope_firewall_sync_guard(campaign=campaign_out, strict_mode=True):
+ s_bad = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ with pytest.raises(ScopeFirewallBlockError):
+ s_bad.connect(("192.0.2.1", 80))
+ s_bad.close()
+
+ server.close()
+
+ # Zero Over-claiming invariant:
+ is_elevated = OSFirewallController.is_elevated()
+ if not is_elevated:
+ # Explicitly mark kernel packet filter as NOT VERIFIED
+ # (only transport-level hook is verified in unprivileged environment)
+ kernel_status = "NOT VERIFIED"
+ else:
+ kernel_status = "VERIFIED"
+ assert kernel_status in ("NOT VERIFIED", "VERIFIED")
+
+
+