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: enforce module contracts and AD bind behavior
Mafifrizi79ad9c817835
diff --git a/QUICKSTART.md b/QUICKSTART.mdindex 8765219..e739f56 100644--- a/QUICKSTART.md+++ b/QUICKSTART.md@@ -90,6 +90,10 @@ already reports `impacket` as importable from a source/local install, usePyPI Impacket wheel install. After installing AD dependencies, restart`ares dashboard dev --no-reload`, rerun `ares doctor --pdf-smoke`, and confirm`pyasn1`, `pyasn1_modules`, `ldap3`, and `httpx_ntlm` are no longer missing.+If `.[ad]` fails on Windows while importing Impacket example scripts such as+`GetNPUsers.py`, restore the known-good source/local Impacket checkout and use+`.[ad-support]` for the direct support libraries instead of repeatedly+retrying the broken wheel install.### D. Install frontend dependencies@@ -371,6 +375,7 @@ yet.`| PDF smoke warning on Windows | Use normal non-Administrator PowerShell, set `$env:ARES_PDF_BROWSER = "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"`, then run `.\.venv\Scripts\ares.exe doctor --pdf-smoke`. || Optional module dependency warning | Install the relevant extra only when that module family is needed, for example `.[ad]`, `.[cloud]`, `.[windows]`, or `.[full]`. For source/local Impacket AD setups, use `.[ad-support]` for the remaining direct AD support libraries. || Impacket source/local install version unknown | OK if Impacket is importable; install `.[ad-support]` if `pyasn1`, `pyasn1_modules`, `ldap3`, or `httpx_ntlm` still warn. Missing or too-old Impacket still warns. |+| AD LDAP/Kerberos login fails on Windows | Prefer UPN usernames such as `[email protected]`. Avoid `LAB\alice` unless NTLM/MD4 support is known to work in the active Python/OpenSSL environment. || `Invalid credentials` | Use the current admin password. Updating `ARES_DEFAULT_ADMIN_PASSWORD` after admin exists does not reset that password. || `Target is not in campaign scope` | Add the target CIDR to the campaign scope, for example `127.0.0.1/32` for local testing. || Report direct URL returns `401` | Use the authenticated dashboard Download button. |diff --git a/README.md b/README.mdindex d212c17..002fd26 100644--- a/README.md+++ b/README.md@@ -404,7 +404,8 @@ Optional module families are installed only when needed, for example `.[ad]`,`.[cloud]`, `.[windows]`, or `.[full]`. For AD users with source/localImpacket already importable, use `.[ad-support]` for the remaining direct ADsupport libraries; see [QUICKSTART.md](QUICKSTART.md) for the full decision-path.+path. For AD usernames on Windows, prefer UPN format such as+`[email protected]`; avoid `LAB\alice` unless NTLM/MD4 support is known to work.---diff --git a/ares/modules/ad/asreproast.py b/ares/modules/ad/asreproast.pyindex a29172c..3659815 100644--- a/ares/modules/ad/asreproast.py+++ b/ares/modules/ad/asreproast.py@@ -22,8 +22,14 @@ from ares.core.campaign import Finding, Severityfrom ares.core.security import sanitize_hostname, sanitize_ldapfrom ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module-from ares.core.errors import ModuleValidationError-from ares.modules.ad.dependencies import ensure_ad_dependencies+from ares.core.errors import AresError, ModuleValidationError+from ares.modules.ad.dependencies import (+ ad_bind_dry_run_metadata,+ build_ad_bind_plan,+ classify_ad_ldap_bind_failure,+ ensure_ad_dependencies,+ sanitize_ad_username,+)def _capture_asrep_raw(dc: str, domain: str, username: str) -> bytes | None:@@ -172,9 +178,22 @@ class ASREPRoastModule(BaseModule):userfile = ctx.params.get("userfile")usernames = ctx.params.get("usernames", [])if getattr(ctx, "dry_run", False):+ if username and password:+ mode = "authenticated"+ elif userfile:+ mode = "userfile"+ else:+ mode = "usernames"+ raw = {+ "dry_run": True,+ "dc": dc,+ "domain": domain,+ "mode": mode,+ **ad_bind_dry_run_metadata(username, domain),+ }return ModuleResult(status="dry_run", module_id=self.MODULE_ID,- raw={"dry_run": True, "dc": dc, "domain": domain},+ raw=raw,)findings, raw = await self.run(dc=dc, username=username, password=password,@@ -196,7 +215,7 @@ class ASREPRoastModule(BaseModule):)dc, domain = sanitize_hostname(dc), sanitize_ldap(domain)if username:- username = sanitize_ldap(username)+ username = sanitize_ad_username(username)await self.before_request(dc, "kerberos_tgs")has_creds = bool(username) and bool(password)@@ -215,7 +234,7 @@ class ASREPRoastModule(BaseModule):hashes, accounts = await self._get_asrep_hashes(dc, domain, username, password, userfile, usernames or [], mode)- except ModuleValidationError:+ except AresError:raiseexcept Exception as exc:from ares.core.errors import NetworkError@@ -303,32 +322,56 @@ class ASREPRoastModule(BaseModule):ensure_ad_dependencies(("ldap3",), module_id=self.MODULE_ID)import sslimport ldap3- from ldap3 import Server, Connection, NTLM, SUBTREE, Tls, ALL+ from ldap3 import Server, Connection, SUBTREE, Tls, ALLfrom ldap3.core.exceptions import LDAPBindError+ bind_plan = build_ad_bind_plan(username, domain)conn = None+ last_error = Nonefor port, use_ssl in [(636, True), (389, False)]:try:tls_arg = Tls(validate=ssl.CERT_NONE) if use_ssl else Noneserver = Server(dc, port=port, use_ssl=use_ssl,tls=tls_arg, get_info=ALL, connect_timeout=10)- conn = Connection(- server,- user=f"{domain.upper()}\\{username}",+ conn_kwargs = dict(+ user=bind_plan.user,password=password,- authentication=NTLM,auto_bind=ldap3.AUTO_BIND_NONE,receive_timeout=30,)+ if bind_plan.mode == "ntlm":+ conn_kwargs["authentication"] = ldap3.NTLM+ conn = Connection(server, **conn_kwargs)if not conn.bind():- raise LDAPBindError(f"Bind failed: {conn.result}")+ result = getattr(conn, "result", {}) or {}+ raise classify_ad_ldap_bind_failure(+ LDAPBindError("LDAP bind returned false"),+ module_id=self.MODULE_ID,+ dc=dc,+ bind_plan=bind_plan,+ result=result,+ )break+ except AresError:+ raiseexcept Exception as exc:logger.debug("asreproast_ldap_bind_failed",- port=port, error=str(exc)[:80])+ port=port, bind_mode=bind_plan.mode,+ username_format=bind_plan.username_format,+ error=str(exc)[:80])+ last_error = classify_ad_ldap_bind_failure(+ exc,+ module_id=self.MODULE_ID,+ dc=dc,+ bind_plan=bind_plan,+ )+ if isinstance(last_error, ModuleValidationError):+ raise last_errorconn = Noneif conn is None:+ if last_error is not None:+ raise last_errorraise ConnectionError(f"LDAP bind failed on {dc}")base = ",".join(f"DC={p}" for p in domain.upper().split("."))@@ -339,24 +382,29 @@ class ASREPRoastModule(BaseModule):"(!(userAccountControl:1.2.840.113556.1.4.803:=2)))")targets: list[str] = []- cookie: bool | bytes = True- while cookie:- conn.search(- base, nopreauth_filter,- search_scope=SUBTREE,- paged_size=200,- paged_cookie=None if cookie is True else cookie,- attributes=["sAMAccountName"],- )- for e in conn.entries:- targets.append(str(e.sAMAccountName))- cookie = (- conn.result.get("controls", {})- .get("1.2.840.113556.1.4.319", {})- .get("value", {})- .get("cookie")- )- conn.unbind()+ try:+ cookie: bool | bytes = True+ while cookie:+ conn.search(+ base, nopreauth_filter,+ search_scope=SUBTREE,+ paged_size=200,+ paged_cookie=None if cookie is True else cookie,+ attributes=["sAMAccountName"],+ )+ for e in conn.entries:+ targets.append(str(e.sAMAccountName))+ cookie = (+ conn.result.get("controls", {})+ .get("1.2.840.113556.1.4.319", {})+ .get("value", {})+ .get("cookie")+ )+ finally:+ try:+ conn.unbind()+ except Exception:+ passreturn targetsdef _analyze(self, raw):diff --git a/ares/modules/ad/dependencies.py b/ares/modules/ad/dependencies.pyindex a4e3943..2b8c70f 100644--- a/ares/modules/ad/dependencies.py+++ b/ares/modules/ad/dependencies.py@@ -2,9 +2,12 @@from __future__ import annotationsimport importlib+import re+from dataclasses import dataclassfrom collections.abc import Iterable+from typing import Any-from ares.core.errors import ModuleValidationError+from ares.core.errors import ModuleValidationError, NetworkErrorAD_INSTALL_HINT = (@@ -21,6 +24,8 @@ AD_SUPPORT_DEPENDENCIES: tuple[tuple[str, str], ...] = (("httpx_ntlm", "httpx-ntlm (ADCS HTTP enrollment)"),)+_AD_IDENTITY_UNSAFE_CHARS = re.compile(r"[*()\x00-\x1f\x7f]")+def ensure_ad_dependencies(import_names: Iterable[str], *, module_id: str) -> None:"""Raise a non-retryable ARES validation error for missing AD local deps."""@@ -36,3 +41,175 @@ def ensure_ad_dependencies(import_names: Iterable[str], *, module_id: str) -> Nomodule_id=module_id,field=import_name,) from exc+++@dataclass(frozen=True)+class ADBindPlan:+ """Safe LDAP bind plan metadata shared by AD modules."""++ user: str+ mode: str+ username_format: str+++def build_ad_bind_plan(username: str, domain: str) -> ADBindPlan:+ """+ Choose a deterministic LDAP bind mode from the user-supplied identity.++ UPN identities use LDAP simple bind to avoid NTLM/MD4 issues on modern+ Windows Python/OpenSSL builds. NETBIOS-style names keep NTLM explicit.+ """+ username = (username or "").strip()+ domain = (domain or "").strip()+ if "@" in username:+ return ADBindPlan(user=username, mode="simple", username_format="upn")+ if "\\" in username:+ return ADBindPlan(user=username, mode="ntlm", username_format="netbios")+ if domain:+ return ADBindPlan(+ user=f"{username}@{domain}",+ mode="simple",+ username_format="plain_to_upn",+ )+ return ADBindPlan(user=username, mode="simple", username_format="plain")+++def sanitize_ad_username(value: str) -> str:+ """Strip LDAP filter metacharacters while preserving UPN and NETBIOS forms."""+ return _AD_IDENTITY_UNSAFE_CHARS.sub("", value or "")+++def ad_bind_dry_run_metadata(username: str | None, domain: str | None) -> dict[str, Any]:+ """Return safe bind metadata for dry-run output."""+ if not username:+ return {+ "bind_mode": None,+ "username_format": None,+ "would_bind_ldap": False,+ "would_request_kerberos": False,+ }+ plan = build_ad_bind_plan(username, domain or "")+ return {+ "bind_mode": plan.mode,+ "username_format": plan.username_format,+ "would_bind_ldap": False,+ "would_request_kerberos": False,+ }+++def _safe_exception_text(exc: BaseException) -> str:+ text = str(exc).replace("\r", " ").replace("\n", " ").strip()+ return text[:160] if text else exc.__class__.__name__+++def _is_ntlm_md4_error(exc: BaseException) -> bool:+ text = f"{exc.__class__.__name__}: {exc}".lower()+ return "unsupported hash type" in text and "md4" in text+++def _is_invalid_ldap_credentials(+ exc: BaseException | None = None,+ result: dict[str, Any] | None = None,+) -> bool:+ if result:+ if result.get("result") == 49:+ return True+ combined = " ".join(+ str(result.get(key, ""))+ for key in ("description", "message", "diagnosticMessage")+ ).lower()+ if "invalidcredentials" in combined or "invalid credentials" in combined:+ return True+ if "acceptsecuritycontext" in combined and "data 52e" in combined:+ return True+ if exc is None:+ return False+ text = f"{exc.__class__.__name__}: {exc}".lower()+ return any(+ marker in text+ for marker in (+ "invalidcredentials",+ "invalid credentials",+ "ldapinvalidcredentials",+ "logon failure",+ "data 52e",+ "kdc_err_preauth_failed",+ )+ )+++def classify_ad_ldap_bind_failure(+ exc: BaseException,+ *,+ module_id: str,+ dc: str,+ bind_plan: ADBindPlan,+ result: dict[str, Any] | None = None,+) -> ModuleValidationError | NetworkError:+ """Classify LDAP bind failures without exposing passwords or raw traces."""+ context = {+ "dc": dc,+ "bind_mode": bind_plan.mode,+ "username_format": bind_plan.username_format,+ }+ prefix = (+ f"{module_id} LDAP bind failed for dc {dc} using {bind_plan.mode} "+ f"(username_format={bind_plan.username_format})"+ )+ if _is_ntlm_md4_error(exc):+ context["reason"] = "ntlm_md4_unavailable"+ return ModuleValidationError(+ (+ f"{prefix}: NTLM bind is unavailable in this Python/OpenSSL "+ "environment; use UPN format such as [email protected]."+ ),+ module_id=module_id,+ field="username",+ target=dc,+ context=context,+ )+ if _is_invalid_ldap_credentials(exc, result):+ context["reason"] = "invalid_credentials"+ return ModuleValidationError(+ f"{prefix}: invalid LDAP credentials.",+ module_id=module_id,+ field="username",+ target=dc,+ context=context,+ )+ context["reason"] = "network_or_directory_unreachable"+ return NetworkError(+ f"{prefix}: network/connectivity failure ({_safe_exception_text(exc)}).",+ module_id=module_id,+ target=dc,+ context=context,+ )+++def nonretryable_ad_auth_error(+ *,+ module_id: str,+ dc: str,+ username: str,+ domain: str,+ service: str,+) -> ModuleValidationError:+ """Return a safe, non-retryable AD authentication error."""+ plan = build_ad_bind_plan(username, domain)+ context = {+ "dc": dc,+ "service": service,+ "bind_mode": plan.mode,+ "username_format": plan.username_format,+ "reason": "invalid_credentials",+ }+ return ModuleValidationError(+ (+ f"{module_id} {service} authentication failed for dc {dc} "+ f"(username_format={plan.username_format}): invalid credentials."+ ),+ module_id=module_id,+ field="username",+ target=dc,+ context=context,+ )diff --git a/ares/modules/ad/enum_spn.py b/ares/modules/ad/enum_spn.pyindex 89c8b84..0c4afb9 100644--- a/ares/modules/ad/enum_spn.py+++ b/ares/modules/ad/enum_spn.py@@ -9,6 +9,13 @@ from ares.core.campaign import Finding, Severityfrom ares.core.security import sanitize_hostname, sanitize_ldapfrom ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module+from ares.core.errors import AresError, ModuleValidationError+from ares.modules.ad.dependencies import (+ ad_bind_dry_run_metadata,+ build_ad_bind_plan,+ classify_ad_ldap_bind_failure,+ sanitize_ad_username,+)def _dn_to_base(domain):return ",".join(f"DC={p}" for p in domain.upper().split("."))@@ -67,7 +74,12 @@ class ADEnumSPNModule(BaseModule):if getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID,- raw={"dry_run": True, "dc": dc, "domain": domain},+ raw={+ "dry_run": True,+ "dc": dc,+ "domain": domain,+ **ad_bind_dry_run_metadata(username, domain),+ },)findings, raw = await self.run(dc=dc, username=username, password=password, domain=domain,@@ -81,7 +93,11 @@ class ADEnumSPNModule(BaseModule):@trace_module("ad.enum_spn")async def run(self, dc, username, password, domain, **kwargs):- dc,username,domain = sanitize_hostname(dc),sanitize_ldap(username),sanitize_ldap(domain)+ dc, username, domain = (+ sanitize_hostname(dc),+ sanitize_ad_username(username),+ sanitize_ldap(domain),+ )await self.before_request(dc,"ldap")logger.info("ad.enum_spn_start", dc=dc)try:@@ -91,6 +107,8 @@ class ADEnumSPNModule(BaseModule):None,lambda: self._fetch_spns_sync(dc, username, password, domain),)+ except AresError:+ raiseexcept Exception as exc:from ares.core.errors import NetworkErrorraise NetworkError(f"LDAP SPN failed: {exc}") from exc@@ -125,34 +143,56 @@ class ADEnumSPNModule(BaseModule):"""import sslimport ldap3- from ldap3 import Server, Connection, ALL, NTLM, SUBTREE, Tls+ from ldap3 import Server, Connection, ALL, SUBTREE, Tlsfrom ldap3.core.exceptions import LDAPBindError# Try LDAPS first, fallback to plain LDAP+ bind_plan = build_ad_bind_plan(username, domain)conn = None+ last_error = Nonefor port, use_ssl in [(636, True), (389, False)]:try:tls_arg = Tls(validate=ssl.CERT_NONE) if use_ssl else Noneserver = Server(dc, port=port, use_ssl=use_ssl,tls=tls_arg, get_info=ALL,connect_timeout=10)- conn = Connection(- server,- user=f"{domain.upper()}\\{username}",+ conn_kwargs = dict(+ user=bind_plan.user,password=password,- authentication=NTLM,auto_bind=ldap3.AUTO_BIND_NONE,receive_timeout=30,)+ if bind_plan.mode == "ntlm":+ conn_kwargs["authentication"] = ldap3.NTLM+ conn = Connection(server, **conn_kwargs)result = conn.bind()if not result:- raise LDAPBindError(f"Bind failed: {conn.result}")+ ldap_result = getattr(conn, "result", {}) or {}+ raise classify_ad_ldap_bind_failure(+ LDAPBindError("LDAP bind returned false"),+ module_id=self.MODULE_ID,+ dc=dc,+ bind_plan=bind_plan,+ result=ldap_result,+ )break- except Exception:+ except AresError:+ raise+ except Exception as exc:+ last_error = classify_ad_ldap_bind_failure(+ exc,+ module_id=self.MODULE_ID,+ dc=dc,+ bind_plan=bind_plan,+ )+ if isinstance(last_error, ModuleValidationError):+ raise last_errorconn = Nonecontinueif conn is None:+ if last_error is not None:+ raise last_errorraise ConnectionError(f"Could not bind to {dc} on ports 636 or 389")base = _dn_to_base(domain)diff --git a/ares/modules/ad/kerberoast.py b/ares/modules/ad/kerberoast.pyindex 42cd6d6..68a9722 100644--- a/ares/modules/ad/kerberoast.py+++ b/ares/modules/ad/kerberoast.py@@ -12,8 +12,13 @@ from ares.core.campaign import Finding, Severity, NoiseProfilefrom ares.core.security import sanitize_hostname, sanitize_ldapfrom ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module-from ares.core.errors import ModuleValidationError-from ares.modules.ad.dependencies import ensure_ad_dependencies+from ares.core.errors import AresError, ModuleValidationError+from ares.modules.ad.dependencies import (+ ad_bind_dry_run_metadata,+ ensure_ad_dependencies,+ nonretryable_ad_auth_error,+ sanitize_ad_username,+)def _format_krb5tgs_hash(tgs: bytes, cipher: "Any", spn: str, domain: str) -> str:@@ -107,7 +112,13 @@ class KerberoastModule(BaseModule):if getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID,- raw={"dry_run": True, "dc": dc, "domain": domain},+ raw={+ "dry_run": True,+ "dc": dc,+ "domain": domain,+ "target_user": target_user,+ **ad_bind_dry_run_metadata(username, domain),+ },)findings, raw = await self.run(dc=dc, username=username, password=password, domain=domain, target_user=target_user,@@ -125,7 +136,11 @@ class KerberoastModule(BaseModule):("impacket", "pyasn1", "pyasn1_modules"),module_id=self.MODULE_ID,)- dc, username, domain = sanitize_hostname(dc), sanitize_ldap(username), sanitize_ldap(domain)+ dc, username, domain = (+ sanitize_hostname(dc),+ sanitize_ad_username(username),+ sanitize_ldap(domain),+ )if self.campaign.noise_profile == NoiseProfile.STEALTH:logger.warning("kerberoast_skipped", reason="stealth_profile")return [], {"skipped": True, "reason": "stealth_profile_too_noisy"}@@ -133,13 +148,19 @@ class KerberoastModule(BaseModule):logger.info("kerberoast_start", dc=dc, domain=domain, target=target_user)try:hashes, accounts = await self._request_tickets(dc, username, password, domain, target_user)- except ModuleValidationError:+ except AresError:raiseexcept Exception as exc:- from ares.core.errors import AuthenticationFailed, NetworkError+ from ares.core.errors import NetworkErrorerr = str(exc).lower()if "invalid credentials" in err or "logon failure" in err:- raise AuthenticationFailed(f"Kerberoast auth failed on {dc}", username=username, module_id=self.MODULE_ID, target=dc) from exc+ raise nonretryable_ad_auth_error(+ module_id=self.MODULE_ID,+ dc=dc,+ username=username,+ domain=domain,+ service="Kerberos",+ ) from excraise NetworkError(f"Kerberoast failed: {exc}") from excraw = {"kerberos_hashes": hashes, "accounts": accounts, "noise_level": self.campaign.noise_profile.value}self._analyze(raw)@@ -190,10 +211,12 @@ class KerberoastModule(BaseModule):err = str(exc).lower()if "invalid credentials" in err or "logon failure" in err or \"kdc_err_preauth_failed" in err:- from ares.core.errors import AuthenticationFailed- raise AuthenticationFailed(- f"Kerberoast TGT failed on {dc}",- username=username, module_id=self.MODULE_ID, target=dc,+ raise nonretryable_ad_auth_error(+ module_id=self.MODULE_ID,+ dc=dc,+ username=username,+ domain=domain,+ service="Kerberos",) from excraise@@ -211,8 +234,9 @@ class KerberoastModule(BaseModule):noise=self.noise,).run(dc=dc, username=username, password=password, domain=domain)_, spn_raw = spn_data- for acct in spn_raw.get("spns", []):- spn_list.extend(acct.get("spns", []))+ for acct in spn_raw.get("spn_list", spn_raw.get("spns", [])):+ spn_values = acct.get("spn_list") or acct.get("spns") or []+ spn_list.extend(spn_values)except Exception as exc:logger.warning("kerberoast_spn_lookup_failed", error=str(exc)[:80])diff --git a/docs/modules.md b/docs/modules.mdindex 6179a39..b753927 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -96,6 +96,12 @@ For AD modules, `.[ad]` is the normal full install. If `ares doctor` alreadyshows Impacket as importable from a source/local install, use `.[ad-support]`to install the direct AD support libraries (`pyasn1`, `pyasn1_modules`,`ldap3`, and `httpx_ntlm`) without forcing another Impacket wheel install.+On Windows, if `.[ad]` fails while importing Impacket example scripts such as+`GetNPUsers.py`, restore the known-good source/local Impacket checkout and use+`.[ad-support]` for the direct support libraries. For dashboard module+parameters, prefer UPN usernames such as `[email protected]`; use `LAB\alice`+only when NTLM/MD4 support is known to work in the active Python/OpenSSL+environment.## Module Categoriesdiff --git a/tests/unit/test_ad_bind_behavior.py b/tests/unit/test_ad_bind_behavior.pynew file mode 100644index 0000000..7c9a533--- /dev/null+++ b/tests/unit/test_ad_bind_behavior.py@@ -0,0 +1,335 @@+from __future__ import annotations++import sys+import types++import pytest++from ares.core.context import ExecutionContext+from ares.core.errors import ModuleValidationError, NetworkError+from tests.unit.modules.test_modules import _make_module+++def _install_fake_ldap3(monkeypatch, *, bind_outcomes=None):+ bind_outcomes = list(bind_outcomes or [True])++ class LDAPBindError(Exception):+ pass++ class FakeTls:+ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs++ class FakeServer:+ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs++ class FakeConnection:+ calls: list[dict] = []++ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs+ self.result = {}+ self.entries = []+ FakeConnection.calls.append(kwargs)++ def bind(self):+ outcome = bind_outcomes.pop(0) if bind_outcomes else True+ if isinstance(outcome, BaseException):+ raise outcome+ if isinstance(outcome, tuple):+ ok, result = outcome+ self.result = result+ return ok+ if outcome is False:+ self.result = {"result": 49, "description": "invalidCredentials"}+ return False+ return True++ def search(self, *args, **kwargs):+ self.result = {+ "controls": {+ "1.2.840.113556.1.4.319": {"value": {"cookie": b""}}+ }+ }+ self.entries = []+ return True++ def unbind(self):+ return True++ ldap3_mod = types.ModuleType("ldap3")+ ldap3_mod.AUTO_BIND_NONE = "AUTO_BIND_NONE"+ ldap3_mod.ALL = "ALL"+ ldap3_mod.NTLM = "NTLM"+ ldap3_mod.SUBTREE = "SUBTREE"+ ldap3_mod.Connection = FakeConnection+ ldap3_mod.Server = FakeServer+ ldap3_mod.Tls = FakeTls+ ldap3_mod.CERT_NONE = 0++ ldap3_core = types.ModuleType("ldap3.core")+ ldap3_exceptions = types.ModuleType("ldap3.core.exceptions")+ ldap3_exceptions.LDAPBindError = LDAPBindError+ ldap3_mod.core = ldap3_core+ ldap3_core.exceptions = ldap3_exceptions++ monkeypatch.setitem(sys.modules, "ldap3", ldap3_mod)+ monkeypatch.setitem(sys.modules, "ldap3.core", ldap3_core)+ monkeypatch.setitem(sys.modules, "ldap3.core.exceptions", ldap3_exceptions)+ return FakeConnection+++def _install_fake_kerberos(monkeypatch, *, tgt_error=None):+ def get_kerberos_tgt(**kwargs):+ if tgt_error is not None:+ raise tgt_error+ return b"tgt", "cipher", b"old_session", b"session"++ def get_kerberos_tgs(**kwargs):+ return b"tgs", "tgs_cipher", b"old", b"tgs_session"++ class _PrincipalNameTypeValue:+ def __init__(self, value):+ self.value = value++ class _PrincipalNameType:+ NT_PRINCIPAL = _PrincipalNameTypeValue(1)+ NT_SRV_INST = _PrincipalNameTypeValue(2)++ class Principal:+ def __init__(self, name, type):+ self.name = name+ self.type = type++ impacket = types.ModuleType("impacket")+ krb5 = types.ModuleType("impacket.krb5")+ kerberosv5 = types.ModuleType("impacket.krb5.kerberosv5")+ kerberosv5.getKerberosTGT = get_kerberos_tgt+ kerberosv5.getKerberosTGS = get_kerberos_tgs+ types_mod = types.ModuleType("impacket.krb5.types")+ types_mod.Principal = Principal+ constants_mod = types.ModuleType("impacket.krb5.constants")+ constants_mod.PrincipalNameType = _PrincipalNameType+ impacket.krb5 = krb5+ krb5.kerberosv5 = kerberosv5+ krb5.types = types_mod+ krb5.constants = constants_mod++ monkeypatch.setitem(sys.modules, "impacket", impacket)+ monkeypatch.setitem(sys.modules, "impacket.krb5", krb5)+ monkeypatch.setitem(sys.modules, "impacket.krb5.kerberosv5", kerberosv5)+ monkeypatch.setitem(sys.modules, "impacket.krb5.types", types_mod)+ monkeypatch.setitem(sys.modules, "impacket.krb5.constants", constants_mod)+ monkeypatch.setitem(sys.modules, "pyasn1", types.ModuleType("pyasn1"))+ monkeypatch.setitem(sys.modules, "pyasn1_modules", types.ModuleType("pyasn1_modules"))+++def test_ad_username_sanitizer_preserves_upn_and_explicit_netbios():+ from ares.modules.ad.dependencies import sanitize_ad_username++ assert sanitize_ad_username("[email protected]") == "[email protected]"+ assert sanitize_ad_username("LAB\\alice") == "LAB\\alice"+ assert sanitize_ad_username("LAB\\alice*") == "LAB\\alice"+++async def test_asreproast_dry_run_does_not_bind_or_request_kerberos(monkeypatch):+ from ares.modules.ad.asreproast import ASREPRoastModule++ async def fail_ldap(*args, **kwargs):+ raise AssertionError("dry-run must not bind LDAP")++ monkeypatch.setattr(ASREPRoastModule, "_ldap_get_nopreauth", fail_ldap)+ module, _ = _make_module(ASREPRoastModule)+ ctx = ExecutionContext.for_test(+ module_id="ad.asreproast",+ params={+ "dc": "10.0.0.5",+ "domain": "lab.local",+ "username": "[email protected]",+ "password": "Password1!",+ },+ dry_run=True,+ )++ result = await module.execute(ctx)++ assert result.status == "dry_run"+ assert result.raw["bind_mode"] == "simple"+ assert result.raw["username_format"] == "upn"+ assert result.raw["would_bind_ldap"] is False+ assert result.raw["would_request_kerberos"] is False+++async def test_kerberoast_dry_run_does_not_request_tgt_or_spns(monkeypatch):+ from ares.modules.ad.kerberoast import KerberoastModule++ async def fail_tickets(*args, **kwargs):+ raise AssertionError("dry-run must not request Kerberos tickets")++ monkeypatch.setattr(KerberoastModule, "_request_tickets", fail_tickets)+ module, _ = _make_module(KerberoastModule)+ ctx = ExecutionContext.for_test(+ module_id="ad.kerberoast",+ params={+ "dc": "10.0.0.5",+ "domain": "lab.local",+ "username": "[email protected]",+ "password": "Password1!",+ "target_user": "HTTP/web.lab.local",+ },+ dry_run=True,+ )++ result = await module.execute(ctx)++ assert result.status == "dry_run"+ assert result.raw["bind_mode"] == "simple"+ assert result.raw["username_format"] == "upn"+ assert result.raw["would_bind_ldap"] is False+ assert result.raw["would_request_kerberos"] is False+++async def test_asreproast_upn_uses_simple_ldap_bind(monkeypatch):+ from ares.modules.ad.asreproast import ASREPRoastModule++ fake_connection = _install_fake_ldap3(monkeypatch)+ module, _ = _make_module(ASREPRoastModule)++ targets = await module._ldap_get_nopreauth(+ "10.0.0.5",+ "lab.local",+ "[email protected]",+ "Password1!",+ )++ assert targets == []+ assert fake_connection.calls[0]["user"] == "[email protected]"+ assert "authentication" not in fake_connection.calls[0]+++async def test_asreproast_netbios_ntlm_md4_error_is_actionable_abort(monkeypatch):+ from ares.modules.ad.asreproast import ASREPRoastModule++ fake_connection = _install_fake_ldap3(+ monkeypatch,+ bind_outcomes=[ValueError("unsupported hash type MD4")],+ )+ module, _ = _make_module(ASREPRoastModule)++ with pytest.raises(ModuleValidationError) as exc_info:+ await module._ldap_get_nopreauth(+ "10.0.0.5",+ "lab.local",+ "LAB\\alice",+ "Password1!",+ )++ message = str(exc_info.value)+ assert exc_info.value.action == "abort"+ assert exc_info.value.field == "username"+ assert not isinstance(exc_info.value, NetworkError)+ assert "NTLM bind is unavailable" in message+ assert "[email protected]" in message+ assert "Password1!" not in message+ assert fake_connection.calls[0]["authentication"] == "NTLM"+++def test_enum_spn_upn_uses_simple_ldap_bind(monkeypatch):+ from ares.modules.ad.enum_spn import ADEnumSPNModule++ fake_connection = _install_fake_ldap3(monkeypatch)+ module, _ = _make_module(ADEnumSPNModule)++ spns = module._fetch_spns_sync(+ "10.0.0.5",+ "[email protected]",+ "Password1!",+ "lab.local",+ )++ assert spns == []+ assert fake_connection.calls[0]["user"] == "[email protected]"+ assert "authentication" not in fake_connection.calls[0]+++def test_enum_spn_invalid_credentials_abort_not_network(monkeypatch):+ from ares.modules.ad.enum_spn import ADEnumSPNModule++ _install_fake_ldap3(monkeypatch, bind_outcomes=[False])+ module, _ = _make_module(ADEnumSPNModule)++ with pytest.raises(ModuleValidationError) as exc_info:+ module._fetch_spns_sync(+ "10.0.0.5",+ "[email protected]",+ "WrongPassword1!",+ "lab.local",+ )++ assert exc_info.value.action == "abort"+ assert exc_info.value.field == "username"+ assert not isinstance(exc_info.value, NetworkError)+ assert "invalid LDAP credentials" in str(exc_info.value)+ assert "WrongPassword1!" not in str(exc_info.value)+++async def test_kerberoast_invalid_tgt_credentials_are_nonretryable(monkeypatch):+ from ares.modules.ad.kerberoast import KerberoastModule++ _install_fake_kerberos(monkeypatch, tgt_error=Exception("KDC_ERR_PREAUTH_FAILED"))+ module, _ = _make_module(KerberoastModule)++ with pytest.raises(ModuleValidationError) as exc_info:+ await module._request_tickets(+ "10.0.0.5",+ "[email protected]",+ "WrongPassword1!",+ "lab.local",+ "HTTP/web.lab.local",+ )++ assert exc_info.value.action == "abort"+ assert exc_info.value.field == "username"+ assert not isinstance(exc_info.value, NetworkError)+ assert "invalid credentials" in str(exc_info.value)+ assert "WrongPassword1!" not in str(exc_info.value)+++async def test_kerberoast_spn_lookup_consumes_enum_spn_output_key(monkeypatch):+ import ares.modules.ad.kerberoast as kerberoast_mod+ from ares.modules.ad.enum_spn import ADEnumSPNModule+ from ares.modules.ad.kerberoast import KerberoastModule++ _install_fake_kerberos(monkeypatch)++ async def fake_enum_spn_run(*args, **kwargs):+ return [], {"spn_list": [{"spn_list": ["HTTP/web.lab.local"]}]}++ monkeypatch.setattr(ADEnumSPNModule, "run", fake_enum_spn_run)+ monkeypatch.setattr(+ kerberoast_mod,+ "_format_krb5tgs_hash",+ lambda *args, **kwargs: "$krb5tgs$23$fake",+ )+ module, _ = _make_module(KerberoastModule)++ hashes, accounts = await module._request_tickets(+ "10.0.0.5",+ "[email protected]",+ "Password1!",+ "lab.local",+ None,+ )++ assert hashes == ["$krb5tgs$23$fake"]+ assert accounts[0]["spn"] == "HTTP/web.lab.local"diff --git a/tests/unit/test_module_contracts.py b/tests/unit/test_module_contracts.pynew file mode 100644index 0000000..50b2626--- /dev/null+++ b/tests/unit/test_module_contracts.py@@ -0,0 +1,83 @@+from __future__ import annotations+++def _builtin_registry():+ from ares.core.plugin.loader import PluginLoader++ loader = PluginLoader()+ loaded = loader._load_builtin()+ return loader, loaded+++def test_module_contracts_enumerate_actual_builtin_loader():+ loader, loaded = _builtin_registry()+ modules = loader.registry.all()+ metadata = loader.registry.list_metadata()++ assert not loader.errors+ assert loaded == len(modules)+ assert loaded >= 60+ assert len(metadata) == loaded++ module_ids = [cls.MODULE_ID for cls in modules]+ assert len(module_ids) == len(set(module_ids))++ metadata_by_id = {item["id"]: item for item in metadata}+ for cls in modules:+ module_id = cls.MODULE_ID+ meta = metadata_by_id[module_id]+ assert meta["source"] == "builtin"+ assert meta["id"] == module_id+ assert meta["name"]+ assert meta["category"]+ assert isinstance(meta["requires"], list)+ assert isinstance(meta["outputs"], list)+ assert isinstance(meta["mitre_list"], list)+++def test_builtin_module_param_schemas_are_renderable_and_match_hard_requires():+ from ares.modules.params import MODULE_PARAMS++ loader, _ = _builtin_registry()+ module_specific_required_fields = {+ "ad.asreproast": {"dc", "domain", "username", "password", "userfile"},+ "ad.kerberoast": {"dc", "domain", "username", "password", "target_user"},+ "credential.golden_ticket": {+ "domain",+ "domain_sid",+ "krbtgt_hash",+ "username",+ },+ }++ missing_schemas = []+ for cls in loader.registry.all():+ module_id = cls.MODULE_ID+ params_model = MODULE_PARAMS.get(module_id)+ if params_model is None:+ missing_schemas.append(module_id)+ continue++ schema = params_model.schema_for_api()+ assert isinstance(schema, dict), module_id+ for field_name, field in schema.items():+ assert field_name, module_id+ assert "type" in field, f"{module_id}.{field_name} missing type"+ assert "required" in field, f"{module_id}.{field_name} missing required flag"++ schema_keys = set(schema)+ requires = set(getattr(cls, "REQUIRES", []))+ if module_id in module_specific_required_fields:+ assert module_specific_required_fields[module_id] <= schema_keys, module_id+ if "domain_creds" in requires and module_id == "ad.kerberoast":+ assert {"domain", "username", "password"} <= schema_keys, module_id+ if "credentials" in requires:+ assert (+ {"username", "password"} <= schema_keys+ or {"ssh_user", "ssh_pass"} <= schema_keys+ or {"access_key", "secret_key"} <= schema_keys+ ), module_id+ if "target" in requires:+ assert {"target", "dc", "host"} & schema_keys, module_id++ assert not missing_schemas