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: classify AD bind and Kerberos clock errors
Mafifrizi765c41e22849
diff --git a/ares/modules/ad/enum_users.py b/ares/modules/ad/enum_users.pyindex f6621b2..1a9df73 100644--- a/ares/modules/ad/enum_users.py+++ b/ares/modules/ad/enum_users.py@@ -16,6 +16,11 @@ 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, NetworkError+from ares.modules.ad.dependencies import (+ build_ad_bind_plan,+ classify_ad_ldap_bind_failure,+)UAC_ACCOUNT_DISABLE = 0x0002UAC_DONT_EXPIRE_PASSWORD = 0x10000@@ -115,8 +120,9 @@ class ADEnumUsersModule(BaseModule):None,lambda: self._ldap_query_sync(dc, username, password, domain, use_ldaps, page_size),)+ except AresError:+ raiseexcept Exception as exc:- from ares.core.errors import NetworkErrorraise NetworkError(f"LDAP failed on {dc}: {exc}") from excraw = {"user_list": users, "password_policy": policy}# ISU-07: produce UserArtifact objects for ArtifactIntelEngine@@ -153,32 +159,77 @@ class ADEnumUsersModule(BaseModule):from ldap3 import Server, Connection, ALL, NTLM, SUBTREE, Tlsfrom ldap3.core.exceptions import LDAPBindError- # Try LDAPS first, fall back to plain LDAP+ bind_plan = build_ad_bind_plan(username, domain)+ last_failure: AresError | None = Noneconn = Nonefor port, use_ssl in ([(636, True), (389, False)] if use_ldaps else [(389, False)]):+ attempt_conn = Nonetry: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}",- password=password,- authentication=NTLM,- auto_bind=ldap3.AUTO_BIND_NONE,- receive_timeout=30,- )- result = conn.bind()+ conn_kwargs = {+ "user": bind_plan.user,+ "password": password,+ "auto_bind": ldap3.AUTO_BIND_NONE,+ "receive_timeout": 30,+ }+ if bind_plan.mode == "ntlm":+ conn_kwargs["authentication"] = NTLM+ attempt_conn = Connection(server, **conn_kwargs)+ result = attempt_conn.bind()if not result:- raise LDAPBindError(f"Bind failed: {conn.result}")+ bind_error = LDAPBindError(f"Bind failed: {attempt_conn.result}")+ classified = classify_ad_ldap_bind_failure(+ bind_error,+ module_id=self.MODULE_ID,+ dc=dc,+ bind_plan=bind_plan,+ result=attempt_conn.result,+ )+ if isinstance(classified, ModuleValidationError):+ raise classified from bind_error+ last_failure = classified+ continue+ conn = attempt_connbreak+ except ModuleValidationError:+ raiseexcept Exception as exc:- conn = None- continue+ classified = classify_ad_ldap_bind_failure(+ exc,+ module_id=self.MODULE_ID,+ dc=dc,+ bind_plan=bind_plan,+ result=getattr(attempt_conn, "result", None),+ )+ if isinstance(classified, ModuleValidationError):+ raise classified from exc+ last_failure = classified+ finally:+ if attempt_conn is not None and attempt_conn is not conn:+ try:+ attempt_conn.unbind()+ except Exception:+ passif conn is None:- raise ConnectionError(f"Could not bind to {dc} on ports 636 or 389")+ if isinstance(last_failure, NetworkError):+ raise NetworkError(+ f"{last_failure.message} Verify use_ldaps={str(use_ldaps).lower()}, "+ "LDAP port 389 versus LDAPS port 636, firewall rules, and "+ "DC certificate/LDAPS configuration.",+ module_id=self.MODULE_ID,+ target=dc,+ context=last_failure.context,+ ) from last_failure+ raise NetworkError(+ f"{self.MODULE_ID} could not bind to {dc} using "+ f"use_ldaps={str(use_ldaps).lower()} on ports 389/636.",+ module_id=self.MODULE_ID,+ target=dc,+ )base = _dn_to_base(domain)users: list[dict] = []diff --git a/ares/modules/ad/kerberoast.py b/ares/modules/ad/kerberoast.pyindex a14bb4d..d0a13ab 100644--- a/ares/modules/ad/kerberoast.py+++ b/ares/modules/ad/kerberoast.py@@ -41,6 +41,18 @@ def format_kerberos_realm_mismatch() -> str:)+def format_kerberos_clock_skew() -> str:+ return (+ "Kerberos clock skew too great; sync the operator host and domain "+ "controller time, then rerun."+ )+++def is_kerberos_clock_skew(exc: BaseException) -> bool:+ error_text = f"{type(exc).__name__}: {exc}".lower()+ return "krb_ap_err_skew" in error_text or "clock skew too great" in error_text++def _kerberos_tgs_worker(connection: Any,spn: str,@@ -306,6 +318,12 @@ class KerberoastModule(BaseModule):except Exception as exc:from ares.core.errors import NetworkErrorerr = str(exc).lower()+ if is_kerberos_clock_skew(exc):+ raise ModuleValidationError(+ format_kerberos_clock_skew(),+ module_id=self.MODULE_ID,+ field="time",+ ) from excif "invalid credentials" in err or "logon failure" in err:raise nonretryable_ad_auth_error(module_id=self.MODULE_ID,@@ -383,6 +401,12 @@ class KerberoastModule(BaseModule):domain=domain,service="Kerberos",) from exc+ if is_kerberos_clock_skew(exc):+ raise ModuleValidationError(+ format_kerberos_clock_skew(),+ module_id=self.MODULE_ID,+ field="time",+ ) from excif "kdc_err_wrong_realm" in err or "wrong realm" in err:raise ModuleValidationError(format_kerberos_realm_mismatch(),@@ -483,6 +507,12 @@ class KerberoastModule(BaseModule):field="kerberos_tgs",) from excexcept Exception as exc:+ if is_kerberos_clock_skew(exc):+ raise ModuleValidationError(+ format_kerberos_clock_skew(),+ module_id=self.MODULE_ID,+ field="time",+ ) from excself._last_tgs_failures += 1logger.debug("kerberoast_tgs_failed", spn=spn, error=str(exc)[:80])diff --git a/tests/unit/test_ad_bind_behavior.py b/tests/unit/test_ad_bind_behavior.pyindex 349e49e..9aee4a0 100644--- a/tests/unit/test_ad_bind_behavior.py+++ b/tests/unit/test_ad_bind_behavior.py@@ -319,6 +319,56 @@ def test_enum_spn_invalid_credentials_abort_not_network(monkeypatch):assert "WrongPassword1!" not in str(exc_info.value)+def test_enum_users_invalid_credentials_abort_not_network(monkeypatch):+ from ares.modules.ad.enum_users import ADEnumUsersModule++ _install_fake_ldap3(monkeypatch, bind_outcomes=[False])+ module, _ = _make_module(ADEnumUsersModule)++ with pytest.raises(ModuleValidationError) as exc_info:+ module._ldap_query_sync(+ "10.0.0.5",+ "[email protected]",+ "WrongPassword1!",+ "lab.local",+ False,+ 50,+ )++ message = str(exc_info.value)+ assert exc_info.value.action == "abort"+ assert exc_info.value.field == "username"+ assert "invalid LDAP credentials" in message+ assert "WrongPassword1!" not in message+++def test_enum_users_network_bind_failure_is_actionable(monkeypatch):+ from ares.modules.ad.enum_users import ADEnumUsersModule++ _install_fake_ldap3(+ monkeypatch,+ bind_outcomes=[OSError("socket connection error while opening")],+ )+ module, _ = _make_module(ADEnumUsersModule)++ with pytest.raises(NetworkError) as exc_info:+ module._ldap_query_sync(+ "10.0.0.5",+ "[email protected]",+ "Password1!",+ "lab.local",+ False,+ 50,+ )++ message = str(exc_info.value)+ assert exc_info.value.action == "retry"+ assert "network/connectivity failure" in message+ assert "use_ldaps=false" in message+ assert "389" in message and "636" in message+ assert "Password1!" not in message++@pytest.mark.asyncioasync def test_kerberoast_invalid_tgt_credentials_are_nonretryable(monkeypatch):from ares.modules.ad.kerberoast import KerberoastModule@@ -365,6 +415,32 @@ async def test_kerberoast_wrong_realm_is_nonretryable(monkeypatch):assert "UserLab!2026" not in str(exc_info.value)+async def test_kerberoast_clock_skew_is_nonretryable(monkeypatch):+ import ares.modules.ad.kerberoast as kerberoast_mod+ from ares.modules.ad.kerberoast import KerberoastModule++ _install_fake_kerberos(+ monkeypatch,+ tgt_error=Exception("KRB_AP_ERR_SKEW(Clock skew too great)"),+ )+ module, _ = _make_module(KerberoastModule)++ with pytest.raises(ModuleValidationError) as exc_info:+ await module._request_tickets(+ "10.0.0.5",+ "[email protected]",+ "Password1!",+ "lab.local",+ "HTTP/web.lab.local",+ )++ assert exc_info.value.action == "abort"+ assert exc_info.value.field == "time"+ assert str(exc_info.value) == kerberoast_mod.format_kerberos_clock_skew()+ assert "Password1!" not in str(exc_info.value)++@pytest.mark.asyncioasync def test_kerberoast_spn_lookup_consumes_enum_spn_output_key(monkeypatch):import ares.modules.ad.kerberoast as kerberoast_moddiff --git a/tests/unit/test_engine.py b/tests/unit/test_engine.pyindex 967358e..949405f 100644--- a/tests/unit/test_engine.py+++ b/tests/unit/test_engine.py@@ -236,6 +236,90 @@ class TestAsyncEngine:assert result.outcome == "operator_error"assert "ASREPRoast candidate" in result.outcome_message+ @pytest.mark.asyncio+ async def test_enum_users_nonretryable_bind_failure_does_not_retry(+ self, settings: AresSettings, campaign: Campaign, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from ares.core.errors import ModuleValidationError+ from ares.core.noise import JitterEngine+ from ares.modules.ad.enum_users import ADEnumUsersModule++ engine = AresEngine(settings=settings)+ engine.load_modules()+ calls = 0++ def classified_bind_failure(*args: Any, **kwargs: Any) -> Any:+ nonlocal calls+ calls += 1+ raise ModuleValidationError(+ "ad.enum_users LDAP bind failed: invalid LDAP credentials.",+ module_id="ad.enum_users",+ field="username",+ )++ monkeypatch.setattr(ADEnumUsersModule, "_ldap_query_sync", classified_bind_failure)++ async def no_noise_sleep(*args: Any, **kwargs: Any) -> None:+ return None++ monkeypatch.setattr(JitterEngine, "sleep", no_noise_sleep)+ params = {+ "dc": "10.0.0.5",+ "domain": "corp.local",+ "username": "[email protected]",+ "password": "Passw0rd!",+ "use_ldaps": False,+ }+ with patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:+ result = await engine.run_module("ad.enum_users", campaign, params)++ assert calls == 1+ assert retry_sleep.await_count == 0+ assert result.outcome == "operator_error"+ assert result.findings == []+ assert "invalid LDAP credentials" in result.outcome_message+ assert "Passw0rd!" not in result.outcome_message++ @pytest.mark.asyncio+ async def test_kerberoast_clock_skew_does_not_retry(+ self, settings: AresSettings, campaign: Campaign+ ) -> None:+ from ares.core.errors import ModuleValidationError+ from ares.modules.ad.kerberoast import (+ KerberoastModule,+ format_kerberos_clock_skew,+ )++ engine = AresEngine(settings=settings)+ engine.load_modules()+ calls = 0++ async def classified_clock_skew(self_unused: Any, ctx: Any) -> Any:+ nonlocal calls+ calls += 1+ raise ModuleValidationError(+ format_kerberos_clock_skew(),+ module_id="ad.kerberoast",+ field="time",+ )++ params = {+ "dc": "10.0.0.5",+ "domain": "corp.local",+ "username": "[email protected]",+ "password": "Passw0rd!",+ "target_user": "sqlsvc",+ }+ with patch.object(KerberoastModule, "execute", classified_clock_skew), \+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:+ result = await engine.run_module("ad.kerberoast", campaign, params)++ assert calls == 1+ assert retry_sleep.await_count == 0+ assert result.outcome == "operator_error"+ assert "clock skew too great" in result.outcome_message+ assert result.findings == []+@pytest.mark.asyncioasync def test_retry_stops_when_retry_attempt_classifies_tgs_timeout(self, settings: AresSettings, campaign: Campaign