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.

37.5 KB
Raw Blame

ARES Security Model

ARES is an offensive framework. This document explains how ARES protects the operator, client data, and engagement scope from accidental harm.


Threat Model

What we protect against

Threat Mitigation
Community module exfiltrates data Production descriptors are disabled; the real subprocess stdin entry rejects every payload
Credential data leaked to logs structlog sensitive field masking, vault encryption
Out-of-scope host attacked CampaignGuardrail scope check on every operation
Lockout caused by spray AccountLocked error stops ALL attempts, AdaptiveOpsecEngine
Operator machine compromised Encrypted checkpoints, no plaintext secrets on disk
API unauthorized access JWT bearer tokens, bcrypt hashing, rate limiting
Replay of live execution Immutable UUIDv4 idempotency receipts; replay owns zero new dispatch or outbox delta
Module marketplace malware SHA-256 signed manifests, trusted registry only

What we do NOT protect against

  • Physical access to operator machine
  • Compromise of the Redis/queue server (use TLS + auth)
  • Legal liability for engagements without written authorization

Encryption

At Rest

Data Algorithm Key Source
Credential vault AES-256-GCM (AEAD) ARES_ENCRYPTION_KEY
Campaign checkpoints AES-256-GCM (AEAD) Same key
Evidence files AES-256-GCM (AEAD) Same key
API tokens bcrypt (cost=12) N/A (one-way hash)

Key management: ARES uses two separate deployment secrets. The deployer or client generates both; ARES does not ship a shared production key.

# Token/session signing key
export ARES_SECRET_KEY="$(openssl rand -hex 32)"

# Encryption key for vault, checkpoint, and stored sensitive material (AES-256-GCM)
export ARES_ENCRYPTION_KEY="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"

Never store these values in version control. Keep ARES_ENCRYPTION_KEY stable and backed up securely; rotating it requires re-encrypting existing vault and stored sensitive records.

Note: ARES uses PBKDF2-HMAC-SHA256 with 600,000 iterations (OWASP 2024) for key derivation. Legacy records encrypted with Fernet (AES-128-CBC + HMAC-SHA256, 100k iterations) are transparently decrypted and re-encrypted with AES-256-GCM on the next write.

In Transit

  • REST API: HTTPS (TLS 1.2+) - use a reverse proxy (nginx/caddy)
  • WebSocket dashboard: WSS
  • Redis cluster connection: redis+tls:// with cert pinning
  • C-LIVE worker IPC: none; subprocess stdin payloads are rejected

Module Isolation & Security Boundaries (SandboxRunner)

ARES enforces defensive execution boundaries across four isolation tiers (NONE, SUBPROCESS, SECCOMP, DOCKER).

Isolation Tiers & Guarantees

Tier Enforcement Mechanism Filesystem Boundary Network Egress Boundary Privilege Containment
NONE In-process Unconfined Python scope_firewall_guard Unconfined
SUBPROCESS Ephemeral subprocess Working directory lock; Unix RLIMIT_FSIZE=(0,0); defense-in-depth Python open/os.open hooks allow_network=False: Linux unshare(CLONE_NEWNET) fail-closed; allow_network=True: parent --uid-owner Netfilter rules + Python socket interceptor Linux: Root dropped to nobody or sandbox_uid fail-closed; Windows: Aborts if Administrator
SECCOMP Subprocess + BPF syscall filter Same as SUBPROCESS + BPF syscall allowlist filter Same as SUBPROCESS PR_SET_NO_NEW_PRIVS + BPF allowlist
DOCKER Ephemeral container Read-only container rootfs (read_only=True) allow_network=False: network_mode="none"; allow_network=True: bridge (requires allow_unconfined_docker_binaries=True in strict mode) Complete container namespace & cgroups isolation

Non-Negotiable Architectural Truths & Operational Boundaries

To eliminate documentation/implementation mismatch and anti-hype over-claiming:

  1. Python Socket Interception ≠ OS Kernel Egress Enforcement:

    • Python stdlib hooks (socket.connect, socket.sendto, asyncio.create_connection) intercept traffic generated by standard Python network libraries.
    • 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. 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.
  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 to assign a dedicated sandbox identity per execution.
  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.
  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. 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 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 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 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 & 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.

