def execute(self, command): dce = self._rpctransport.get_dce_rpc() dce.set_credentials(*self._rpctransport.get_credentials()) dce.connect() dce.bind(tsch.MSRPC_UUID_TSCHS) xml = self.gen_xml(command) tmpName = ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(8)) self._log.debug("Register random task {}".format(tmpName)) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) time.sleep(3) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) dce.disconnect()
def execute(self, commands): try: dce = self._rpctransport.get_dce_rpc() dce.set_credentials(*self._rpctransport.get_credentials()) if self._conn.kerberos: dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) dce.connect() dce.bind(tsch.MSRPC_UUID_TSCHS) xml = self.gen_xml(commands) tmpName = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) self._log.debug("Register random task {}".format(tmpName)) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) time.sleep(3) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) dce.disconnect() except KeyboardInterrupt as e: self._log.debug("Scheduled task execution stopped because of keyboard interruption") self.cleanup_task(dce, tmpName) dce.disconnect() raise KeyboardInterrupt(e) except Exception as e: self._log.debug("Error : {}".format(e)) self.cleanup_task(dce, tmpName) dce.disconnect() raise Exception(e)
def test_hSchRpcStopInstance(self): dce, rpctransport = self.connect(self.stringBindingAtSvc, tsch.MSRPC_UUID_TSCHS) dce2, rpctransport = self.connect(self.stringBindingAtSvc, atsvc.MSRPC_UUID_ATSVC) atInfo = AT_INFO() atInfo['JobTime'] = NULL atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\Temp\\ANI 2>&1\x00' try: resp = atsvc.hNetrJobAdd(dce2, NULL, atInfo) resp.dump() except Exception as e: if e.get_error_code() != ERROR_NOT_SUPPORTED: raise else: # OpNum not supported, aborting test return jobId = resp['pJobId'] try: resp = tsch.hSchRpcRun(dce, '\\At%d\x00' % jobId, ('arg0','arg1')) resp.dump() except Exception, e: print e pass
def test_hSchRpcStopInstance(self): dce, rpctransport = self.connect(self.stringBindingAtSvc, tsch.MSRPC_UUID_TSCHS) dce2, rpctransport = self.connect(self.stringBindingAtSvc, atsvc.MSRPC_UUID_ATSVC) atInfo = AT_INFO() atInfo['JobTime'] = NULL atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo[ 'Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\Temp\\ANI 2>&1\x00' resp = atsvc.hNetrJobAdd(dce2, NULL, atInfo) resp.dump() jobId = resp['pJobId'] try: resp = tsch.hSchRpcRun(dce, '\\At%d\x00' % jobId, ('arg0', 'arg1')) resp.dump() except Exception, e: print e pass
def test_hSchRpcRun(self): dce, rpctransport = self.connect(self.stringBindingAtSvc, tsch.MSRPC_UUID_TSCHS) dce2, rpctransport = self.connect(self.stringBindingAtSvc, atsvc.MSRPC_UUID_ATSVC) atInfo = AT_INFO() atInfo['JobTime'] = NULL atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo[ 'Command'] = '%%COMSPEC%% /C dir > %%SYSTEMROOT%%\\Temp\\ANI 2>&1\x00' try: resp = atsvc.hNetrJobAdd(dce2, NULL, atInfo) resp.dump() except Exception as e: if e.get_error_code() != ERROR_NOT_SUPPORTED: raise else: # OpNum not supported, aborting test return jobId = resp['pJobId'] try: resp = tsch.hSchRpcRun(dce, '\\At%d\x00' % jobId, ('arg0', 'arg1')) resp.dump() except Exception as e: print(e) pass resp = atsvc.hNetrJobDel(dce2, NULL, jobId, jobId) resp.dump()
def doStuff(self, command): dce = self.__rpctransport.get_dce_rpc() dce.set_credentials(*self.__rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = gen_random_string(8) tmpFileName = tmpName + '.tmp' xml = self.gen_xml(command) taskCreated = False self.logger.debug('Creating task \\{}'.format(tmpName)) tsch.hSchRpcRegisterTask(dce, '\\{}'.format(tmpName), xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True self.logger.debug('Running task \\{}'.format(tmpName)) tsch.hSchRpcRun(dce, '\\{}'.format(tmpName)) done = False while not done: self.logger.debug( 'Calling SchRpcGetLastRunInfo for \\{}'.format(tmpName)) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\{}'.format(tmpName)) if resp['pLastRuntime']['wYear'] != 0: done = True else: sleep(2) self.logger.debug('Deleting task \\{}'.format(tmpName)) tsch.hSchRpcDelete(dce, '\\{}'.format(tmpName)) taskCreated = False if taskCreated is True: tsch.hSchRpcDelete(dce, '\\{}'.format(tmpName)) # Get output if self.noOutput: self.__outputBuffer = "Command executed with no output" elif self.fileless_output: self.get_output_fileless() else: self.get_output() dce.disconnect()
def exec(self, command): if not super().exec(command): return False try: stringbinding = r'ncacn_np:%s[\pipe\atsvc]' % self.session.address self._rpctransport = transport.DCERPCTransportFactory(stringbinding) if hasattr(self._rpctransport, 'set_credentials'): self._rpctransport.set_credentials(self.session.username, self.session.password, self.session.domain, self.session.lmhash, self.session.nthash, self.session.aesKey) self._rpctransport.set_kerberos(self.session.kerberos, self.session.dc_ip) self._dce = self._rpctransport.get_dce_rpc() self._dce.set_credentials(*self._rpctransport.get_credentials()) if self.session.kerberos: self._dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) self._dce.connect() self._dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) self._dce.bind(tsch.MSRPC_UUID_TSCHS) xml = self.gen_xml(command) logging.debug("Register random task {}".format(self._taskname)) tsch.hSchRpcRegisterTask(self._dce, '\\%s' % self._taskname, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) tsch.hSchRpcRun(self._dce, '\\%s' % self._taskname) done = False while not done: resp = tsch.hSchRpcGetLastRunInfo(self._dce, '\\%s' % self._taskname) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) time.sleep(3) self.clean() except KeyboardInterrupt as e: self.clean() raise KeyboardInterrupt(e) except Exception as e: self.clean() raise Exception(e) return True
def test_hSchRpcStopInstance(self): dce, rpc_transport = self.connect() dce_2, rpc_transport_2 = self.connect( iface_uuid=atsvc.MSRPC_UUID_ATSVC) atInfo = AT_INFO() atInfo['JobTime'] = NULL atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo[ 'Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\Temp\\ANI 2>&1\x00' try: resp = atsvc.hNetrJobAdd(dce_2, NULL, atInfo) resp.dump() except atsvc.DCERPCSessionError as e: if e.get_error_code() != ERROR_NOT_SUPPORTED: raise else: # OpNum not supported, aborting test return jobId = resp['pJobId'] try: resp = tsch.hSchRpcRun(dce, '\\At%d\x00' % jobId, ('arg0', 'arg1')) resp.dump() except tsch.DCERPCSessionError as e: print(e) pass try: resp = tsch.hSchRpcStopInstance(dce, resp['pGuid']) resp.dump() except tsch.DCERPCSessionError as e: if str(e).find('SCHED_E_TASK_NOT_RUNNING') <= 0: raise pass try: resp = atsvc.hNetrJobDel(dce_2, NULL, jobId, jobId) resp.dump() except atsvc.DCERPCSessionError as e: if e.get_error_code() != ERROR_NOT_SUPPORTED: raise else: # OpNum not supported, aborting test return
def test_SchRpcStopInstance(self): dce, rpctransport = self.connect(self.stringBindingAtSvc, tsch.MSRPC_UUID_TSCHS) dce2, rpctransport = self.connect(self.stringBindingAtSvc, atsvc.MSRPC_UUID_ATSVC) atInfo = AT_INFO() atInfo['JobTime'] = NULL atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo[ 'Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\Temp\\ANI 2>&1\x00' try: resp = atsvc.hNetrJobAdd(dce2, NULL, atInfo) resp.dump() except Exception as e: if e.get_error_code() != ERROR_NOT_SUPPORTED: raise else: # OpNum not supported, aborting test return jobId = resp['pJobId'] try: resp = tsch.hSchRpcRun(dce, '\\At%d\x00' % jobId, ('arg0', 'arg1')) resp.dump() except Exception as e: print(e) pass request = tsch.SchRpcStopInstance() request['guid'] = resp['pGuid'] request['flags'] = 0 try: resp = dce.request(request) resp.dump() except Exception as e: if str(e).find('SCHED_E_TASK_NOT_RUNNING') <= 0: raise pass resp = atsvc.hNetrJobDel(dce2, NULL, jobId, jobId) resp.dump()
def test_hSchRpcStopInstance(self): dce, rpctransport = self.connect(self.stringBindingAtSvc, tsch.MSRPC_UUID_TSCHS) dce2, rpctransport = self.connect(self.stringBindingAtSvc, atsvc.MSRPC_UUID_ATSVC) atInfo = AT_INFO() atInfo['JobTime'] = NULL atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo['Command'] = '%%COMSPEC%% /C vssadmin > %%SYSTEMROOT%%\\Temp\\ANI 2>&1\x00' resp = atsvc.hNetrJobAdd(dce2, NULL, atInfo) resp.dump() jobId = resp['pJobId'] try: resp = tsch.hSchRpcRun(dce, '\\At%d\x00' % jobId, ('arg0','arg1')) resp.dump() except Exception, e: print e pass
def doStuff(self, rpctransport): def output_callback(data): print(data.decode('utf-8')) dce = rpctransport.get_dce_rpc() dce.set_credentials(*rpctransport.get_credentials()) if self.__doKerberos is True: dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) tmpFileName = tmpName + '.tmp' xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> <Arguments>/C %s > %%windir%%\\Temp\\%s 2>&1</Arguments> </Exec> </Actions> </Task> """ % (self.__command, tmpFileName) taskCreated = False try: logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False except tsch.DCERPCSessionError as e: logging.error(e) e.get_packet().dump() finally: if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) smbConnection = rpctransport.get_smb_connection() waitOnce = True while True: try: logging.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, output_callback) break except Exception as e: if str(e).find('SHARING') > 0: time.sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: if waitOnce is True: # We're giving it the chance to flush the file before giving up time.sleep(3) waitOnce = False else: raise else: raise logging.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) dce.disconnect()
def doStuff(self, rpctransport): def output_callback(data): print(data.decode('utf-8')) dce = rpctransport.get_dce_rpc() dce.set_credentials(*rpctransport.get_credentials()) if self.__doKerberos is True: dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) dce.connect() # dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = ''.join( [random.choice(string.ascii_letters) for _ in range(8)]) tmpFileName = tmpName + '.tmp' xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> <Arguments>/C %s > %%windir%%\\Temp\\%s 2>&1</Arguments> </Exec> </Actions> </Task> """ % (self.__command, tmpFileName) taskCreated = False try: logger.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logger.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: logger.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) logger.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False except tsch.DCERPCSessionError as e: logger.error(e) e.get_packet().dump() finally: if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) smbConnection = rpctransport.get_smb_connection() waitOnce = True while True: try: logger.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, output_callback) break except Exception as e: if str(e).find('SHARING') > 0: time.sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: if waitOnce is True: # We're giving it the chance to flush the file before giving up time.sleep(3) waitOnce = False else: raise else: raise logger.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) dce.disconnect()
def doStuff(self, command, fileless=False): dce = self.__rpctransport.get_dce_rpc() if self.__doKerberos: dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) dce.set_credentials(*self.__rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = gen_random_string(8) tmpFileName = tmpName + '.tmp' xml = self.gen_xml(command, tmpFileName, fileless) #logging.info("Task XML: {}".format(xml)) taskCreated = False logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: sleep(2) logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) if self.__retOutput: if fileless: while True: try: with open(os.path.join('/tmp', 'cme_hosted', tmpFileName), 'r') as output: self.output_callback(output.read()) break except IOError: sleep(2) else: peer = ':'.join(map(str, self.__rpctransport.get_socket().getpeername())) smbConnection = self.__rpctransport.get_smb_connection() while True: try: #logging.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, self.output_callback) break except Exception as e: if str(e).find('SHARING') > 0: sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: sleep(3) else: raise #logging.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) dce.disconnect()
def doStuff(self, rpctransport): def output_callback(data): buf = StringIO(data.strip()).readlines() for line in buf: print_att(line.strip()) dce = rpctransport.get_dce_rpc() dce.set_credentials(*rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = ''.join([random.choice(string.letters) for _ in range(8)]) tmpFileName = tmpName + '.tmp' xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> """ if self.__noOutput is False: xml+= """ <Arguments>/C {} > %windir%\\Temp\\{} 2>&1</Arguments> </Exec> </Actions> </Task> """.format(self.__command, tmpFileName) else: xml+= """ <Arguments>/C {}</Arguments> </Exec> </Actions> </Task> """.format(self.__command) logging.info("Task XML: {}".format(xml)) taskCreated = False try: logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: sleep(2) logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False except tsch.DCERPCSessionError, e: logging.error(e) e.get_packet().dump()
def _run(self): # Here PUT YOUR CODE! tmpName = ''.join( [random.choice(string.ascii_letters) for _ in range(8)]) cmd = "cmd.exe" args = "/C %s" % self.config.command LOG.info('Executing command %s in no output mode via %s' % (self.config.command, self.stringbinding)) xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>%s</Command> <Arguments>%s</Arguments> </Exec> </Actions> </Task> """ % (self._xml_escape(cmd), self._xml_escape(args)) LOG.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(self.dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) LOG.info('Running task \\%s' % tmpName) done = False tsch.hSchRpcRun(self.dce, '\\%s' % tmpName) while not done: LOG.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(self.dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) LOG.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(self.dce, '\\%s' % tmpName) LOG.info('Completed!')
def doStuff(self, command, fileless=False): dce = self.__rpctransport.get_dce_rpc() dce.set_credentials(*self.__rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = gen_random_string(8) tmpFileName = tmpName + '.tmp' xml = self.gen_xml(command, tmpFileName, fileless) #logging.info("Task XML: {}".format(xml)) taskCreated = False logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: sleep(2) logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) if self.__retOutput: if fileless: while True: try: with open(os.path.join('/tmp', 'cme_hosted', tmpFileName), 'r') as output: self.output_callback(output.read()) break except IOError: sleep(2) else: peer = ':'.join(map(str, self.__rpctransport.get_socket().getpeername())) smbConnection = self.__rpctransport.get_smb_connection() while True: try: #logging.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, self.output_callback) break except Exception as e: if str(e).find('SHARING') > 0: sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: sleep(3) else: raise #logging.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) dce.disconnect()
def atexec(self, command): def output_callback(data): print(data.decode('utf-8')) if DataStore.version_major < 6: logger.warn('This command only works on Windows >= Vista') return self.__tmpFileName = ''.join( [random.choice(string.letters) for _ in range(8)]) + '.tmp' self.__at_command = command self.__atsvc_connect() xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> <Arguments>/C %s > %%windir%%\\Temp\\%s 2>&1</Arguments> </Exec> </Actions> </Task> """ % (self.__at_command, self.__tmpFileName) taskCreated = False try: logger.info('Creating task \\%s' % self.__tmpFileName) tsch.hSchRpcRegisterTask(self.__dce, '\\%s' % self.__tmpFileName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logger.info('Running task \\%s' % self.__tmpFileName) tsch.hSchRpcRun(self.__dce, '\\%s' % self.__tmpFileName) done = False while not done: logger.debug('Calling SchRpcGetLastRunInfo for \\%s' % self.__tmpFileName) resp = tsch.hSchRpcGetLastRunInfo(self.__dce, '\\%s' % self.__tmpFileName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) logger.info('Deleting task \\%s' % self.__tmpFileName) tsch.hSchRpcDelete(self.__dce, '\\%s' % self.__tmpFileName) taskCreated = False except tsch.DCERPCSessionError as e: logger.error(e) e.get_packet().dump() finally: if taskCreated is True: tsch.hSchRpcDelete(self.__dce, '\\%s' % self.__tmpFileName) self.transferClient = self.trans.get_smb_connection() waitOnce = True while True: try: logger.info('Attempting to read ADMIN$\\Temp\\%s' % self.__tmpFileName) self.transferClient.getFile('ADMIN$', 'Temp\\%s' % self.__tmpFileName, output_callback) break except Exception as e: if str(e).find('SHARING') > 0: time.sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: if waitOnce is True: # We're giving it the chance to flush the file before giving up time.sleep(3) waitOnce = False else: raise else: raise logger.debug('Deleting file ADMIN$\\Temp\\%s' % self.__tmpFileName) self.transferClient.deleteFile('ADMIN$', 'Temp\\%s' % self.__tmpFileName) self.__atsvc_disconnect()
def doStuff(self, rpctransport): def output_callback(data): print data dce = rpctransport.get_dce_rpc() dce.set_credentials(*rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = ''.join([random.choice(string.letters) for _ in range(8)]) tmpFileName = tmpName + '.tmp' xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> <Arguments>/C %s > %%windir%%\\Temp\\%s 2>&1</Arguments> </Exec> </Actions> </Task> """ % (self.__command, tmpFileName) taskCreated = False try: logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False except tsch.DCERPCSessionError, e: logging.error(e) e.get_packet().dump()
def doStuff(self, command): def output_callback(data): self.__outputBuffer = data dce = self.__rpctransport.get_dce_rpc() dce.set_credentials(*self.__rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = gen_random_string(8) xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> """ if self.__retOutput: tmpFileName = tmpName + '.tmp' xml += """ <Arguments>/C {} > %windir%\\Temp\\{} 2>&1</Arguments> </Exec> </Actions> </Task> """.format(command, tmpFileName) elif self.__retOutput is False: xml += """ <Arguments>/C {}</Arguments> </Exec> </Actions> </Task> """.format(command) #logging.info("Task XML: {}".format(xml)) taskCreated = False #logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True #logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: #logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: sleep(2) #logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) peer = ':'.join( map(str, self.__rpctransport.get_socket().getpeername())) #self.__logger.success('Executed command via ATEXEC') if self.__retOutput: smbConnection = self.__rpctransport.get_smb_connection() while True: try: #logging.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, output_callback) break except Exception as e: if str(e).find('SHARING') > 0: sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: sleep(3) else: raise #logging.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) else: pass #logging.info('Output retrieval disabled') dce.disconnect()
def doStuff(self, rpctransport): def output_callback(data): try: print(data.decode(CODEC)) except UnicodeDecodeError: logging.error( 'Decoding error detected, consider running chcp.com at the target,\nmap the result with ' 'https://docs.python.org/3/library/codecs.html#standard-encodings\nand then execute atexec.py ' 'again with -codec and the corresponding codec') print(data.decode(CODEC, errors='replace')) def xml_escape(data): replace_table = { "&": "&", '"': """, "'": "'", ">": ">", "<": "<", } return ''.join(replace_table.get(c, c) for c in data) def cmd_split(cmdline): cmdline = cmdline.split(" ", 1) cmd = cmdline[0] args = cmdline[1] if len(cmdline) > 1 else '' return [cmd, args] dce = rpctransport.get_dce_rpc() dce.set_credentials(*rpctransport.get_credentials()) if self.__doKerberos is True: dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) dce.connect() dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = ''.join( [random.choice(string.ascii_letters) for _ in range(8)]) tmpFileName = tmpName + '.tmp' if self.sessionId is not None: cmd, args = cmd_split(self.__command) else: cmd = "cmd.exe" args = "/C %s > %%windir%%\\Temp\\%s 2>&1" % (self.__command, tmpFileName) xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>%s</Command> <Arguments>%s</Arguments> </Exec> </Actions> </Task> """ % (xml_escape(cmd), xml_escape(args)) taskCreated = False try: logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True logging.info('Running task \\%s' % tmpName) done = False if self.sessionId is None: tsch.hSchRpcRun(dce, '\\%s' % tmpName) else: try: tsch.hSchRpcRun(dce, '\\%s' % tmpName, flags=tsch.TASK_RUN_USE_SESSION_ID, sessionId=self.sessionId) except Exception as e: if str(e).find('ERROR_FILE_NOT_FOUND') >= 0 or str(e).find( 'E_INVALIDARG') >= 0: logging.info('The specified session doesn\'t exist!') done = True else: raise while not done: logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: time.sleep(2) logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False except tsch.DCERPCSessionError as e: logging.error(e) e.get_packet().dump() finally: if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) if self.sessionId is not None: dce.disconnect() return smbConnection = rpctransport.get_smb_connection() waitOnce = True while True: try: logging.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, output_callback) break except Exception as e: if str(e).find('SHARING') > 0: time.sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: if waitOnce is True: # We're giving it the chance to flush the file before giving up time.sleep(3) waitOnce = False else: raise else: raise logging.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) dce.disconnect()
def doStuff(self, command): def output_callback(data): self.__outputBuffer = data dce = self.__rpctransport.get_dce_rpc() dce.set_credentials(*self.__rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) dce.bind(tsch.MSRPC_UUID_TSCHS) tmpName = gen_random_string(8) xml = """<?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers> <CalendarTrigger> <StartBoundary>2015-07-15T20:35:13.2757294</StartBoundary> <Enabled>true</Enabled> <ScheduleByDay> <DaysInterval>1</DaysInterval> </ScheduleByDay> </CalendarTrigger> </Triggers> <Principals> <Principal id="LocalSystem"> <UserId>S-1-5-18</UserId> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>true</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>P3D</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="LocalSystem"> <Exec> <Command>cmd.exe</Command> """ if self.__retOutput: tmpFileName = tmpName + '.tmp' xml+= """ <Arguments>/C {} > %windir%\\Temp\\{} 2>&1</Arguments> </Exec> </Actions> </Task> """.format(command, tmpFileName) elif self.__retOutput is False: xml+= """ <Arguments>/C {}</Arguments> </Exec> </Actions> </Task> """.format(command) #logging.info("Task XML: {}".format(xml)) taskCreated = False #logging.info('Creating task \\%s' % tmpName) tsch.hSchRpcRegisterTask(dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) taskCreated = True #logging.info('Running task \\%s' % tmpName) tsch.hSchRpcRun(dce, '\\%s' % tmpName) done = False while not done: #logging.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) resp = tsch.hSchRpcGetLastRunInfo(dce, '\\%s' % tmpName) if resp['pLastRuntime']['wYear'] != 0: done = True else: sleep(2) #logging.info('Deleting task \\%s' % tmpName) tsch.hSchRpcDelete(dce, '\\%s' % tmpName) taskCreated = False if taskCreated is True: tsch.hSchRpcDelete(dce, '\\%s' % tmpName) peer = ':'.join(map(str, self.__rpctransport.get_socket().getpeername())) #self.__logger.success('Executed command via ATEXEC') if self.__retOutput: smbConnection = self.__rpctransport.get_smb_connection() while True: try: #logging.info('Attempting to read ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, output_callback) break except Exception as e: if str(e).find('SHARING') > 0: sleep(3) elif str(e).find('STATUS_OBJECT_NAME_NOT_FOUND') >= 0: sleep(3) else: raise #logging.debug('Deleting file ADMIN$\\Temp\\%s' % tmpFileName) smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) else: pass #logging.info('Output retrieval disabled') dce.disconnect()