ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix: normalize module contracts and dry-run outcomes
Mafifrizi69b027ebd5b4
diff --git a/ares/api/server.py b/ares/api/server.pyindex 10f8b76..b02034f 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -57,6 +57,7 @@ from ares.core.config import AresSettings, get_settingsfrom ares.core.engine import AresEnginefrom ares.core.logger import get_loggerfrom ares.core.security import create_access_token+from ares.modules.base import normalize_module_metadatafrom ares.core.tracing import get_current_trace_id, instrument_fastapi, setup_tracingfrom ares.db.database import AresDatabase@@ -1188,10 +1189,13 @@ async def list_modules()cls = engine.registry.get(str(module_id)) if module_id else Noneparams_model = MODULE_PARAMS.get(str(module_id))- module_meta["param_schema"] = (+ param_schema = (params_model.schema_for_api() if params_model else {})if cls:+ module_meta = normalize_module_metadata(+ cls, param_schema=param_schema, base=module_meta+ )module_meta.setdefault("category", getattr(cls, "MODULE_CATEGORY", ""))module_meta.setdefault("description", getattr(cls, "MODULE_DESCRIPTION", "")@@ -1202,6 +1206,8 @@ async def list_modules(mitre = list(getattr(cls, "MITRE_TECHNIQUES", []))module_meta.setdefault("mitre_list", mitre)module_meta.setdefault("mitre", ", ".join(mitre))+ else:+ module_meta["param_schema"] = param_schemaenriched.append(module_meta)return enriched@@ -1252,6 +1258,13 @@ async def run_module({"field": ".".join(str(x) for x in e["loc"]), "msg": e["msg"]}for e in exc.errors()]+ if body.dry_run:+ missing = [item["field"] for item in errors]+ return engine.dry_run_module(+ module_id,+ body.params,+ missing_params=missing,+ )raise HTTPException(status_code=422,detail={@@ -1285,10 +1298,7 @@ async def run_module(# Dry-run: validate + preview without touching targetif getattr(body, "dry_run", False):- from ares.core.engine import ExecutionPlan-- p_plan = ExecutionPlan().add_stage("run", [module_id])- return engine.dry_run_plan(p_plan, safe_params)+ return engine.dry_run_module(module_id, safe_params)result = await engine.run_module(module_id, c_obj, safe_params, actor_role=actor.rolediff --git a/ares/core/engine.py b/ares/core/engine.pyindex 8f04bb0..2ddfd65 100644--- a/ares/core/engine.py+++ b/ares/core/engine.py@@ -5,6 +5,7 @@ Full async orchestration with parallel module execution.from __future__ import annotationsimport asyncio+import reimport timefrom dataclasses import dataclass, fieldfrom enum import Enum@@ -35,6 +36,131 @@ class ModuleStatus(str, Enum):TIMEOUT = "timeout"+MODULE_OUTCOMES = (+ "confirmed_findings",+ "completed_no_findings",+ "operator_error",+ "dependency_error",+ "network_error",+ "unsupported",+ "module_error",+)+_SECRET_ERROR_PATTERN = re.compile(+ r"(?i)\b(password|passwd|secret|token|api[_-]?key|nt_hash|lm_hash|krbtgt_hash)\b\s*([:=])\s*([^\s,;]+)"+)+++def redact_error_message(error: str | None) -> str | None:+ """Bound and redact common secret key/value forms in engine errors."""+ if not error:+ return error+ text = str(error)[:300]+ return _SECRET_ERROR_PATTERN.sub(+ lambda match: f"{match.group(1)}{match.group(2)}[redacted]", text+ )+++def normalize_module_outcome(+ status: ModuleStatus | str,+ findings: list[Any] | None = None,+ error: str | None = None,+ raw_output: dict[str, Any] | None = None,+) -> tuple[str, str]:+ """Map engine results to a stable operator-facing outcome contract."""+ findings = findings or []+ raw = raw_output or {}+ raw_outcome = str(raw.get("outcome_category", ""))+ raw_message = str(raw.get("outcome_message", "")).strip()++ if findings:+ return "confirmed_findings", f"{len(findings)} confirmed finding(s) returned."+ if raw_outcome in MODULE_OUTCOMES:+ if raw_message:+ return raw_outcome, raw_message+ return raw_outcome, raw_outcome.replace("_", " ").capitalize() + "."++ status_value = status.value if isinstance(status, ModuleStatus) else str(status)+ error_text = str(error or "").strip()+ lowered = error_text.lower()+ if status_value == ModuleStatus.TIMEOUT.value or any(+ marker in lowered+ for marker in ("timed out", "timeout", "unreachable", "connection refused", "network")+ ):+ outcome = "network_error"+ default_message = "The module could not complete because the target or network was unavailable."+ elif any(+ marker in lowered+ for marker in (+ "dependency",+ "not installed",+ "no module named",+ "impacket",+ "pyasn1",+ "ldap3",+ )+ ):+ outcome = "dependency_error"+ default_message = "The module dependency check failed."+ elif status_value == ModuleStatus.SKIPPED.value or any(+ marker in lowered for marker in ("unsupported", "blocked", "not permitted")+ ):+ outcome = "unsupported"+ default_message = "The module is unsupported or blocked for this run."+ elif status_value == ModuleStatus.FAILED.value and any(+ marker in lowered+ for marker in ("validation", "required", "scope", "credential", "auth", "role")+ ):+ outcome = "operator_error"+ default_message = "Review the module inputs, authorization, and campaign scope."+ elif status_value == ModuleStatus.DONE.value:+ outcome = "completed_no_findings"+ default_message = (+ "Module completed; no confirmed findings or exploitable condition was observed."+ )+ else:+ outcome = "module_error"+ default_message = "The module failed before producing a confirmed result."++ if error_text:+ return outcome, f"{default_message} Details: {error_text[:300]}"+ return outcome, default_message+++def redact_module_params(module_id: str, params: dict[str, Any]) -> dict[str, Any]:+ """Return a JSON-safe parameter summary with credential material redacted."""+ secret_fields: set[str] = set()+ try:+ from ares.modules.params import MODULE_PARAMS++ model = MODULE_PARAMS.get(module_id)+ if model:+ secret_fields = {+ name+ for name, field in model.schema_for_api().items()+ if field.get("secret")+ }+ except (ImportError, AttributeError):+ pass++ secret_names = secret_fields | {+ "password", "secret", "token", "api_key", "private_key",+ "nt_hash", "lm_hash", "krbtgt_hash", "ssh_pass", "access_key", "secret_key",+ }++ def _copy(name: str, value: Any) -> Any:+ if name in secret_names:+ return "[redacted]"+ if isinstance(value, dict):+ return {str(key): _copy(str(key), item) for key, item in value.items()}+ if isinstance(value, (list, tuple)):+ return [_copy(name, item) for item in value]+ if value is None or isinstance(value, (str, int, float, bool)):+ return value+ return str(value)++ return {str(key): _copy(str(key), value) for key, value in params.items()}++class EngineModuleResult(BaseModel):module_id: strstatus: ModuleStatus = ModuleStatus.DONE@@ -43,6 +169,20 @@ class EngineModuleResult(BaseModel):raw_output: dict[str, Any] = {}error: str | None = Noneduration_ms: float = 0.0+ outcome: str = ""+ outcome_message: str = ""++ def model_post_init(self, __context: Any) -> None:+ self.error = redact_error_message(self.error)+ if not self.outcome or not self.outcome_message:+ outcome, message = normalize_module_outcome(+ self.status,+ self.findings,+ self.error,+ self.raw_output,+ )+ self.outcome = self.outcome or outcome+ self.outcome_message = self.outcome_message or message@propertydef confirmed_findings(self) -> list[Finding]:@@ -647,7 +787,17 @@ class AresEngine:if not cls:param_errors.append({"module_id": mid, "field": "(module)","error": f"Module '{mid}' not found in registry"})- stage_info["modules"].append({"module_id": mid, "status": "not_found"})+ stage_info["modules"].append({+ "module_id": mid,+ "status": "not_found",+ "dry_run_status": "dry_run_unsupported",+ "validated_params_summary": redact_module_params(mid, {**gp, **sp.get(mid, {})}),+ "missing_params": [],+ "missing_dependencies": [],+ "would_execute": False,+ "warnings": ["The module is not present in the loaded registry."],+ "operator_next_steps": ["Refresh the module catalog or check module installation."],+ })continuemerged = {**gp, **sp.get(mid, {})}@@ -668,6 +818,12 @@ class AresEngine:passopsec = getattr(cls, "OPSEC_LEVEL", "?")+ dry_run_supported = bool(getattr(cls, "DRY_RUN_SUPPORTED", True))+ module_dry_status = (+ "dry_run_blocked" if mod_errors+ else "dry_run_ok" if dry_run_supported+ else "dry_run_unsupported"+ )stage_info["modules"].append({"module_id": mid,"opsec_level": opsec.value if hasattr(opsec, "value") else str(opsec),@@ -676,12 +832,23 @@ class AresEngine:"mitre": getattr(cls, "MITRE_TECHNIQUES", []),"missing_params": mod_errors,"status": "error" if mod_errors else "ready",+ "dry_run_status": module_dry_status,+ "validated_params_summary": redact_module_params(mid, merged),+ "missing_dependencies": [],+ "would_execute": module_dry_status == "dry_run_ok",+ "warnings": [+ "Dry-run validates the plan only; no module code contacts a target."+ ],+ "operator_next_steps": [+ "Review parameters and campaign scope before live execution."+ ],})stages_out.append(stage_info)return {"dry_run": True,+ "status": "dry_run_blocked" if param_errors else "dry_run_ok","plan": stages_out,"param_validation": {"ok": len(param_errors) == 0,@@ -698,6 +865,75 @@ class AresEngine:},}+ def dry_run_module(+ self,+ module_id: str,+ params: dict[str, Any] | None = None,+ missing_params: list[str] | None = None,+ ) -> dict[str, Any]:+ """Return a side-effect-free, stable preview for one module run."""+ raw_params = params or {}+ cls = self.registry.get(module_id)+ summary = redact_module_params(module_id, raw_params)+ if cls is None:+ return {+ "dry_run": True,+ "status": "dry_run_unsupported",+ "module_id": module_id,+ "validated_params_summary": summary,+ "missing_params": list(missing_params or []),+ "missing_dependencies": [],+ "would_execute": False,+ "warnings": ["The module is not present in the loaded registry."],+ "operator_next_steps": ["Refresh the module catalog or check module installation."],+ }++ supported = bool(getattr(cls, "DRY_RUN_SUPPORTED", True))+ if not supported:+ return {+ "dry_run": True,+ "status": "dry_run_unsupported",+ "module_id": module_id,+ "validated_params_summary": summary,+ "missing_params": list(missing_params or []),+ "missing_dependencies": [],+ "would_execute": False,+ "warnings": ["This module does not advertise a safe dry-run path."],+ "operator_next_steps": ["Review the module documentation before an authorized live run."],+ }++ missing = list(missing_params or [])+ if missing:+ return {+ "dry_run": True,+ "status": "dry_run_blocked",+ "module_id": module_id,+ "validated_params_summary": summary,+ "missing_params": missing,+ "missing_dependencies": [],+ "would_execute": False,+ "warnings": ["Required parameters are missing; no module code was executed."],+ "operator_next_steps": ["Provide the missing parameters and run dry-run again."],+ }++ warnings = ["Dry-run validates the request only; it does not contact the target."]+ if getattr(getattr(cls, "OPSEC_LEVEL", None), "value", "") == "high_noise":+ warnings.append("The selected module is high-noise and remains role/OPSEC guarded.")+ return {+ "dry_run": True,+ "status": "dry_run_ok",+ "module_id": module_id,+ "validated_params_summary": summary,+ "missing_params": [],+ "missing_dependencies": [],+ "would_execute": True,+ "warnings": warnings,+ "operator_next_steps": [+ "Review the validated parameters and campaign scope.",+ "Disable dry-run only after confirming authorization.",+ ],+ }+async def _persist_vault_credentials(self, campaign: "Campaign") -> int:"""Sync in-memory CredentialVault to the DB after each module run.diff --git a/ares/modules/ad/asreproast.py b/ares/modules/ad/asreproast.pyindex 3659815..e98d8ba 100644--- a/ares/modules/ad/asreproast.py+++ b/ares/modules/ad/asreproast.py@@ -123,6 +123,28 @@ def _format_krb5asrep_hash(raw_asrep: bytes, username: str, domain: str) -> str:return ""+def classify_asrep_outcome(+ mode: str, candidate_count: int, hash_count: int+) -> tuple[str, str]:+ """Explain an AS-REP run that did not produce a confirmed finding."""+ if hash_count:+ return "confirmed_findings", f"Captured {hash_count} AS-REP roastable result(s)."+ if candidate_count:+ return (+ "completed_no_findings",+ f"LDAP found {candidate_count} candidate account(s), but no AS-REP roast material was obtained; the condition was not confirmed.",+ )+ if mode == "authenticated":+ return (+ "completed_no_findings",+ "LDAP completed successfully; no accounts without Kerberos pre-auth were found.",+ )+ return (+ "completed_no_findings",+ "The username input completed without AS-REP roast material; no condition was confirmed.",+ )++class ASREPRoastModule(BaseModule):"""ad.asreproast — Capture AS-REP hashes from accounts without Kerberos pre-auth@@ -230,6 +252,7 @@ class ASREPRoastModule(BaseModule):logger.info("asreproast_start", dc=dc, domain=domain, mode=mode)+ self._last_candidate_count = 0try:hashes, accounts = await self._get_asrep_hashes(dc, domain, username, password, userfile, usernames or [], mode@@ -240,7 +263,17 @@ class ASREPRoastModule(BaseModule):from ares.core.errors import NetworkErrorraise NetworkError(f"ASREPRoast failed: {exc}") from exc- raw = {"asrep_hashes": hashes, "vulnerable_accounts": accounts, "mode": mode}+ raw = {+ "asrep_hashes": hashes,+ "vulnerable_accounts": accounts,+ "mode": mode,+ }+ if not hashes:+ category, message = classify_asrep_outcome(+ mode, self._last_candidate_count, len(hashes)+ )+ raw["outcome_category"] = category+ raw["outcome_message"] = messageself._analyze(raw)return self._findings, raw@@ -277,6 +310,8 @@ class ASREPRoastModule(BaseModule):else:targets = list(usernames)+ self._last_candidate_count = len(targets)+if not targets:return [], []diff --git a/ares/modules/ad/enum_spn.py b/ares/modules/ad/enum_spn.pyindex 0c4afb9..fd6a1dd 100644--- a/ares/modules/ad/enum_spn.py+++ b/ares/modules/ad/enum_spn.py@@ -27,6 +27,16 @@ def _days_since_ts(ts):return max(0,(datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)-dt).days)except Exception: return None++def classify_enum_spn_outcome(spn_count: int) -> tuple[str, str]:+ """Explain whether LDAP found any service principal candidates."""+ if spn_count:+ return "confirmed_findings", f"Found {spn_count} service principal candidate(s)."+ return (+ "completed_no_findings",+ "LDAP completed successfully; no enabled user accounts with service principals were found.",+ )+class ADEnumSPNModule(BaseModule):"""ad.enum_spn — Find SPN accounts (Kerberoasting candidates)@@ -112,7 +122,12 @@ class ADEnumSPNModule(BaseModule):except Exception as exc:from ares.core.errors import NetworkErrorraise NetworkError(f"LDAP SPN failed: {exc}") from exc- raw = {"spn_list": spns}+ category, message = classify_enum_spn_outcome(len(spns))+ raw = {+ "spn_list": spns,+ "outcome_category": category,+ "outcome_message": message,+ }# ISU-07: produce UserArtifact objects (is_kerberoastable=True)try:from ares.normalize.artifacts import UserArtifact, ArtifactStorediff --git a/ares/modules/ad/kerberoast.py b/ares/modules/ad/kerberoast.pyindex 68a9722..a5c904b 100644--- a/ares/modules/ad/kerberoast.py+++ b/ares/modules/ad/kerberoast.py@@ -47,6 +47,28 @@ def _format_krb5tgs_hash(tgs: bytes, cipher: "Any", spn: str, domain: str) -> stexcept Exception:return ""++def classify_kerberoast_outcome(+ spn_count: int, hash_count: int, request_failures: int = 0+) -> tuple[str, str]:+ """Explain a Kerberoast run that did not produce a confirmed finding."""+ if hash_count:+ return "confirmed_findings", f"Captured {hash_count} TGS roastable result(s)."+ if request_failures:+ return (+ "network_error",+ f"Found {spn_count} SPN candidate(s), but TGS collection failed for {request_failures} request(s).",+ )+ if spn_count:+ return (+ "completed_no_findings",+ f"Found {spn_count} SPN candidate(s), but no TGS roast material was obtained; the condition was not confirmed.",+ )+ return (+ "completed_no_findings",+ "LDAP completed successfully; no service principal candidates were found.",+ )+class KerberoastModule(BaseModule):"""ad.kerberoast — Request TGS tickets for SPN accounts — hashcat-ready hashes@@ -146,6 +168,8 @@ class KerberoastModule(BaseModule):return [], {"skipped": True, "reason": "stealth_profile_too_noisy"}await self.before_request(dc, "kerberos_tgs")logger.info("kerberoast_start", dc=dc, domain=domain, target=target_user)+ self._last_spn_count = 0+ self._last_tgs_failures = 0try:hashes, accounts = await self._request_tickets(dc, username, password, domain, target_user)except AresError:@@ -162,7 +186,19 @@ class KerberoastModule(BaseModule):service="Kerberos",) from excraise NetworkError(f"Kerberoast failed: {exc}") from exc- raw = {"kerberos_hashes": hashes, "accounts": accounts, "noise_level": self.campaign.noise_profile.value}+ raw = {+ "kerberos_hashes": hashes,+ "accounts": accounts,+ "noise_level": self.campaign.noise_profile.value,+ }+ if not hashes:+ category, message = classify_kerberoast_outcome(+ self._last_spn_count,+ len(hashes),+ self._last_tgs_failures,+ )+ raw["outcome_category"] = category+ raw["outcome_message"] = messageself._analyze(raw)return self._findings, raw@@ -240,6 +276,8 @@ class KerberoastModule(BaseModule):except Exception as exc:logger.warning("kerberoast_spn_lookup_failed", error=str(exc)[:80])+ self._last_spn_count = len(spn_list)+if not spn_list:return [], []@@ -276,6 +314,7 @@ class KerberoastModule(BaseModule):"hash": hash_str[:60] + "...",})except Exception as exc:+ self._last_tgs_failures += 1logger.debug("kerberoast_tgs_failed", spn=spn, error=str(exc)[:80])# Bug 2+3: jitter per-ticket + explicit rate-limit sleepdiff --git a/ares/modules/base.py b/ares/modules/base.pyindex 08fa06b..7b66f0d 100644--- a/ares/modules/base.py+++ b/ares/modules/base.py@@ -43,6 +43,91 @@ if TYPE_CHECKING:logger = get_logger("ares.module")+MODULE_OUTCOME_SEMANTICS = [+ "confirmed_findings",+ "completed_no_findings",+ "operator_error",+ "dependency_error",+ "network_error",+ "unsupported",+ "module_error",+]+MODULE_SAFE_ERROR_CATEGORIES = [+ "operator_error",+ "dependency_error",+ "network_error",+ "unsupported",+ "module_error",+]+++def normalize_module_metadata(+ cls: Any,+ *,+ param_schema: dict[str, Any] | None = None,+ base: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Return the stable metadata contract exposed by the registry and API."""+ metadata = dict(base or {})++ if param_schema is None:+ try:+ from ares.modules.params import MODULE_PARAMS++ params_model = MODULE_PARAMS.get(str(getattr(cls, "MODULE_ID", "")))+ param_schema = params_model.schema_for_api() if params_model else {}+ except (ImportError, AttributeError):+ param_schema = {}++ schema = param_schema or {}+ required_params = [+ name for name, field in schema.items() if bool(field.get("required"))+ ]+ optional_params = [+ name for name, field in schema.items() if not bool(field.get("required"))+ ]+ defaults = {+ name: field["default"]+ for name, field in schema.items()+ if "default" in field and field.get("default") is not None+ }++ def _list_attr(name: str, default: list[str]) -> list[str]:+ value = getattr(cls, name, default)+ if isinstance(value, str):+ return [value]+ return list(value or [])++ for key, attr, fallback in (+ ("id", "MODULE_ID", ""),+ ("name", "MODULE_NAME", ""),+ ("category", "MODULE_CATEGORY", ""),+ ("description", "MODULE_DESCRIPTION", ""),+ ):+ if not metadata.get(key):+ metadata[key] = getattr(cls, attr, fallback)++ metadata.setdefault("required_params", required_params)+ metadata.setdefault("optional_params", optional_params)+ metadata.setdefault("defaults", defaults)+ metadata.setdefault("capability_flags", _list_attr("CAPABILITIES", []))+ metadata.setdefault(+ "dry_run_supported", bool(getattr(cls, "DRY_RUN_SUPPORTED", True))+ )+ metadata.setdefault(+ "supported_modes", _list_attr("SUPPORTED_MODES", ["standard"])+ )+ metadata.setdefault(+ "dependency_notes", _list_attr("DEPENDENCY_NOTES", [])+ )+ metadata.setdefault("outcome_semantics", list(MODULE_OUTCOME_SEMANTICS))+ metadata.setdefault(+ "safe_error_categories", list(MODULE_SAFE_ERROR_CATEGORIES)+ )+ metadata["param_schema"] = schema+ return metadata++# ── OpSec level enum ──────────────────────────────────────────────────────────class OpsecLevel(str, Enum):@@ -218,6 +303,10 @@ class BaseModule(abc.ABC):MITRE_TECHNIQUES: list[str] = []MODULE_AUTHOR: str = "ARES Team"MIN_NOISE_PROFILE: str | None = None # None = runs in any profile+ CAPABILITIES: list[str] = []+ DRY_RUN_SUPPORTED: bool = True+ SUPPORTED_MODES: list[str] = ["standard"]+ DEPENDENCY_NOTES: list[str] = []# Per-module timeout override (seconds). None = use engine default (120s).# Set higher for slow ops: dcsync on WAN, lsass_dump transfer, crack jobs.@@ -382,7 +471,7 @@ class BaseModule(abc.ABC):@classmethoddef metadata(cls) -> dict[str, Any]:"""Return full module metadata as a dict (used by registry + API)."""- return {+ return normalize_module_metadata(cls, base={"id": cls.MODULE_ID,"name": cls.MODULE_NAME,"category": cls.MODULE_CATEGORY,@@ -395,7 +484,7 @@ class BaseModule(abc.ABC):"author": cls.MODULE_AUTHOR,"min_noise_profile": cls.MIN_NOISE_PROFILE,"required_privilege": getattr(cls, "REQUIRED_PRIVILEGE", None),- }+ })@classmethoddef can_run_with_noise(cls, noise_profile: str) -> bool:diff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.mdindex 84fe333..11b22d7 100644--- a/docs/dashboard-guide.md+++ b/docs/dashboard-guide.md@@ -268,7 +268,7 @@ Use it for:- Run with `dry_run` enabled by default.- Confirm high-noise or sensitive execution when required.- Watch the run button/loading state while backend execution is in progress.-- Review validation and scope errors without checking the terminal.+- Review the backend outcome label and message without checking the terminal.Good habit:@@ -279,6 +279,11 @@ Good habit:5. Review validation output.6. Run live only if authorized.+Results distinguish confirmed findings, completed runs with no confirmed+findings, operator/dependency/network errors, unsupported runs, and unexpected+module errors. A dry-run result is a validation preview only; it is not evidence+that the target is vulnerable or reachable.+Scope behavior:- Targeted modules can run only against targets inside the selected campaigndiff --git a/docs/modules.md b/docs/modules.mdindex b753927..7b70451 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -28,6 +28,34 @@ The dashboard and API enforce authentication, RBAC, scope validation, parametervalidation, rate limits, and token revocation. The frontend is a conveniencelayer; the backend remains the enforcement boundary.+## Dry-Run and Outcomes++The module catalog is the source of truth for required and optional parameters,+defaults, capability labels, supported modes, dependency notes, and whether a+safe dry-run is supported. A module dry-run validates the request and campaign+context only; it does not contact a target or perform module actions. The API+returns `dry_run_ok`, `dry_run_blocked`, or `dry_run_unsupported` with a+redacted parameter summary, missing inputs, warnings, and next steps.++Live results use these outcome labels:++- `confirmed_findings`: confirmed observations were returned.+- `completed_no_findings`: execution completed, but no exploitable condition was+ confirmed. This is different from a failed run.+- `operator_error`: review inputs, authorization, credentials, or scope.+- `dependency_error`: an optional runtime dependency is unavailable.+- `network_error`: the target or network could not be reached or completed.+- `unsupported`: the module or requested mode is blocked or unavailable.+- `module_error`: the module failed unexpectedly; preserve the displayed error+ when troubleshooting.++For AD modules, an LDAP-success result can still be `completed_no_findings`:+`ad.asreproast` explains whether candidates were found without AS-REP material,+`ad.enum_spn` reports when no SPN candidates matched, and `ad.kerberoast`+distinguishes no SPNs, no TGS material, and TGS collection failures. On Windows+with a source/local Impacket install, use `.[ad-support]` for the direct AD+support libraries and follow the doctor/setup guidance for Python 3.12.x.+## How Modules Are Used### Dashboard Flowdiff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 134eee8..c2290ba 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1090,7 +1090,8 @@ function ModulesPage() {);});const sensitive = isSensitiveModule(selected);- const canRun = Boolean(campaignId && selectedId) && (!sensitive || confirmed) && !run.isPending;+ const dryRunSupported = selected?.dry_run_supported !== false;+ const canRun = Boolean(campaignId && selectedId) && (!sensitive || confirmed) && !run.isPending && (!dryRun || dryRunSupported);const runBlocked = !canRun || Boolean(scopeWarning);const runHint = moduleRunHint(campaignId, selected, selectedCampaign, sensitive, confirmed, dryRun);const persistedRun = lastRunRecord?.campaignId === campaignId && lastRunRecord.moduleId === selectedId ? lastRunRecord : null;@@ -1167,6 +1168,19 @@ function ModulesPage() {eyebrow={selected ? selected.id : "Select module"}action={selected ? <span className={opsecBadge(selected.opsec_level)}>{selected.opsec_level || "n/a"}</span> : null}/>+ {selected?.description && <p className="text-sm text-slate-600">{selected.description}</p>}+ {selected && (selected.capability_flags?.length || selected.supported_modes?.length) ? (+ <div className="mt-2 flex flex-wrap gap-1">+ {(selected.capability_flags ?? []).map((flag) => <span className="badge" key={flag}>{flag}</span>)}+ {(selected.supported_modes ?? []).map((mode) => <span className="badge" key={mode}>mode: {mode}</span>)}+ </div>+ ) : null}+ {selected?.dependency_notes?.length ? (+ <p className="notice mt-3">Dependencies: {selected.dependency_notes.join("; ")}</p>+ ) : null}+ {selected && !dryRunSupported && (+ <p className="notice notice-danger mt-3">Dry-run is unavailable for this module. No preview will be generated.</p>+ )}<CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />{campaignId && campaignDetail.isFetching && (<div className="notice mt-3">@@ -1198,7 +1212,7 @@ function ModulesPage() {)}<label className="toggle-row"><input type="checkbox" checked={dryRun} onChange={(e) => setDryRun(e.target.checked)} />- Dry run+ {dryRunSupported ? "Dry run" : "Dry run unavailable"}</label>{sensitive && (<label className="notice notice-danger">@@ -2588,6 +2602,20 @@ function ModuleRunSummary({ result, error }: { result?: Record<string, unknown>;const status = String(result?.status ?? "unknown");const moduleId = String(result?.module_id ?? "module");const runError = typeof result?.error === "string" ? result.error : "";+ const outcome = String(result?.outcome ?? "");+ const outcomeMessage = String(result?.outcome_message ?? "");+ const displayOutcome = outcome || status;+ const dryRun = result?.dry_run === true || status.startsWith("dry_run_");+ const warnings = Array.isArray(result?.warnings) ? result.warnings.map(String) : [];+ const nextSteps = Array.isArray(result?.operator_next_steps) ? result.operator_next_steps.map(String) : [];+ const hasOutcomeError = ["operator_error", "dependency_error", "network_error", "unsupported", "module_error", "failed", "timeout"].includes(displayOutcome);+ const emptyText = dryRun+ ? "No live execution was performed."+ : outcome === "completed_no_findings"+ ? "No confirmed findings. The module completed without observing an exploitable condition."+ : runError+ ? "No findings recorded because execution failed."+ : "No findings returned.";return (<section className="inline-summary mt-4">@@ -2596,17 +2624,29 @@ function ModuleRunSummary({ result, error }: { result?: Record<string, unknown>;action={(<div className="flex flex-wrap gap-2"><span className="badge">{moduleId}</span>- <span className={status === "done" ? "badge badge-low" : "badge badge-medium"}>{status}</span>+ <span className={hasOutcomeError ? "badge badge-high" : displayOutcome === "confirmed_findings" || displayOutcome === "completed_no_findings" || displayOutcome === "dry_run_ok" || displayOutcome === "done" ? "badge badge-low" : "badge badge-medium"}>{displayOutcome}</span><span className="badge">{duration}</span></div>)}/>- {runError && (- <p className="notice notice-danger mb-3">- <AlertTriangle size={16} />- {runError}+ {(outcomeMessage || runError) && (+ <p className={`notice mb-3 ${hasOutcomeError || runError ? "notice-danger" : ""}`}>+ {hasOutcomeError || runError ? <AlertTriangle size={16} /> : null}+ {outcomeMessage || runError}</p>)}+ {warnings.length > 0 && (+ <div className="notice mb-3">+ <strong>{dryRun ? "Dry-run notes" : "Notes"}</strong>+ <ul className="mt-1 list-disc pl-5">{warnings.map((warning) => <li key={warning}>{warning}</li>)}</ul>+ </div>+ )}+ {nextSteps.length > 0 && (+ <div className="notice mb-3">+ <strong>Next steps</strong>+ <ul className="mt-1 list-disc pl-5">{nextSteps.map((step) => <li key={step}>{step}</li>)}</ul>+ </div>+ )}<div className="mini-stat-grid mb-3"><MiniStat title="Findings" value={String(findings.length)} detail="returned observations" /><MiniStat title="Validation" value={String(validationCount)} detail="post-run checks" />@@ -2637,7 +2677,7 @@ function ModuleRunSummary({ result, error }: { result?: Record<string, unknown>;))}</div>) : (- <EmptyState text={runError ? "No findings recorded." : "No findings returned."} />+ <EmptyState text={emptyText} />)}</section>);diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.tsindex 28897c7..5842065 100644--- a/frontend/src/api/types.ts+++ b/frontend/src/api/types.ts@@ -64,6 +64,15 @@ export interface ModuleMeta {opsec_level?: string;mitre?: string;mitre_list?: string[];+ required_params?: string[];+ optional_params?: string[];+ defaults?: Record<string, unknown>;+ capability_flags?: string[];+ dry_run_supported?: boolean;+ supported_modes?: string[];+ dependency_notes?: string[];+ outcome_semantics?: string[];+ safe_error_categories?: string[];param_schema: ParamSchema;[key: string]: unknown;}diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex 996ced3..3a3f0fd 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -802,6 +802,19 @@ class TestModuleSchemaEndpoint:assert module["mitre_list"] == ["T1558.003"]assert "dc" in module["param_schema"]assert module["param_schema"]["password"]["secret"] is True+ for field in (+ "required_params",+ "optional_params",+ "defaults",+ "capability_flags",+ "dry_run_supported",+ "supported_modes",+ "dependency_notes",+ "outcome_semantics",+ "safe_error_categories",+ ):+ assert field in module+ assert module["dry_run_supported"] is True# ── Reports safety ───────────────────────────────────────────────────────────@@ -811,6 +824,59 @@ class TestModuleRunEndpoint:def setup_method(self) -> None:_reset_rate_limiter()+ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_module_dry_run_returns_redacted_stable_contract(+ self, aclient: Any+ ) -> None:+ c, db, app = aclient+ from ares.api.server import get_engine+ from ares.core.engine import AresEngine++ engine = AresEngine(settings=_settings())+ engine.load_modules()+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": "camp-dry-run-contract",+ "name": "Dry Run Contract",+ "client": "Internal",+ "operator": "admin",+ "noise_profile": "normal",+ "status": "created",+ "scope_json": '[{"cidr": "10.0.0.0/8", "description": ""}]',+ "targets_json": '["10.0.0.5"]',+ "notes": "",+ "created_at": "2026-06-27 02:15:19",+ "updated_at": "2026-06-27 02:15:19",+ }+ app.dependency_overrides[get_engine] = lambda: engine+ try:+ r = await c.post(+ "/modules/ad.kerberoast/run",+ json={+ "campaign_id": "camp-dry-run-contract",+ "params": {+ "dc": "10.0.0.5",+ "domain": "corp.local",+ "username": "svc-roast",+ "password": "Passw0rd!",+ "target_user": "sqlsvc",+ },+ "dry_run": True,+ },+ headers=_auth("admin", "team_lead"),+ )+ finally:+ app.dependency_overrides.pop(get_engine, None)++ assert r.status_code == 200+ payload = r.json()+ assert payload["status"] == "dry_run_ok"+ assert payload["module_id"] == "ad.kerberoast"+ assert payload["missing_params"] == []+ assert payload["validated_params_summary"]["password"] == "[redacted]"+ assert "Passw0rd!" not in r.text+ assert payload["would_execute"] is True+@pytest.mark.asyncio # type: ignore[untyped-decorator]async def test_module_run_uses_persisted_campaign_scope_json(self, aclient: Anydiff --git a/tests/unit/test_module_contracts.py b/tests/unit/test_module_contracts.pyindex 50b2626..30d32f7 100644--- a/tests/unit/test_module_contracts.py+++ b/tests/unit/test_module_contracts.py@@ -23,6 +23,21 @@ def test_module_contracts_enumerate_actual_builtin_loader():assert len(module_ids) == len(set(module_ids))metadata_by_id = {item["id"]: item for item in metadata}+ normalized_fields = {+ "id",+ "name",+ "category",+ "description",+ "required_params",+ "optional_params",+ "defaults",+ "capability_flags",+ "dry_run_supported",+ "supported_modes",+ "dependency_notes",+ "outcome_semantics",+ "safe_error_categories",+ }for cls in modules:module_id = cls.MODULE_IDmeta = metadata_by_id[module_id]@@ -33,6 +48,16 @@ def test_module_contracts_enumerate_actual_builtin_loader():assert isinstance(meta["requires"], list)assert isinstance(meta["outputs"], list)assert isinstance(meta["mitre_list"], list)+ assert normalized_fields <= set(meta), module_id+ assert isinstance(meta["required_params"], list)+ assert isinstance(meta["optional_params"], list)+ assert isinstance(meta["defaults"], dict)+ assert isinstance(meta["capability_flags"], list)+ assert isinstance(meta["dry_run_supported"], bool)+ assert isinstance(meta["supported_modes"], list)+ assert isinstance(meta["dependency_notes"], list)+ assert isinstance(meta["outcome_semantics"], list)+ assert isinstance(meta["safe_error_categories"], list)def test_builtin_module_param_schemas_are_renderable_and_match_hard_requires():@@ -81,3 +106,127 @@ def test_builtin_module_param_schemas_are_renderable_and_match_hard_requires():assert {"target", "dc", "host"} & schema_keys, module_idassert not missing_schemas+++def test_single_module_dry_run_is_structured_and_redacts_secrets():+ from ares.core.config import AresSettings+ from ares.core.engine import AresEngine++ engine = AresEngine(+ settings=AresSettings(+ ares_secret_key="test-contract-secret-key-min32-chars!!",+ ares_encryption_key="test-contract-encryption-key-32!!",+ ares_default_admin_password="TestContractPass1!",+ )+ )+ engine.load_modules()+ result = engine.dry_run_module(+ "ad.kerberoast",+ {+ "dc": "10.0.0.5",+ "domain": "corp.local",+ "username": "svc-roast",+ "password": "Passw0rd!",+ "target_user": "sqlsvc",+ },+ )++ assert result["status"] == "dry_run_ok"+ assert result["module_id"] == "ad.kerberoast"+ assert result["would_execute"] is True+ assert result["missing_params"] == []+ assert result["validated_params_summary"]["password"] == "[redacted]"+ assert "Passw0rd!" not in str(result)+ assert result["warnings"]+ assert result["operator_next_steps"]++ blocked = engine.dry_run_module(+ "ad.kerberoast",+ {"dc": "10.0.0.5", "domain": "corp.local"},+ missing_params=["username", "password"],+ )+ assert blocked["status"] == "dry_run_blocked"+ assert blocked["missing_params"] == ["username", "password"]+ assert blocked["would_execute"] is False+++def test_unsupported_module_dry_run_is_explicit():+ from ares.core.config import AresSettings+ from ares.core.engine import AresEngine+ from ares.core.plugin.loader import ModuleRegistry+ from ares.modules.base import BaseModule++ class UnsupportedModule(BaseModule):+ MODULE_ID = "test.unsupported"+ MODULE_NAME = "Unsupported test module"+ MODULE_CATEGORY = "test"+ MODULE_DESCRIPTION = "Test-only module"+ DRY_RUN_SUPPORTED = False++ engine = AresEngine(+ settings=AresSettings(+ ares_secret_key="test-contract-secret-key-min32-chars!!",+ ares_encryption_key="test-contract-encryption-key-32!!",+ ares_default_admin_password="TestContractPass1!",+ )+ )+ engine._registry = ModuleRegistry()+ engine.registry.register(UnsupportedModule)++ result = engine.dry_run_module("test.unsupported", {"target": "127.0.0.1"})++ assert result["status"] == "dry_run_unsupported"+ assert result["would_execute"] is False+ assert result["operator_next_steps"]+++def test_engine_done_without_findings_has_explicit_outcome():+ from ares.core.engine import EngineModuleResult, ModuleStatus++ result = EngineModuleResult(+ module_id="demo.empty",+ status=ModuleStatus.DONE,+ findings=[],+ )++ assert result.outcome == "completed_no_findings"+ assert "no confirmed findings" in result.outcome_message.lower()++ invalid = EngineModuleResult(+ module_id="ad.kerberoast",+ status=ModuleStatus.FAILED,+ error="Validation failed: invalid LDAP credentials",+ )+ timeout = EngineModuleResult(+ module_id="ad.kerberoast",+ status=ModuleStatus.TIMEOUT,+ error="Timed out after 120s",+ )+ dependency = EngineModuleResult(+ module_id="ad.kerberoast",+ status=ModuleStatus.FAILED,+ error="AD dependency 'impacket' is unavailable",+ )+ secret_error = EngineModuleResult(+ module_id="ad.kerberoast",+ status=ModuleStatus.FAILED,+ error="invalid credentials password=Passw0rd! token=secret-token",+ )+ assert invalid.outcome == "operator_error"+ assert timeout.outcome == "network_error"+ assert dependency.outcome == "dependency_error"+ assert "Passw0rd!" not in (secret_error.error or "")+ assert "secret-token" not in (secret_error.error or "")+++def test_ad_empty_results_have_operator_facing_classification():+ from ares.modules.ad.asreproast import classify_asrep_outcome+ from ares.modules.ad.enum_spn import classify_enum_spn_outcome+ from ares.modules.ad.kerberoast import classify_kerberoast_outcome++ assert classify_asrep_outcome("authenticated", 1, 0)[0] == "completed_no_findings"+ assert "candidate" in classify_asrep_outcome("authenticated", 1, 0)[1]+ assert classify_asrep_outcome("authenticated", 0, 0)[0] == "completed_no_findings"+ assert classify_kerberoast_outcome(1, 0, 1)[0] == "network_error"+ assert classify_kerberoast_outcome(1, 0, 0)[0] == "completed_no_findings"+ assert classify_enum_spn_outcome(0)[0] == "completed_no_findings"