API Security

Authentication

Most non-execution API endpoints require a valid JWT bearer token or may accept an API key. C-LIVE execution endpoints are bearer-only:

Authorization: Bearer eyJhbGci...

or:

X-API-Key: ares_...

API keys are created after login from the Security page or POST /auth/api-keys. They are not startup secrets. Use them for scripts, CI jobs, internal integrations, or repeatable local validation where an interactive browser session is not practical. The raw API key is shown only once at creation time, is stored hashed, and can be revoked from the Security page. In the dashboard, key creation opens the Save your key modal. The full secret appears there once, Copy changes to Copied after a successful copy, and Done closes the modal and clears the in-memory new-key state. The key list shows metadata and a prefix only; the full secret cannot be retrieved later.

API-key scopes are read, write, and admin. They are an additional restriction on API-key-compatible automation routes and do not replace RBAC. Use X-API-Key for automation endpoints such as GET /auth/me; account credential management, user registration, and API-key lifecycle operations are performed from an authenticated browser/JWT session.

Endpoints without an existing bearer (by design):

  • GET /auth/csrf - same-origin pre-login CSRF bootstrap
  • POST /auth/token - same-origin, CSRF-protected browser login
  • GET /health - health check (no sensitive data)

The supported dashboard is the React application served by the main ARES FastAPI application at /dashboard. The older ares.api.dashboard.app:dashboard_app FastAPI application is not mounted by that topology. The executable guard's control objective is to prevent accidental or default deployment of the legacy surface. Under normal ASGI lifespan processing, legacy startup is denied unless both ARES_LEGACY_DASHBOARD_ENABLED=true and ARES_DEBUG=true; the legacy flag must never be enabled in production. Supported main-application, CLI, Docker, and Compose launch paths use the main ARES application and normal lifecycle processing, so they remain fail-closed by default.

The guard trusts the supported ASGI server to execute application lifespan. Running the legacy target with lifespan disabled, including --lifespan off, is unsupported. Directly dispatching HTTP or WebSocket request scopes without managing lifespan is likewise unsupported and bypasses the startup guard. This is operational containment for supported startup behavior, not parity hardening or a security boundary against a malicious or privileged deployment operator who deliberately bypasses ASGI lifespan.

The explicit opt-in does not give the legacy application modern authentication, campaign-ownership, WebSocket, credential-transport, or deployment parity. Query-token exposure and its global live-WebSocket design remain. Full retirement is the preferred final control.

Tokens are issued by POST /auth/token with valid operator credentials (bcrypt-hashed password). Each login creates an independent refresh-token family with one active token, a 30-day absolute lifetime, and no sliding extension. Only lowercase SHA-256 token hashes are stored. Access JWTs contain sub, sid, ver, jti, iat, and exp; they contain no role claim. Current database user status, role, authentication epoch, family state, and JTI are authoritative on every bearer resolution. Default access expiry is one hour.

Browser refresh authority is transported only by a host-only HttpOnly cookie. Production uses __Host-ares-refresh and __Host-ares-csrf with Secure, SameSite=Strict, Path=/, and no Domain; access tokens remain memory-only. Every browser-auth mutation requires one exact configured HTTPS Origin and a constant-time match between the readable CSRF cookie and X-ARES-CSRF. Refresh-token JSON, header, query, and bearer fallbacks are rejected. Debug cookies use distinct names and are available only for the fixed loopback Vite origins under explicit debug mode. CORS remains noncredentialed and is not a browser-auth mechanism.

Refresh is a one-winner database transaction. The predecessor is consumed and exactly one child is inserted before commit; the raw child is returned only after commit. Reuse of a known consumed or revoked predecessor atomically revokes the complete family, including the committed winner after a concurrent or lost-response retry. Unknown random values reveal nothing and mutate nothing. POST /auth/logout revokes only the current family; POST /auth/logout-all, password changes/resets, role changes, and activation state changes increment the user epoch and revoke all families. Separate login families remain isolated, and API keys never enter refresh families.

