def onOpenProcess(self): fileDlg = QFileDialog(self) fileDlg.setNameFilter(self.tr("Executable (*.exe)")) pykd.startProcess(fileDlg.getOpenFileName()[0]) self.goThread = GoThread(pykd.go)
def run_pykd(py, dll, output, align): cmd = [ sys.executable, py, f"--dll=\"{dll}\"", f"--output=\"{output}\"", f"--align=\"{align}\"", ] base = get_image_base(dll) breakpoints = {"yz1": [(0x10011270 - base, rewrite_filename)]} pykd.initialize() pykd.handler = EventHandler(breakpoints) pykd.startProcess(" ".join(str(x) for x in cmd)) pykd.go()
def Monitor(): testcase = "Testcases\\Test.txt" try: pykd.initialize() Handler = ExceptionHandler() print "[*] Starting Scan64.exe" pykd.startProcess( "C:\\Program Files (x86)\\McAfee\\VirusScan Enterprise\\x64\\Scan64.Exe " + testcase) pykd.dbgCommand(".childdbg 1") except: print "[!] Error starting process" sys.exit(1) print "[*] Success!" pykd.go()
def main(): pykd.initialize() pykd.handler = ExceptionHandler() pykd.startProcess("hello.exe") targetModule = pykd.module("hello") targetModule.reload() breakCount = callCounter() b1 = pykd.setBp(targetModule.offset('add'), breakCount) # The b1 cannot be commented print "There is %d breakpoint" % pykd.getNumberBreakpoints() pykd.go() print breakCount.count targetModule = None pykd.killAllProcesses()
def __init__(self, executable_path='', breakpoint_db=None): pykd.startProcess(executable_path) pykd.eventHandler.__init__(self) self.logger = logging.getLogger(__name__) out_hdlr = logging.StreamHandler(sys.stdout) out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s')) out_hdlr.setLevel(logging.INFO) self.logger.addHandler(out_hdlr) self.logger.setLevel(logging.INFO) self.BreakpointsMap = {} if breakpoint_db: breakpoints_db = breakpoints.DB(breakpoint_db) breakpoints_db.load() self.set_bp(breakpoints_db.Breakpoints)
def testLoadUnload(self): """Start new process and track loading and unloading modules""" pykd.startProcess(target.appPath + " loadunloadmodule") with testutils.ContextCallIt(pykd.killProcess) as contextCallIt: pykd.go() # skip initail break modLoadHandler = ModuleLoadHandler("ws2_32*") pykd.go() #with testutils.ContextCallIt( getattr(modLoadHandler, "reset") ) as resetEventHandler: # try: # while True: # pykd.go() # except pykd.WaitEventException: # pass self.assertTrue(modLoadHandler.wasLoad) self.assertTrue(modLoadHandler.wasUnload)
def main(): currentNum = 0 while True: if currentNum >= (flagLength * 8 - 1): break if currentNum > 0: proc = pykd.startProcess(f"\"C:/Users/Software Dev PC/source/repos/Kaf-Challenge/PackAndVirtualize/Debug/kafChallenge.exe\" {''.join(flag)}") solverObj = solve_chal() # print("\n".join(solverObj.instruction_list)) tempCurNum = currentNum for instruction_pack_index in range(currentNum, len(solverObj.instruction_list[::7])): if DEBUG: print(instruction_pack_index) instruction_pack = solverObj.instruction_list[instruction_pack_index * 7: (instruction_pack_index + 1) * 7] if instruction_pack[0].startswith("push"): print("Reached failure.") break instruction_pack = instruction_pack[2:] if DEBUG: print(f"Index: {instruction_pack[0]}") index = get_current_index(instruction_pack[0]) instruction_pack = instruction_pack[3:] if DEBUG: print(f"And: {instruction_pack[0]}") and_num = get_current_compare(instruction_pack[0]) instruction_pack = instruction_pack[1:] if DEBUG: print(f"jz: {instruction_pack[0]}") jmpEq = instruction_pack[0].startswith("je") if DEBUG: print(f"flag[{index}] & {and_num} {'==' if jmpEq else '!='} 0") char_num = ord(flag[index]) if jmpEq: #print(bin((char_num) & 0xff)) char_num &= (~and_num) & 0xff #print(bin((char_num) & 0xff)) #print(bin((~and_num) & 0xff)) else: char_num |= and_num char_num = chr(char_num) flag[index] = char_num tempCurNum += 1 currentNum = tempCurNum print("".join(flag))
def Monitor(self): Generator = TestcaseGenerator() Generator.CheckDir() pykd.initialize() Handler = ExceptionHandler() testcase = os.listdir("Queue")[0] try: print "[*] Starting Scan64.exe" pykd.startProcess("C:\\Program Files (x86)\\McAfee\\VirusScan Enterprise\\x64\\Scan64.Exe " + testcase) pykd.dbgCommand(".childdbg 1") except: print "[!] Error starting process" sys.exit(1) try: while Handler.keep_running: self.GetProcess() # Get PID print "[*] Attaching Debugger" print "[*] Success!" pykd.go() print "[*] Killing pykd..." pykd.killAllProcesses() finally: return
def _debug_server(self): ''' debugger thread ''' self._system_pid = None self.logger.info('Init pykd environment') pykd.initialize() try: # Start a new process for debugging argv = [self._process_path ] + self._process_args + self.process_data argv = ' '.join(argv) self.logger.debug('Debugger starting server: %s' % argv) try: self.logger.info('Start running program with cmd:"%s"' % argv) self.report.add('cmd', argv) self._pid = pykd.startProcess(argv) self._get_correct_process_id() self.logger.debug('Process started. pykd_pid=%d' % self._pid) self._process = pykd.getCurrentProcess() self.logger.debug('Process is %s' % hex(self._process)) except WindowsError: self.logger.error('debug_server received exception', traceback.fmt_exc()) # Get Process System ID self._wait_break() while self._system_pid is None: try: self._system_pid = pykd.getProcessSystemID(self._pid) self.logger.info('process system_id=%d' % self._system_pid) except Exception as err: self.logger.debug("Get system id fail because of: %s" % err) continue # Set break points if self._wait_break(): self.logger.info( "Server is in break status setting break points") for bp in self._break_points: pykd.setBp(bp) self.logger.info("Start register event handle") # This will register our handle handler = self._handler(self) self.logger.debug('Handler object is : %s' % handler) self.logger.info('Go !!!!!') pykd.go() except: self.logger.error('Got an exception in _debug_server') self.logger.error(traceback.format_exc())
def testExceptionHandler(self): class ExceptionHandler(pykd.eventHandler): def __init__(self): pykd.eventHandler.__init__(self) def onException(self, exceptInfo): self.exceptInfo = exceptInfo return pykd.eventResult.Break processId = pykd.startProcess(target.appPath + " exception") with testutils.ContextCallIt( testutils.KillProcess(processId)) as killStartedProcess: exceptionHandler = ExceptionHandler() self.assertEqual(pykd.Break, pykd.go()) self.assertEqual(0xC0000005, exceptionHandler.exceptInfo. exceptionCode) #0xC0000005 = Access violation
def testSecondChance(self): class ExceptionHandler(pykd.eventHandler): def __init__(self): pykd.eventHandler.__init__(self) def onException(self, exceptInfo): self.exceptInfo = exceptInfo return pykd.eventResult.Proceed processId = pykd.startProcess(target.appPath + " exception") with testutils.ContextCallIt( testutils.KillProcess(processId)) as killStartedProcess: exceptionHandler = ExceptionHandler() self.assertEqual(pykd.Break, pykd.go()) self.assertEqual(True, exceptionHandler.exceptInfo.firstChance) self.assertEqual(pykd.Break, pykd.go()) self.assertEqual(False, exceptionHandler.exceptInfo.firstChance)
def _debug_server(self): ''' debugger thread ''' self._system_pid = None self.logger.info('Init pykd environment') pykd.initialize() try: # Start a new process for debugging argv = [self._process_path] + self._process_args + self.process_data argv = ' '.join(argv) self.logger.debug('Debugger starting server: %s' % argv) try: self.logger.info('Start running program with cmd:"%s"' % argv) self.report.add('cmd', argv) self._pid = pykd.startProcess(argv) self._get_correct_process_id() self.logger.debug('Process started. pykd_pid=%d' % self._pid) self._process = pykd.getCurrentProcess() self.logger.debug('Process is %s' % hex(self._process)) except WindowsError: self.logger.error('debug_server received exception', traceback.fmt_exc()) # Get Process System ID self._wait_break() while self._system_pid is None: try: self._system_pid = pykd.getProcessSystemID(self._pid) self.logger.info('process system_id=%d' % self._system_pid) except Exception as err: self.logger.debug("Get system id fail because of: %s" % err) continue # Set break points if self._wait_break(): self.logger.info("Server is in break status setting break points") for bp in self._break_points: pykd.setBp(bp) self.logger.info("Start register event handle") # This will register our handle handler = self._handler(self) self.logger.debug('Handler object is : %s' % handler) self.logger.info('Go !!!!!') pykd.go() except: self.logger.error('Got an exception in _debug_server') self.logger.error(traceback.format_exc())
def testChangeSymbolsState(self): """Start new process and track change symbols exception""" _locProcessId = pykd.startProcess(target.appPath + " -testLoadUnload") with testutils.ContextCallIt( testutils.KillProcess(_locProcessId)) as killStartedProcess: mod = pykd.module("targetapp") symbolsStateHandler = SymbolsStateHandler(mod.begin()) pykd.dbgCommand(".reload /u targetapp.exe") self.assertTrue(symbolsStateHandler.unloadModuleTrigged) pykd.dbgCommand(".reload /u") self.assertTrue(symbolsStateHandler.unloadAllModulesTrigged) self.assertRaises(pykd.WaitEventException, testutils.infGo) self.assertTrue("iphlpapi" in symbolsStateHandler.modNames)
def testException(self): """Start new process and track exceptions""" _locProcessId = pykd.startProcess(target.appPath + " -testChangeStatus") with testutils.ContextCallIt( testutils.KillProcess(_locProcessId)) as killStartedProcess: pykd.go() #skip initial break statusChangeHandler = StatusChangeHandler() self.assertRaises(pykd.WaitEventException, testutils.infGo) self.assertEqual(2, statusChangeHandler.breakCount) self.assertEqual(1, statusChangeHandler.noDebuggee) self.assertEqual( statusChangeHandler.breakCount + statusChangeHandler.noDebuggee, statusChangeHandler.goCount)
def testException(self): """Start new process and track exceptions""" _locProcessId = pykd.startProcess(target.appPath + " -testExceptions") with testutils.ContextCallIt( testutils.KillProcess(_locProcessId)) as killStartedProcess: exceptionHandler = ExceptionHandler() while not exceptionHandler.accessViolationOccured: pykd.go() self.assertEqual(pykd.lastEvent(), pykd.eventType.Exception) self.assertTrue(exceptionHandler.accessViolationOccured) self.assertEqual(exceptionHandler.param0, 1) # write self.assertEqual(exceptionHandler.param1, 2) # addr exceptInfo = pykd.lastException() self.assertEqual(exceptInfo.ExceptionCode, 0xC0000005) self.assertEqual(exceptionHandler.param0, exceptInfo.Parameters[0]) self.assertEqual(exceptionHandler.param1, exceptInfo.Parameters[1])
def testLocalVariable(self): """Start new process and test local variables""" _locProcessId = pykd.startProcess(target.appPath + " -testEnumWindows") with testutils.ContextCallIt( testutils.KillProcess(_locProcessId)) as killStartedProcess: pykd.go() # initial breakpoint -> wmain pykd.go() # wmain -> targetapp!EnumWindowsProc1 testEnumWindowsProc1Locals(self, pykd.getLocals()) pykd.go( ) # targetapp!EnumWindowsProc1 -> targetapp!functionCalledFromEnumWindowsProc1 testEnumWindowsProc1Locals(self, pykd.getStack()[1].locals) pykd.go( ) # targetapp!EnumWindowsProc1 -> targetapp!EnumWindowsProc2 locals = pykd.getLocals() self.assertEqual(len(locals), 2) self.assertTrue(locals[0] == 7 or locals[1] == 7) funcParams = pykd.getParams() self.assertEqual(len(funcParams), 2) self.assertTrue(funcParams[0] == 7 or funcParams[1] == 7)
def testStart(self): target.processId = pykd.startProcess( target.appPath ) target.module = pykd.module( target.moduleName ) target.module.reload(); # print "\n" + str( pykd.getSystemVersion() ) pykd.go()
def run(self): if self.timeout != 0: self.timer = Timer(self.timeout, self.timeout_func) self.timer.start() self.do_stop = False self.id = pykd.startProcess(self.program, debugChildren=True) if self.handler is None: self.handler = ExceptionHandler() while not self.handler.exception_occurred and not self.do_stop: try: pykd.go() except: break if self.do_stop: try: pykd.dbgCommand(".kill") except: log("Exception killing target: %s" % str(sys.exc_info()[1])) return None if self.timer is not None: self.timer.cancel() ret = None if self.handler.exception_occurred: tmp = pykd.dbgCommand("k 1") if tmp.find("Wow64NotifyDebugger") > -1: pykd.dbgCommand(".effmach x86") stack_trace = pykd.dbgCommand("k") registers = pykd.dbgCommand("r") exploitable = None msec_path = None if self.exploitable_path is None: if self.mode == 32: msec_path = os.path.join(self.windbg_path, r"Debuggers\x86\winext") elif self.mode == 64: msec_path = os.path.join(self.windbg_path, r"Debuggers\x64\winext") elif self.mode == "arm": msec_path = os.path.join(self.windbg_path, r"Debuggers\arm\winext") else: raise Exception( "Unknown mode %s, known ones are 32, 64 or 'arm'." % self.mode) else: msec_path = self.exploitable_path if msec_path is not None: full_msec_path = os.path.join(msec_path, r"msec.dll") if os.path.exists(full_msec_path): try: msec_handle = pykd.loadExt(full_msec_path) commandOutput = pykd.callExt(msec_handle, "exploitable", "") exploitable = commandOutput except: log("Error loading extension: " + str(sys.exc_info()[1])) try: if self.minidump_path is not None: pykd.dbgCommand(r".dump /m /u %s\\" % self.minidump_path) log("*** Minidump written at %s" % self.minidump_path) except: log("!!! Error saving minidump:" + str(sys.exc_info()[1])) ret = self.create_crash_data(registers, stack_trace, exploitable) print pykd.dbgCommand("k 10") print pykd.dbgCommand("r") print exploitable crash_data_buf = self.crash_data.dump_json() ret = self.crash_data.dump_dict() print print "Yep, we got a crash! \o/" print return ret
def run(self, executable_path): pykd.startProcess(executable_path)
import regtest def getTestSuite(singleName=""): if singleName == "": return unittest.TestSuite([ unittest.TestLoader().loadTestsFromTestCase(basetest.BaseTest), unittest.TestLoader().loadTestsFromTestCase(typeinfo.TypeInfoTest), unittest.TestLoader().loadTestsFromTestCase(regtest.CpuRegTest) ]) else: return unittest.TestSuite( unittest.TestLoader().loadTestsFromName(singleName)) if __name__ == "__main__": targetAppPath = sys.argv[1] target.moduleName = os.path.splitext(os.path.basename(targetAppPath))[0] print "\nTest module: %s" % targetAppPath pykd.startProcess(targetAppPath) pykd.go() target.module = pykd.loadModule(target.moduleName) suite = getTestSuite() unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite)
def openProcess(self, name): pykd.startProcess(name) self.processOpened = True self.targetAttached.emit() self.targetBreak.emit()
def start_process(self): if not "ProcessDebugOptions" in dir(pykd): self.id = pykd.startProcess(self.program, debugChildren=True) else: self.id = pykd.startProcess(self.program, pykd.ProcessDebugOptions.DebugChildren) return self.id
for f in fList: print("File Name: " + f) sumFile.write("File Name: " + f) sumFile.write("\n") if f == "E:/Data/pdfFuzzerResult/run6/crash_input09.pdf": print "WARNING: Skip this file because it won't trigger a crash on my new laptop" sumFile.write("WARNING: Skip this file because it won't trigger a crash on my new laptop") sumFile.write("\n") sumFile.write("\n") continue pykd.startProcess(apps[0] + " " + f) pykd.go() # print information at crash site r_o = pykd.dbgCommand('r') # print r_o k_o = pykd.dbgCommand('k') #print k_o stackTrace = "" firstLine = True lines = k_o.split("\n") for line in lines: if firstLine: firstLine = False
def setUp(self): pykd.startProcess(target.appPath + " breakhandlertest") self.targetModule = pykd.module(target.moduleName) self.targetModule.reload() pykd.go()
def run(self): if self.timeout != 0: self.timer = Timer(self.timeout, self.timeout_func) self.timer.start() self.do_stop = False self.id = pykd.startProcess(self.program, debugChildren=True) if self.handler is None: self.handler = ExceptionHandler() while not self.handler.exception_occurred and not self.do_stop: try: pykd.go() except: break if self.do_stop: try: pykd.dbgCommand(".kill") except: log("Exception killing target: %s" % str(sys.exc_info()[1])) return None if self.timer is not None: self.timer.cancel() ret = None if self.handler.exception_occurred: tmp = pykd.dbgCommand("k 1") if tmp.find("Wow64NotifyDebugger") > -1: pykd.dbgCommand(".effmach x86") stack_trace = pykd.dbgCommand("k") registers = pykd.dbgCommand("r") exploitable = None msec_path = None if self.exploitable_path is None: if self.mode == 32: msec_path = os.path.join(self.windbg_path, r"Debuggers\x86\winext") elif self.mode == 64: msec_path = os.path.join(self.windbg_path, r"Debuggers\x64\winext") elif self.mode == "arm": msec_path = os.path.join(self.windbg_path, r"Debuggers\arm\winext") else: raise Exception("Unknown mode %s, known ones are 32, 64 or 'arm'." % self.mode) else: msec_path = self.exploitable_path if msec_path is not None: full_msec_path = os.path.join(msec_path, r"msec.dll") if os.path.exists(full_msec_path): try: msec_handle = pykd.loadExt(full_msec_path) commandOutput = pykd.callExt(msec_handle, "exploitable", "") exploitable = commandOutput except: log("Error loading extension: " + str(sys.exc_info()[1])) try: if self.minidump_path is not None: pykd.dbgCommand(r".dump /m /u %s\\" % self.minidump_path) log("*** Minidump written at %s" % self.minidump_path) except: log("!!! Error saving minidump:" + str(sys.exc_info()[1])) ret = self.create_crash_data(registers, stack_trace, exploitable) print pykd.dbgCommand("k 10") print pykd.dbgCommand("r") print exploitable crash_data_buf = self.crash_data.dump_json() ret = self.crash_data.dump_dict() print print "Yep, we got a crash! \o/" print return ret
print "[+]\tAdding Rawsize, VirtualSize of 0x1000, Header marked [R+W+X]" sections.push_back(VirtualSize=0x00001000, RawSize=0x00001000, Characteristics=0xE0000020) time.sleep(1.0) print "[+]\tNew PE section added..." except SectionDoublePError as e: print e pe.write(filename="tempCave.exe") time.sleep(0.5) print "[+]Code caving successful..." print "=============================\n" #exe_path = raw_input("Enter exe path: ") #print "[+]Starting the executable" print "[+]Started file analysis" pykd.startProcess("tempCave.exe") print "[+]setting entry point breakpoint" pykd.dbgCommand("bp $exentry") print "[+]stepping into breakpoint" pykd.dbgCommand("g") print "[+]Fetching address of esp @entryPoint" #print "[+]" + str(pykd.dbgCommand("r esp")) initial_esp = str(pykd.dbgCommand("r esp")) #print type(initial_esp) initial_esp = initial_esp.split("=")[1] #print "splitted..." + initial_esp initial_esp = "0x"+initial_esp print "[+]Initial ESP: " + initial_esp initial_esp = int(initial_esp,16) time.sleep(1)
def run(self): if self.timeout != 0: self.timer = Timer(self.timeout, self.timeout_func) self.timer.start() self.do_stop = False self.id = pykd.startProcess(self.program, debugChildren=True) while not self.handler.exception_occurred and not self.do_stop: try: pykd.go() except: break if self.do_stop: try: pykd.dbgCommand(".kill") except: log("Exception killing target: %s" % str(sys.exc_info()[1])) return None if self.timer is not None: self.timer.cancel() ret = None if self.handler.exception_occurred: stack_trace = pykd.dbgCommand("k") registers = pykd.dbgCommand("r") exploitable = None msec_path = None if self.exploitable_path is None: if self.mode == 32: msec_path = os.path.join(self.windbg_path, r"Debuggers\x86\winext") elif self.mode == 64: msec_path = os.path.join(self.windbg_path, r"Debuggers\x64\winext") elif self.mode == "arm": msec_path = os.path.join(self.windbg_path, r"Debuggers\arm\winext") else: raise Exception("Unknown mode %s, known ones are 32, 64 or 'arm'." % self.mode) else: msec_path = self.exploitable_path print msec_path if msec_path is not None: full_msec_path = os.path.join(msec_path, r"msec.dll") print full_msec_path if os.path.exists(full_msec_path): print "bai?" os.chdir(msec_path) msec_handle = pykd.loadExt(full_msec_path) commandOutput = pykd.callExt(msec_handle, "exploitable", "") exploitable = commandOutput print "exploitable?", exploitable ret = self.create_crash_data(registers, stack_trace, exploitable) print pykd.dbgCommand("k 8") print pykd.dbgCommand("r") print exploitable crash_data_buf = self.crash_data.dump_json() ret = self.crash_data.dump_dict() print print "Yep, we got a crash! \o/" print return ret
def start_process(self, path, arguments, debug_child=False): self._process_id = pykd.startProcess(path + " " + arguments, debugChildren=debug_child) self._logger.debug("Process created")
def setUp(self): pykd.startProcess(target.appPath) pykd.startProcess(target.appPath) pykd.startProcess(target.appPath)
def setUp(self): self.processId = pykd.startProcess(target.appPath + " stacktest") pykd.go() # skip initial breakpoint
def start_process(self, arguments): self._process_id = pykd.startProcess(self._program_path + " " + arguments, debugChildren=self._debug_child) self._logger.debug("Process created")