ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
"""
ARES ExecutionContext
A single, typed object passed to every module execution.
Replaces the scattered (settings, campaign, noise, **kwargs) pattern.
Before (v0.8.0):
module = KerberoastModule(settings=settings, campaign=campaign, noise=noise)
findings, extra = await module.run(dc="dc01.corp.local", domain="CORP")
After (v0.9.0):
ctx = ExecutionContext.build(campaign, target="dc01.corp.local",
params={"domain": "CORP"})
findings, extra = await module.run(ctx)
Benefits:
- Modules have a stable API surface regardless of engine changes
- Context carries all shared state: credentials, session, telemetry hook
- Validators can inspect the context before execution
- Replay engine can serialize/deserialize context for campaign replay
- Testing is trivial: just build a mock context
Context lifecycle:
Engine builds context
→ validates context (BaseModule.validate(ctx))
→ executes module (BaseModule.execute(ctx))
→ processes result (BaseModule.report(result, ctx))
→ updates session state
"""
from __future__ import annotations
import time
import uuid
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Generic, TypeVar
from ares.core.errors import InvalidContext
from ares.core.logger import get_logger
logger = get_logger("ares.core.context")
P = TypeVar("P")
T = TypeVar("T")
if TYPE_CHECKING:
from ares.credential.vault import Credential
from ares.state.target_state import HostState
@dataclass
class ExecutionContext(Generic[P]):
"""
Unified execution context passed to every module.
Immutable after construction (fields are set once by the engine).
Required fields:
target - IP address or hostname being attacked
campaign_id - which campaign this belongs to
module_id - which module will consume this context
Optional but strongly recommended:
credentials - ordered list of credentials to try
session - shared operator session (host states, attack history)
params - module-specific parameters
operator - operator username for audit logging
"""
# ── Identity ──────────────────────────────────────────────────────────
execution_id: str = field(default_factory=lambda: str(uuid.uuid4())[:12])
campaign_id: str = ""
module_id: str = ""
operator: str = "unknown"
# ── Target ────────────────────────────────────────────────────────────
target: str = "" # IP or hostname being attacked
domain: str = "" # AD domain (CORP.LOCAL)
port: int = 0 # specific port if protocol-targeted
# ── Parameters ────────────────────────────────────────────────────────
params: P | dict[str, Any] = field(default_factory=dict)
# ── Credentials ───────────────────────────────────────────────────────
# Ordered by score (highest first). Module tries each in order.
credentials: list[Any] = field(default_factory=list) # list[Credential]
primary_credential: Any = None # best credential to try first
# ── Shared state ──────────────────────────────────────────────────────
# These are references - mutations visible to engine after execution
session: Any = None # OperatorSession
vault: Any = None # CredentialVault
artifact_store: Any = None # ArtifactStore
runtime_state: Any = None # CampaignRuntimeState
# ── Engine references ─────────────────────────────────────────────────
settings: Any = None # AresSettings
campaign: Any = None # Campaign
noise: Any = None # NoiseController
telemetry: Any = None # TelemetryCollector
# ── OpSec ─────────────────────────────────────────────────────────────
opsec_profile: str = "normal" # stealth | normal | aggressive
max_retries: int = 3
timeout_s: int = 300
# ── Audit ─────────────────────────────────────────────────────────────
created_at: float = field(default_factory=time.time)
dry_run: bool = False # simulation mode - no real network calls
network_io_occurred: bool = False
def mark_network_io_occurred(self, occurred: bool = True) -> None:
"""Mark that genuine network I/O has occurred within this execution context."""
self.network_io_occurred = occurred
# ── Metadata ──────────────────────────────────────────────────────────
tags: list[str] = field(default_factory=list)
extra: dict[str, Any] = field(default_factory=dict)
findings: list[Any] = field(default_factory=list)
collected_loot: list[Any] = field(default_factory=list)
# ── Validation ────────────────────────────────────────────────────────
def require(self, *fields: str) -> None:
"""
Assert that required fields are present.
Called by BaseModule.validate() to check context completeness.
Usage:
ctx.require("target", "domain", "credentials")
Raises:
InvalidContext if any field is empty/None
"""
for f in fields:
val = getattr(self, f, None)
if val is None or val == "" or val == []:
raise InvalidContext(
f"ExecutionContext missing required field: {f!r}",
module_id=self.module_id,
missing_field=f,
)
def has(self, *fields: str) -> bool:
"""Check if optional fields are populated."""
return all(
getattr(self, f, None) not in (None, "", [])
for f in fields
)
# ── Fluent helpers (v2 Modern SDK) ────────────────────────────────────
def typed_params(self, model_cls: type[T]) -> T:
"""Parse, validate, and return params as a typed Pydantic model."""
from ares.sdk.params import validate_params
return validate_params(model_cls, self.params, module_id=self.module_id)
def emit_finding(
self,
title: str,
severity: Any,
description: str = "",
mitre_technique: str | None = None,
mitre_tactic: str | None = None,
evidence: dict[str, Any] | None = None,
remediation: str = "",
host: str | None = None,
confidence: float = 1.0,
) -> Any:
"""Fluent helper to create and record a finding in the execution context."""
from ares.core.campaign import Finding, Severity
sev = severity if isinstance(severity, Severity) else Severity(str(severity).lower())
desc = description.strip() if (description and description.strip()) else (title.strip() or "Finding emitted")
finding = Finding(
id=str(uuid.uuid4()),
title=title,
description=desc,
severity=sev,
mitre_technique=mitre_technique,
mitre_tactic=mitre_tactic,
evidence=evidence or {},
remediation=remediation,
host=host or self.target,
confidence=confidence,
module_id=self.module_id,
)
if self.runtime_state and hasattr(self.runtime_state, "record_finding"):
try:
self.runtime_state.record_finding(finding)
except Exception as exc:
logger.error(
"runtime_state_record_finding_failed",
finding_id=finding.id,
title=finding.title,
module_id=self.module_id,
error=str(exc),
exc_info=True,
)
return False
self.findings.append(finding)
return finding
# Alias for API consistency and backwards compatibility
record_finding = emit_finding
def store_artifact(self, artifact: Any) -> Any:
"""Store an artifact in the execution context's artifact store if available."""
if self.artifact_store and hasattr(self.artifact_store, "add"):
return self.artifact_store.add(artifact)
return None
def record_credential(
self,
username: str,
secret: str = "",
domain: str = "",
cred_type: str = "password",
metadata: dict[str, Any] | None = None,
io_verified: bool | None = None,
target: str = "",
privilege: str = "",
source: str = "",
**kwargs: Any,
) -> Any:
"""Store a discovered credential in the context vault if available (protected by Gate 6)."""
has_io = (
io_verified
if io_verified is not None
else (
self.network_io_occurred
or bool(self.findings)
or bool(self.collected_loot)
or bool(self.telemetry and getattr(self.telemetry, "network_bytes_sent", 0) > 0)
)
)
if not has_io:
logger.warning(
"vault_write_blocked_zero_io",
username=username,
cred_type=cred_type,
module_id=self.module_id,
reason="no network I/O or evidence recorded in execution context",
)
return False
if self.vault and hasattr(self.vault, "add"):
try:
return self.vault.add(
username=username,
secret=secret,
domain=domain or self.domain,
cred_type=cred_type,
host=target or self.target,
target_host=target or self.target,
privilege=privilege or "user",
source_module=source or self.module_id,
metadata=metadata or {},
io_verified=has_io,
ctx=self,
**kwargs,
)
except Exception as exc:
logger.error(
"vault_record_credential_failed",
username=username,
cred_type=str(cred_type),
module_id=self.module_id,
error=str(exc),
exc_info=True,
)
return False
return None
def record_loot(
self,
name: str,
content: Any,
loot_type: str = "artifact",
description: str = "",
path_on_target: str = "",
tags: list[str] | None = None,
) -> Any:
"""Record harvested loot artifact to be persisted durably."""
import uuid
from ares.db.database import Loot
campaign_id = getattr(getattr(self, "campaign", None), "id", "")
item = Loot(
id=f"loot_{uuid.uuid4().hex[:12]}",
campaign_id=campaign_id,
host_id=getattr(self, "target", "") or None,
loot_type=loot_type,
name=name,
description=description,
content=content,
path_on_target=path_on_target,
source_module=getattr(self, "module_id", ""),
tags=tags or [],
)
self.collected_loot.append(item)
return item
# ── Accessors ─────────────────────────────────────────────────────────
def best_credential(self) -> "Credential | None":
"""Return highest-scored credential, or primary_credential if set."""
if self.primary_credential:
return self.primary_credential
if self.credentials:
return self.credentials[0]
return None
def host_state(self) -> "HostState | None":
"""Retrieve current host state from session, if session available."""
if self.session and self.target:
return self.session.get_host(self.target)
return None
def record_metric(self, metric: str, value: float) -> None:
"""Record an execution metric in telemetry, if collector available."""
if self.telemetry:
self.telemetry.record_execution(
self.module_id, value, success=True, campaign_id=self.campaign_id
)
# ── Serialization ─────────────────────────────────────────────────────
def to_dict(self) -> dict[str, Any]:
"""
Serialize context for audit logging and replay.
Sensitive fields (credentials, vault) are excluded.
"""
return {
"execution_id": self.execution_id,
"campaign_id": self.campaign_id,
"module_id": self.module_id,
"operator": self.operator,
"target": self.target,
"domain": self.domain,
"port": self.port,
"params": self.params,
"opsec_profile": self.opsec_profile,
"dry_run": self.dry_run,
"created_at": self.created_at,
"tags": self.tags,
"has_credentials": len(self.credentials) > 0,
"has_session": self.session is not None,
"has_artifact_store": self.artifact_store is not None,
}
@classmethod
def build(
cls,
campaign: Any,
target: str,
module_id: str,
params: dict[str, Any] | None = None,
domain: str = "",
port: int = 0,
operator: str = "",
credentials: list[Any] | None = None,
session: Any = None,
vault: Any = None,
artifact_store: Any = None,
runtime_state: Any = None,
settings: Any = None,
noise: Any = None,
telemetry: Any = None,
opsec_profile: str = "normal",
timeout_s: int = 300,
dry_run: bool = False,
tags: list[str] | None = None,
) -> "ExecutionContext":
"""
Factory method - preferred way to create an ExecutionContext.
Derives campaign_id and operator from the Campaign object.
"""
return cls(
campaign_id = getattr(campaign, "id", "") if campaign else "",
module_id = module_id,
operator = operator or getattr(campaign, "operator", "unknown"),
target = target,
domain = domain or (params or {}).get("domain", "") or getattr(campaign, "domain", ""),
port = port,
params = params or {},
credentials = credentials or [],
session = session,
vault = vault,
artifact_store = artifact_store,
runtime_state = runtime_state,
settings = settings,
campaign = campaign,
noise = noise,
telemetry = telemetry,
opsec_profile = opsec_profile,
timeout_s = timeout_s,
dry_run = dry_run,
tags = tags or [],
)
@classmethod
def for_test(
cls,
target: str = "10.0.0.1",
module_id: str = "test.module",
params: dict[str, Any] | None = None,
dry_run: bool = True,
) -> "ExecutionContext":
"""
Build a minimal context for unit testing.
Sets dry_run=True so no real network calls are made.
"""
return cls(
target=target, module_id=module_id,
params=params or {}, campaign_id="test",
operator="test", dry_run=dry_run,
)
def __repr__(self) -> str:
return (
f"ExecutionContext(id={self.execution_id!r}, "
f"module={self.module_id!r}, target={self.target!r}, "
f"profile={self.opsec_profile!r}, dry_run={self.dry_run})"
)