Cookie publication follows the confirmed family commit. An indeterminate network result is not refreshed again: the browser clears memory authority and attempts one locked family logout before requiring sign-in. Active XSS can still act as the user and read the CSRF cookie; HttpOnly limits refresh-token exfiltration but does not claim to defeat active script, browser extensions, developer tools, or upstream traffic inspection.

Family lineage is retained until 30 days after the later of family expiry or revocation. Fixed security audit actions record login-family creation, rotation, replay revocation, current/all-device logout, and account security events without token, hash, family, user, SQL, or exception values.

Main WebSocket tickets

The supported main campaign WebSocket never accepts a bearer token or API key in its query string. A client authenticates POST /campaigns/{campaign_id}/websocket-ticket with the normal bearer or API-key header, then presents the returned ticket as the sole WebSocket query parameter. Tickets have a 30-second issuance lifetime, are bound to one campaign, and are globally single-use. A wrong-campaign presentation is denied without consuming the ticket; replay and every legacy token or api_key query form are denied.

Consumption is only the handshake authority. A connected socket retains an opaque consumed handle and ARES revalidates the original current user, bearer-expiry/JTI, API-key scope/lifetime/ownership, role, and campaign access before protected events. This resolution is read-only and remains possible after the ticket row expires or is purged. No registry entry retains a raw ticket, bearer, API key, ticket hash, or original query string.

Bearer-backed tickets also bind the user authentication epoch and refresh family. Family replay, logout, password/security events, expiry, or revocation therefore deny ticket consumption and terminate connected bearer sockets on the next heartbeat/event revalidation. API-key-backed tickets remain independent of refresh families.

Tickets remain visible to the browser and any upstream component that receives the handshake URL, so production clients must initiate HTTPS/WSS directly. The production nginx TLS log and port-80 redirect use $uri, which omits query strings; the redirect deliberately drops them. Production clients must still connect through HTTPS/WSS. The control does not claim to hide tickets from browser developer tools or arbitrary third-party proxies.

Backend and frontend rollout is atomic: drain existing main WebSockets, deploy both components together, and obtain a fresh ticket for every reconnect. Mixed old/new component versions are unsupported. A rollback replaces both together while leaving additive migrations installed. These controls do not change the default-disabled legacy dashboard WebSocket or repair its known limitations.

Authorization

ARES uses four account roles. Role values are lowercase in API requests: team_lead, operator, recon, and reporter.

Role Intended use Access model
team_lead Engagement lead or local administrator. Full API access, user registration, security audit, campaign deletion, restricted authorization, and normal operator work.
operator Day-to-day operator. Campaign workflows, module execution, reports, graph, artifacts, and core validation flows. Cannot register users.
recon Low-risk review/recon identity. Read-heavy access. The module permission matrix marks enumeration, fingerprint, and network modules as recon-safe, but the main dashboard execution endpoints are still operator-gated in this release.
reporter Reviewer or stakeholder. Read-only campaign/report/graph-style access. No module execution and no user administration.

The first account is bootstrapped as:

Username Role Password source
admin team_lead ARES_DEFAULT_ADMIN_PASSWORD

ARES creates that account only when the user table is empty. Changing ARES_DEFAULT_ADMIN_PASSWORD after the admin account exists does not reset the password. Use the Security page after login for normal password changes, or recreate the local ares.db only when disposable local dashboard data can be lost. Do not use local database reset guidance on real or shared deployments.

Additional accounts are created by a team_lead through POST /auth/register. The role is assigned at creation time:

POST /auth/register
Authorization: Bearer <team-lead-token>
Content-Type: application/json

{
  "username": "alice",
  "password": "StrongPass1!",
  "role": "operator"
}

Valid role values are team_lead, operator, recon, and reporter. Passwords must be at least 12 characters and include uppercase, lowercase, numeric, and special-character content. The Security dashboard can list users, but the current release does not expose a dashboard role editor for changing an existing account's role.

