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(security): Gate 6 - vault write guard against synthetic and type-incoherent credentials (SUCCESS_MECHANISM_AUDIT.md)
Mafifriziea81bd5f25e6
diff --git a/ares/core/context.py b/ares/core/context.pyindex d847ea3..933af11 100644--- a/ares/core/context.py+++ b/ares/core/context.py@@ -106,6 +106,11 @@ class ExecutionContext(Generic[P]):# ── 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)@@ -201,8 +206,30 @@ class ExecutionContext(Generic[P]):domain: str = "",cred_type: str = "password",metadata: dict[str, Any] | None = None,+ io_verified: bool | None = None,) -> Any:- """Store a discovered credential in the context vault if available."""+ """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:+ from ares.core.logger import get_logger+ get_logger("ares.core.context").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(@@ -212,6 +239,8 @@ class ExecutionContext(Generic[P]):cred_type=cred_type,host=self.target,metadata=metadata or {},+ io_verified=has_io,+ ctx=self,)except Exception:passdiff --git a/ares/credential/vault.py b/ares/credential/vault.pyindex cad19f5..8cf2efd 100644--- a/ares/credential/vault.py+++ b/ares/credential/vault.py@@ -135,6 +135,14 @@ class Credential:PrivilegeLevel.SYSTEM,)+ @property+ def secret(self) -> str:+ return getattr(self, "_secret", "")++ @secret.setter+ def secret(self, val: str) -> None:+ self._secret = val+def to_dict(self, include_secret: bool = False) -> dict[str, Any]:d: dict[str, Any] = {"id": self.id,@@ -217,6 +225,53 @@ class CredentialScorer:return round(min(max(s, 0.0), 10.0), 2)+# ── Gate 6: Vault Write Guard Constants & Validation ─────────────────────────++SYNTHETIC_PREFIXES = (+ "PRT_ESTSAUTH_", # phantom_token pattern+ "TGT_PKINIT_", # ghost_forge pattern+ "SIMULATED_",+ "FAKE_",+ "TEST_",+)+++def _is_valid_secret(secret: str) -> bool:+ """Gate 6 Condition 1: Secret cannot be empty, whitespace-only, or synthetic."""+ if not secret or not secret.strip():+ return False+ if any(secret.startswith(p) for p in SYNTHETIC_PREFIXES):+ return False+ return True+++def _validate_type_coherence(secret: str, cred_type: CredentialType) -> bool:+ """Gate 6 Condition 3: Secret format must match the declared CredentialType."""+ if cred_type == CredentialType.HASH:+ # Hash must have a recognized format+ return (+ secret.startswith(("$6$", "$y$", "$5$", "$2b$", "$1$", "$NT$", "aad3b435"))+ or (+ len(secret) in (32, 64)+ and all(c in "0123456789abcdefABCDEF" for c in secret)+ )+ )+ if cred_type == CredentialType.CLEARTEXT:+ # Cleartext must not look like a Unix crypt hash or exceeds reasonable length+ return not secret.startswith("$") and len(secret) < 256+ if cred_type == CredentialType.NTLM:+ if ":" in secret:+ parts = secret.split(":")+ if all(all(c in "0123456789abcdefABCDEF" for c in p) for p in parts if p):+ return True+ if all(c in "0123456789abcdefABCDEF" for c in secret):+ return True+ if secret.startswith("hash"):+ return True+ return False+ return True # Other types are not strictly constrained++# ── Credential Vault ───────────────────────────────────────────────────────────class CredentialVault:@@ -394,18 +449,56 @@ class CredentialVault:return self._fernet.decrypt(raw).decode()raise ValueError("Cannot decrypt: ephemeral vault has no Fernet key")- def store(self, cred: Credential, secret: str) -> str:+ def store(self, cred: Credential, secret: str, io_verified: bool = True) -> str | bool:"""Encrypt and store a credential. Returns credential ID.Deduplicates by (domain, username, cred_type).Args:- cred: Credential metadata (no plaintext secret)- secret: The actual secret - encrypted immediately on entry+ cred: Credential metadata (no plaintext secret)+ secret: The actual secret - encrypted immediately on entry+ io_verified: True if execution context has verified I/O evidence (Gate 6)"""- if not secret:+ if not secret or not secret.strip():+ logger.warning(+ "vault_write_blocked_invalid_secret",+ username=cred.username,+ cred_type=str(cred.cred_type),+ reason="empty or synthetic secret",+ )raise ValueError("Cannot store credential with empty secret")+ # Gate 6 Condition 1 - Vault Write Guard: check empty or synthetic secret+ if not _is_valid_secret(secret):+ logger.warning(+ "vault_write_blocked_invalid_secret",+ username=cred.username,+ cred_type=str(cred.cred_type),+ reason="empty or synthetic secret",+ )+ return False++ # Gate 6 Condition 3 - Type Coherence+ if not _validate_type_coherence(secret, cred.cred_type):+ logger.warning(+ "vault_write_blocked_type_mismatch",+ username=cred.username,+ secret_prefix=secret[:8],+ cred_type=str(cred.cred_type),+ reason="secret format incompatible with declared type",+ )+ return False++ # Gate 6 Condition 2 - I/O Verification+ if not io_verified:+ logger.warning(+ "vault_write_blocked_zero_io",+ username=cred.username,+ cred_type=str(cred.cred_type),+ reason="no network I/O or evidence recorded in execution context",+ )+ return False+dedup_key = f"{cred.domain.lower()}:{cred.username.lower()}:{cred.cred_type.value}"if dedup_key in self._by_fqdn:existing_id = self._by_fqdn[dedup_key]@@ -443,46 +536,94 @@ class CredentialVault:)return cred.id- def add(self, cred: "Any" = None, secret: str = "", **kwargs: Any) -> str:- """Alias for store() - supports both Credential model and kwargs."""+ def add(self, cred: "Any" = None, secret: str = "", **kwargs: Any) -> str | bool:+ """Alias for store() - supports both Credential model and kwargs with Gate 6 write guard."""+ sec = secret or getattr(cred, "secret", "") or (str(kwargs.get("secret", "")) if kwargs.get("secret") is not None else "")++ # Extract type and username for pre-validationif isinstance(cred, Credential):- return self.store(cred, secret)- username = str(kwargs.get("username") or (cred if isinstance(cred, str) else ""))- cred_type_raw = kwargs.get("cred_type", CredentialType.CLEARTEXT)- type_map = {- "cleartext": CredentialType.CLEARTEXT,- "password": CredentialType.CLEARTEXT,- "ntlm": CredentialType.NTLM,- "hash": CredentialType.HASH,- "token": CredentialType.JWT,- "jwt": CredentialType.JWT,- "api_key": CredentialType.API_KEY,- "ticket": CredentialType.KRB5_TGT,- "tgt": CredentialType.KRB5_TGT,- "tgs": CredentialType.KRB5_TGS,- "certificate": CredentialType.CERTIFICATE,- "cert": CredentialType.CERTIFICATE,- "cookie": CredentialType.COOKIE,- }- if isinstance(cred_type_raw, str):- cred_type = type_map.get(cred_type_raw.lower(), CredentialType.CLEARTEXT)- elif isinstance(cred_type_raw, CredentialType):- cred_type = cred_type_raw+ c_type = cred.cred_type+ u_name = cred.usernameelse:- cred_type = CredentialType.CLEARTEXT+ u_name = str(kwargs.get("username") or (cred if isinstance(cred, str) else ""))+ cred_type_raw = kwargs.get("cred_type", CredentialType.CLEARTEXT)+ type_map = {+ "cleartext": CredentialType.CLEARTEXT,+ "password": CredentialType.CLEARTEXT,+ "ntlm": CredentialType.NTLM,+ "hash": CredentialType.HASH,+ "token": CredentialType.JWT,+ "jwt": CredentialType.JWT,+ "api_key": CredentialType.API_KEY,+ "ticket": CredentialType.KRB5_TGT,+ "tgt": CredentialType.KRB5_TGT,+ "tgs": CredentialType.KRB5_TGS,+ "certificate": CredentialType.CERTIFICATE,+ "cert": CredentialType.CERTIFICATE,+ "cookie": CredentialType.COOKIE,+ }+ if isinstance(cred_type_raw, str):+ c_type = type_map.get(cred_type_raw.lower(), CredentialType.CLEARTEXT)+ elif isinstance(cred_type_raw, CredentialType):+ c_type = cred_type_raw+ else:+ c_type = CredentialType.CLEARTEXT++ # Gate 6 Condition 1 - Vault Write Guard: check empty or synthetic secret+ if not _is_valid_secret(sec):+ logger.warning(+ "vault_write_blocked_invalid_secret",+ username=u_name,+ cred_type=str(c_type),+ reason="empty or synthetic secret",+ )+ return False++ # Gate 6 Condition 3 - Type Coherence+ if not _validate_type_coherence(sec, c_type):+ logger.warning(+ "vault_write_blocked_type_mismatch",+ username=u_name,+ secret_prefix=sec[:8],+ cred_type=str(c_type),+ reason="secret format incompatible with declared type",+ )+ return False++ # Gate 6 Condition 2 - I/O Verification+ io_verified = kwargs.get("io_verified", True)+ ctx = kwargs.get("ctx")+ if ctx is not None:+ io_verified = (+ getattr(ctx, "network_io_occurred", False)+ or bool(getattr(ctx, "findings", []))+ or bool(getattr(ctx, "collected_loot", []))+ )++ if not io_verified:+ logger.warning(+ "vault_write_blocked_zero_io",+ username=u_name,+ cred_type=str(c_type),+ reason="no network I/O or evidence recorded in execution context",+ )+ return False++ if isinstance(cred, Credential):+ return self.store(cred, sec, io_verified=io_verified)c = Credential(campaign_id=str(kwargs.get("campaign_id", getattr(self, "campaign_id", ""))),- username=username,+ username=u_name,domain=str(kwargs.get("domain", "")),target_host=str(kwargs.get("host") or kwargs.get("target_host", "")),- cred_type=cred_type,+ cred_type=c_type,privilege=kwargs.get("privilege", PrivilegeLevel.LOCAL_USER),source_module=str(kwargs.get("source_module", "")),source_host=str(kwargs.get("source_host", "")),tags=list(kwargs.get("tags") or []),)- return self.store(c, secret or str(kwargs.get("secret", "")))+ return self.store(c, sec, io_verified=io_verified)def reveal(self, cred_id: str) -> str:"""Decrypt and return the secret for a credential. Audit-logged."""diff --git a/tests/unit/test_honesty_gates.py b/tests/unit/test_honesty_gates.pyindex 9989c70..1b54a27 100644--- a/tests/unit/test_honesty_gates.py+++ b/tests/unit/test_honesty_gates.py@@ -400,3 +400,103 @@ class TestGate3And5IntegrationSimulations:# Gate 5: goal not achievedcampaign.findings = [fake_lateral_finding]assert strategy_engine._check_goal_achieved(campaign, "domain_admin") is False+++# ═══════════════════════════════════════════════════════════════════════════════+# GATE 6: Vault Write Guard (MOD-045, MOD-049 Integrity Protection)+# ═══════════════════════════════════════════════════════════════════════════════++class TestGate6VaultWriteGuard:+ """+ Gate 6 verifies that:+ 1. Empty or synthetic secrets (PRT_ESTSAUTH_, TGT_PKINIT_, SIMULATED_, FAKE_, TEST_) are blocked.+ 2. Incoherent credential types (e.g. Linux crypt hash declared as CLEARTEXT) are blocked.+ 3. Secrets are only stored when genuine I/O evidence exists in the execution context.+ 4. Synthetic token injection attacks like cloud.phantom_token are blocked before vault poisoning.+ """++ def test_empty_secret_blocked(self, caplog, capsys):+ vault = CredentialVault(encryption_key=None)+ # Empty string via add()+ res = vault.add(username="testuser", secret="", cred_type="cleartext")+ assert res is False+ captured = caplog.text + capsys.readouterr().out + capsys.readouterr().err+ assert "vault_write_blocked_invalid_secret" in captured++ def test_synthetic_prefixes_blocked(self, caplog, capsys):+ vault = CredentialVault(encryption_key=None)+ synthetic_secrets = [+ "PRT_ESTSAUTH_dev-123456789abc",+ "TGT_PKINIT_base64payloadhere",+ "SIMULATED_TOKEN_XYZ",+ "FAKE_PASSWORD_123",+ "TEST_SECRET_DO_NOT_USE",+ ]+ for syn in synthetic_secrets:+ res = vault.add(username="user1", secret=syn, cred_type="cleartext")+ assert res is False+ captured = caplog.text + capsys.readouterr().out + capsys.readouterr().err+ assert "vault_write_blocked_invalid_secret" in captured++ def test_hash_declared_as_cleartext_blocked(self, caplog, capsys):+ vault = CredentialVault(encryption_key=None)+ linux_sha512 = "$6$rounds=5000$saltsalt$xyz123abc456"+ # Declared as CLEARTEXT (MOD-045 bug pattern) -> must be blocked+ res = vault.add(username="root", secret=linux_sha512, cred_type=CredentialType.CLEARTEXT)+ assert res is False+ captured = caplog.text + capsys.readouterr().out + capsys.readouterr().err+ assert "vault_write_blocked_type_mismatch" in captured++ def test_hash_declared_as_hash_allowed(self):+ vault = CredentialVault(encryption_key=None)+ linux_sha512 = "$6$rounds=5000$saltsalt$xyz123abc456"+ # Correctly declared as HASH+ res = vault.add(username="root", secret=linux_sha512, cred_type=CredentialType.HASH)+ assert res is not False+ assert len(vault.all()) == 1++ def test_credential_valid_with_io_evidence_allowed(self):+ from ares.core.context import ExecutionContext+ vault = CredentialVault(encryption_key=None)+ ctx = ExecutionContext(+ target="10.0.0.1",+ module_id="linux.sssd_harvest",+ vault=vault,+ )+ ctx.mark_network_io_occurred(True)+ res = ctx.record_credential(+ username="ad_admin",+ secret="CorrectPassword2026!",+ cred_type="cleartext",+ )+ assert res is not None+ assert res is not False+ assert len(vault.all()) == 1++ def test_phantom_token_synthetic_simulation_completely_blocked(self, caplog, capsys):+ from ares.core.context import ExecutionContext+ vault = CredentialVault(encryption_key=None)+ ctx = ExecutionContext(+ target="corp.onmicrosoft.com",+ module_id="cloud.phantom_token",+ vault=vault,+ )+ # Case A: No I/O occurred -> blocked by Condition 2+ res = ctx.record_credential(+ username="corp.onmicrosoft.com_prt_session",+ secret="PRT_ESTSAUTH_dev-0123456789ab",+ cred_type="token",+ )+ assert res is False+ captured = caplog.text + capsys.readouterr().out + capsys.readouterr().err+ assert "vault_write_blocked_zero_io" in captured++ # Case B: Even if someone marked I/O occurred, blocked by Condition 1 (synthetic prefix)+ ctx.mark_network_io_occurred(True)+ res2 = ctx.record_credential(+ username="corp.onmicrosoft.com_prt_session",+ secret="PRT_ESTSAUTH_dev-0123456789ab",+ cred_type="token",+ )+ assert res2 is False or res2 is None+ assert len(vault.all()) == 0