Rate limiting

  • Default: 100 requests/minute per token
  • Auth endpoint: 5 requests/minute per IP (lockout protection)
  • WebSocket: 1 connection per operator

Input validation

All request bodies validated by Pydantic v2 models. Any extra fields are rejected. SQL queries use parameterized statements via aiosqlite.

Security headers

X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'
Strict-Transport-Security: max-age=31536000

Scope Enforcement

Scope Firewall (Dual-Layer OS & Transport Egress Firewall)

ARES deploys a strict dual-layer Scope Firewall (ares.core.scope_firewall.ScopeFirewall and OSFirewallController) to enforce fail-closed scope boundaries:

  1. OS / Kernel-Level Packet Filtering (Elevated Mode):
    • When running with administrative privileges (Windows Administrator / Linux root), OSFirewallController interacts directly with OS network packet filtering (netsh advfirewall on Windows, iptables / ip6tables on Linux), establishing outbound firewall rules that physically block network egress outside campaign scope CIDRs.
    • Active Kernel State Verification: CLI return codes are not treated as proof of enforcement. ARES explicitly queries the live kernel/OS packet filtering state (iptables -C / ip6tables -C on Linux, netsh advfirewall firewall show rule on Windows) to verify that every subrule physically exists before transitioning to VERIFIED_ACTIVE. If verification fails, the state transitions to VERIFICATION_FAILED and all applied rules are immediately rolled back.
    • Resilient Cleanup Retention (CLEANUP_PENDING): In remove_rules() and emergency cleanup_all() (atexit), rules and cleanup commands are never purged from internal tracking upfront. If any cleanup command fails, the rule is retained in state tracking and the controller transitions to CLEANUP_PENDING (degraded mode), allowing cleanup retries and never falsely reporting INACTIVE while kernel rules may still exist.
    • Parent-Managed Firewall Lifecycle for Dropped Privileges: When drop_privileges=True is enabled on Linux, the child process running as nobody (UID 65534) lacks CAP_NET_ADMIN and cannot manipulate host packet filters. The elevated parent orchestrator installs the --uid-owner <nobody> Netfilter rules before spawning the child, enforcing the boundary physically in the Linux kernel the instant privileges drop, and tears down the rules in finally when the child terminates. The child process runs only Layer 2 in-process socket interception without attempting unprivileged OS firewall modifications.
    • External Binary & Process Descendant Confinement:
      • Linux Offline (allow_network=False): CLONE_NEWNET network namespace unshare creates an isolated network namespace with zero external interfaces, inherently confining the child process, all descendants, and any external binaries (e.g. curl, nmap) executed within it.
      • Linux Online (allow_network=True): Parent-managed --uid-owner <uid> Netfilter rules match all packets originating from that UID, confining external binaries launched by the sandbox child. Note: This is a host-wide UID boundary that affects all processes executing under that UID on the system.
      • Windows: Windows Defender Firewall CLI lacks per-PID and per-UID filtering. Rules are applied via program=<sys.executable>. While concurrent Python processes executing the exact same binary are restricted, external binaries (e.g. curl.exe, powershell.exe) do NOT match python.exe and are NOT restricted by the Windows Firewall rule. Operators requiring strict external binary confinement on Windows MUST execute modules inside the DOCKER tier.
    • Windows Executable-Path Matching Collateral Scope: Rules use program=<sys.executable> combined with mathematical complement CIDR block rules. Any concurrent process executing that exact python.exe executable during the rule's active lifetime is subject to egress blocking. Fail-safe transactional teardown (finally and atexit emergency cleanup) ensures rules are removed immediately upon task completion.
    • Transactional State Machine: State transitions strictly follow:
      UNINITIALIZED -> APPLYING -> (verify in OS) -> VERIFIED_ACTIVE -> INACTIVE
                                        ↓                                  ↑
                                VERIFICATION_FAILED ───────────────────────┤
                                        ↓                                  │
                                 CLEANUP_PENDING ──────────────────────────┘ (upon successful retry)
      
  2. In-Process Transport Socket Interceptor (Process Mode):
    • Hooks low-level socket and event loop connections (socket.connect, socket.sendto, socket.sendmsg, asyncio.create_connection) in Python user space, ensuring fail-closed scope enforcement even when running unprivileged without OS admin rights.
    • Fail-Closed Egress Blocking: Any out-of-scope connection attempt is instantly aborted with ScopeFirewallBlockError (status 403 Forbidden) and recorded in security audit logs.
    • Explicit Empty Scope Semantics (scope=[] vs scope=None): scope=None represents unconfigured scope; scope=[] explicitly activates fail-closed deny-all egress blocking, rejecting all external IPv4 and IPv6 network access while preserving internal loopback IPC.
    • ContextVar Task Isolation & Guaranteed Context Restoration: Active exclusively within the attack module execution coroutine. Structured nested try...finally blocks guarantee that the _current_firewall ContextVar always restores the exact previous context token (including nested outer guards and setup failures), preventing state leaks across async tasks.
    • DNS Re-entrancy & Rebinding Defense: Non-blocking hostname resolution checks resolved IPs against scope CIDRs, with an internal lock preventing recursive interception.
    • Loopback & Proactor IPC Safety: Exempts internal loopback (127.0.0.1, ::1) and Windows Proactor event loop named pipes.
    • Cloud Category Allowlist: Cloud modules (MODULE_CATEGORY == "cloud") are permitted to access official provider endpoints (*.microsoftonline.com, *.amazonaws.com, etc.) while blocking untrusted egress.

Sandbox Execution & Filesystem Isolation Semantics

ARES provides four isolation tiers (IsolationTier in ares.core.sandbox) with explicit boundary definitions:

  • DOCKER (Tier 3): Full OS container isolation. When allow_write=False, the root filesystem is mounted strictly read-only (read_only=True). When allow_network=False, container network mode is set to 'none'. CPU and memory quotas are enforced by kernel cgroups. Complete OS-level filesystem and external binary isolation is guaranteed exclusively at this tier.
  • SUBPROCESS (Tier 1 & 2): Separate child Python process. Working directory is locked to an ephemeral ares-sandbox-* temporary directory. On Unix, RLIMIT_FSIZE=(0,0) is applied to inhibit file enlargement.
    • Canonical Path Containment Defense-in-Depth: Application-level builtins.open and os.open hooks enforce canonical path containment (os.path.realpath + os.path.commonpath), strictly rejecting prefix-sibling attacks (e.g. /tmp/ares-sandbox-123-evil), symlink escapes, and relative directory traversals.
    • Technical Classification: Application-level open hooks are strictly classified as DEFENSE-IN-DEPTH for standard Python code. They do not constitute an impenetrable OS filesystem sandbox: native C/C++ extensions, direct syscalls, os.rename, os.replace, truncate, ftruncate, or file descriptors opened prior to sandboxing bypass Python-level hooks. Complete filesystem sandboxing requires Docker containers.
  • Privilege Dropping (drop_privileges=True): On Linux, child processes starting as root (EUID 0) drop privileges to nobody fail-closed (setgroups([]), setgid, setuid), verifying non-root UID before payload execution. On Windows, privilege dropping from Administrator is unsupported and execution is rejected fail-closed to prevent unconfined privileged execution.

CampaignGuardrail & Pre-Flight Scope Enforcement

Every module execution passes through comprehensive pre-flight verification:

  1. Recursive Parameter Target Scanner: Recursively extracts all target keys (target, targets, dc, host, rhost, rhosts, ip, server, destination, url) before module instantiation.
  2. Recon Module Scope Enforcement: Reconnaissance modules are strictly bound to campaign scope CIDRs.
  3. Sensitive Range Check: 169.254.0.0/16 (AWS IMDS), 127.0.0.0/8 (loopback) - always blocked for offensive targeting.
  4. Scope CIDR Check: Target must be within one of the campaign's declared scope CIDRs.
  5. Dangerous Module Confirmation: ad.dcsync, lateral.psexec, linux.container require confirmed=True.
allowed, reason = guardrail.check("ad.dcsync", "10.0.0.1")
# → False, "Module 'ad.dcsync' is HIGH-RISK. Pass confirmed=True to execute."

guardrail.confirm_dangerous("ad.dcsync", "10.0.0.1")
allowed, _ = guardrail.check("ad.dcsync", "10.0.0.1", confirmed=True)
# → True, "ok"

ScopeGuard (NoiseController)

At the module level, ScopeGuard.assert_in_scope(target) is called in BaseModule.before_request() before individual requests, raising ScopeError (aborting immediately without retry).


Audit Logging

All sensitive operations are written to the NDJSON audit log:

{"event": "campaign_started", "actor": "alice", "campaign_id": "abc123", "timestamp": "..."}
{"event": "module_executed", "actor": "alice", "module": "ad.dcsync", "target": "dc01", "..."}
{"event": "credential_added", "actor": "engine", "username": "CORP\\Administrator", "..."}
{"event": "checkpoint_saved", "actor": "alice", "campaign_id": "abc123", "path": "..."}
{"event": "operator_joined", "actor": "bob", "role": "recon", "campaign_id": "..."}

Audit log location follows the supported logging configuration: ARES writes audit.ndjson next to ARES_LOG_FILE (default: logs/audit.ndjson).

Sensitive field masking

Passwords, hashes, and secret keys are automatically masked:

# structlog processor strips these fields before writing
SENSITIVE_KEYS = {"password", "secret", "token", "hash", "key", "ntlm", "krb5"}

Module Marketplace Security

Signing

Each community module must be signed:

# Module author signs their module
ares-dev sign ./mymodule/ --key author.pem
# Produces manifest.json with "signature": "sha256:<hash>"

Verification

Before installation, ARES verifies:

  1. Manifest signature matches content hash
  2. Author public key is in the trusted keyring
  3. Module version matches the pinned version in manifest

Trusted registry

The default trusted registry is https://modules.ares-framework.io. Operators can configure a private registry:

[marketplace]
registry_url = "https://internal-registry.corp.local"
trusted_keys = ["/etc/ares/trusted-keys/"]

OpSec Posture

AccountLocked handling

When AccountLocked is raised, the engine:

  1. Immediately stops ALL further attempts against that account
  2. Marks the account as locked in OperatorSession
  3. Logs at ERROR level: account_locked event
  4. Notifies the operator via dashboard WebSocket

DetectionSignal handling

AdaptiveOpsecEngine monitors for:

  • 3 timeouts in 60s → escalate profile
  • 5 connection resets in 60s → blacklist host 5 min
  • 3 auth failures in 60s → stop account
  • RATE_LIMITED response → double jitter
  • SCAN_DETECTED → pause all activity, switch to stealth

HoneypotDetected handling

Campaign is paused immediately. Operator is notified. No further network activity until operator runs ares campaign resume --confirmed.


Responsible Use

ARES is intended for:

  • Authorized penetration testing engagements
  • Red team exercises with written client authorization
  • Purple team exercises and security training
  • Internal security research

Do not use ARES against systems you do not own or have explicit written permission to test.

Anthropic and the ARES authors take no responsibility for misuse.


C-LIVE-v1 execution authority

Execution is stricter than general API authentication. Only a current bearer principal may submit live work; API keys and raw credential material are denied. operator maps to lifecycle operator and team_lead to lifecycle team lead. reporter and recon are rejected before admission, and admin is never synthesized.

The bearer is revalidated before admission and again before queue ownership; each child and retry repeats that check. Point-in-time revocation is enforced, while transaction-linearizable revocation is outside this release. A canonical UUIDv4 Idempotency-Key names one immutable submission. Replays and changed-intent conflicts have zero new lifecycle/outbox delta, no target-module execution, and no handler-initiated broadcast.

The only authorized effect capability is a nonserializable, process-local, single-use seal issued after RUNNING/APPLIED. The subprocess stdin boundary rejects all payloads, production descriptors remain ineligible, and uncertain post-running work cannot auto-retry.