Exemplo n.º 1
0
    def __init__(self):

        # store the allocations we find
        self.allocs = []
        self.ret_addr = None
        self.bp_heap_alloc = None

        # offsets to these symbols via reversing
        # tested on FoxitReader.exe v9.0.1.1049 (sha1: a01a5bde0699abda8294d73544a1ec6b4115fa68)
        # you will need to update this on different versions
        self.__CIatan_pentium4 = 0x13dc840
        self.__CIasin_pentium4 = 0x13dcb30

        addr = self.get_address("FoxitReader!CertFreeCertificateChain")

        if addr is None:
            return

        # address offsets for later use
        self.asan_addr = (int(addr, 16) + self.__CIatan_pentium4)
        self.asin_addr = (int(addr, 16) + self.__CIasin_pentium4)

        print("(+) setting up __CIatan_pentium4 bp")
        self.bp_asan = pykd.setBp((int(addr, 16) + self.__CIatan_pentium4), self._cb_CIatan_pentium4)

        print("(+) setting up __CIasin_pentium4 bp")
        self.bp_asin = pykd.setBp((int(addr, 16) + self.__CIasin_pentium4), self._cb_CIasin_pentium4)
        self.bp_end_atan = None
        self.bp_end_asin = None
        pykd.go()
Exemplo n.º 2
0
def _run(process_id, log_file):
    """
    _run(process_id, log_file) -> None
    _run() takes the process_id of the process to attach to.
    The collected debugger data is saved to log_file.

    returns None
    """
    with open(log_file, "w") as out_fp:
        out_fp.write("\nAttaching WinDBG debugger...\n")
        try:
            session_id = pykd.attachProcess(process_id)
            while True:
                pykd.go()
                if not pykd.getLastException().firstChance:
                    break
            dbg_info = pykd.dbgCommand(".lastevent;r;k")
            if dbg_info is not None:
                out_fp.write("%s\n" % dbg_info)
            pykd.detachProcess(session_id)
            out_fp.write("Debugger detached.\n")
        except pykd.DbgException as dbg_e:
            out_fp.write("DbgException: %s\n" % dbg_e)
        except KeyboardInterrupt:
            pass
Exemplo n.º 3
0
    def run_until_crash(self):
        while True:
            if self._exception_handler.got_bp():
                self.shell()

            # You can have crash while interacting with shell.
            if self._exception_handler.got_crash():
                break

            pykd.go()
Exemplo n.º 4
0
def main(init_sym, mem_limit, timeout):
    run_time = time.time()
    timeout = timeout + time.time()
    pykd.dbgCommand("bu %x" % sym_off_to_addr(init_sym))
    page_size = get_page_size()
    pykd.go()
    target_pid = get_pid()
    pykd.removeBp(get_bp_hit())
    pykd.dbgCommand("bm MSVCR*!malloc")
    pykd.dbgCommand("bm MSVCR*!realloc")
    pykd.dbgCommand("bm MSVCR*!calloc")
    log.debug("target pid: %d", target_pid)
    while time.time() < timeout:
        pykd.go()
        cur_mem = get_mem_usage(target_pid)
        if cur_mem >= mem_limit:
            log.info("missed request! current memory: %d", cur_mem)
            break
        req = requested_mem_size()
        if req == 0:
            log.info("unexpected break on: %s", get_current_stack()[0])
            continue
        if req > page_size:
            if req % page_size:
                page_req = page_size * ((req / page_size) + 1)
            else:
                page_req = page_size * (req / page_size)
        else:
            page_req = page_size
        if cur_mem + page_req >= mem_limit:
            log.info("request will exceed limit, current: %d, request %d",
                     cur_mem, req)
            break

    log.info("*" * 60)
    if time.time() < timeout:
        set_thread(get_hung_thread())
        call_stack = get_current_stack()
        if not call_stack:
            log.info("Unable to trace!")
        for line in call_stack:
            log.info("STACK_FRAME:%s" % line)
    else:
        log.info("Timeout!")
    log.info("*" * 60)
    log.info("----- STATS -----")
    log.info("MEMORY LIMIT: %d MB", mem_limit / 0x100000)
    log.info("DGB TIME: %0.2f", time.time() - run_time)
    log.info("PROC TIME: %0.2f", get_proc_run_time())
    log.info("THREAD TIME: %0.2f",
             get_thread_run_time(get_thread_list()[get_hung_thread()]))
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
 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())
Exemplo n.º 7
0
def main(init_sym, mem_limit, timeout):
    run_time = time.time()
    timeout = timeout + time.time()
    pykd.dbgCommand("bu %x" % sym_off_to_addr(init_sym))
    page_size = get_page_size()
    pykd.go()
    target_pid = get_pid()
    pykd.removeBp(get_bp_hit())
    pykd.dbgCommand("bm MSVCR*!malloc")
    pykd.dbgCommand("bm MSVCR*!realloc")
    pykd.dbgCommand("bm MSVCR*!calloc")
    log.debug("target pid: %d", target_pid)
    while time.time() < timeout:
        pykd.go()
        cur_mem = get_mem_usage(target_pid)
        if cur_mem >= mem_limit:
            log.info("missed request! current memory: %d", cur_mem)
            break
        req = requested_mem_size()
        if req == 0:
            log.info("unexpected break on: %s", get_current_stack()[0])
            continue
        if req > page_size:
            if req % page_size:
                page_req = page_size * ((req/page_size)+1)
            else:
                page_req = page_size * (req/page_size)
        else:
            page_req = page_size
        if cur_mem + page_req >= mem_limit:
            log.info("request will exceed limit, current: %d, request %d", cur_mem, req)
            break

    log.info("*" * 60)
    if time.time() < timeout:
        set_thread(get_hung_thread())
        call_stack = get_current_stack()
        if not call_stack:
            log.info("Unable to trace!")
        for line in call_stack:
            log.info("STACK_FRAME:%s" % line)
    else:
        log.info("Timeout!")
    log.info("*" * 60)
    log.info("----- STATS -----")
    log.info("MEMORY LIMIT: %d MB", mem_limit/0x100000)
    log.info("DGB TIME: %0.2f", time.time()-run_time)
    log.info("PROC TIME: %0.2f", get_proc_run_time())
    log.info("THREAD TIME: %0.2f", get_thread_run_time(get_thread_list()[get_hung_thread()]))
Exemplo n.º 8
0
def Monitor():
    print "[*] Attaching to TaniumReceiver.exe"
    process = filter(lambda p: p.name() == "TaniumReceiver.exe",
                     psutil.process_iter())
    for process_id in process:
        print "[*] PID: %s" % process_id.pid
    pykd.initialize()
    Handler = ExceptionHandler()
    try:
        pykd.attachProcess(process_id.pid)
    except:
        print "[!] Error attaching to process"
        sys.exit(1)
    print "[*] Success!"
    pykd.go()
Exemplo n.º 9
0
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()
Exemplo n.º 10
0
	def __init__(self):
		self.instruction_list = []
		if DEBUG:
			print("[+] Acquiring assembly code...")
			print(f" [=] Setting breakpoint at {hex(shellcodeAddress)}")
		self.bp = pykd.setBp(shellcodeAddress, self.acquire_next_instruction)
		while True:
			try:
				pykd.go()
			except:
				break

		if DEBUG:
			print("[+] Finished getting assembly!")

		self.instruction_list = self.instruction_list[len(lengthInstruction.split("\n")):]
Exemplo n.º 11
0
Arquivo: debug.py Projeto: Junch/debug
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 testRemoveAllBp(self):
     bp1 = pykd.setBp(self.targetModule.CdeclFunc)
     bp2 = pykd.setBp(self.targetModule.CdeclFunc + 1)
     bp3 = pykd.setBp(self.targetModule.CdeclFunc + 2)
     self.assertEqual(3, pykd.getNumberBreakpoints())
     pykd.removeAllBp()
     self.assertEqual(0, pykd.getNumberBreakpoints())
     self.assertEqual(pykd.executionStatus.NoDebuggee, pykd.go())
Exemplo n.º 13
0
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()
Exemplo n.º 14
0
    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)
Exemplo n.º 15
0
 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())
Exemplo n.º 16
0
    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)
Exemplo n.º 17
0
    def run(self):
        self.winBr.initLog()
        self.winBr.dbiprintf("< WinDbg DBI >")
        if self.winBr.getImageInfo() != 0:
            self.winBr.dbiprintf(
                "[!] Check the symbol path ( Recommended : %s )" %
                self.symPath)
            return 1
        if self.winBr.getSectionInfo() != 0:
            return 2
        if self.winBr.procImageBase != -1 and self.winBr.procImageEnd != -1 and self.winBr.procImageSize != 0:
            memBpHandler = MemBpHandler(self.lObfusMem, self.winBr)
            memBpHandler.forceSetIat(self.winBr.procImageBase + 0x2000,
                                     0xa00)  # IAT
            memBpHandler.forceSetCode(self.winBr.lSection[1][0],
                                      self.winBr.lSection[1][3])
            handler_AllocateVirtualMemory = Handler_AllocateVirtualMemory(
                self.lObfusMem, self.winBr, memBpHandler)
            handler_FreeVirtualMemory = Handler_FreeVirtualMemory(
                self.lObfusMem, self.winBr, memBpHandler)

            pykd.go()
            self.winBr.dbiprintf("[!] PYKD retake the control")

            self.patchCall(memBpHandler.lIatCodePatch)
            self.winBr.dbiprintf("[+] Dump %d sections" %
                                 self.maxDumpSectionNum)
            for i in range(self.maxDumpSectionNum):
                s = self.winBr.lSection[i]
                self.dumpMemory(self.dumpPath, s[0], s[3])
            self.rebuild(self.dumpPath)

            self.winBr.dbiprintf("[!] PE info")
            self.winBr.dbiprintf(" -> OEP : 0x%08x ( 0x%08x + 0x%08x )" %
                                 (memBpHandler.oep, self.winBr.procImageBase,
                                  memBpHandler.oep - self.winBr.procImageBase))
            self.winBr.dbiprintf(
                " -> IAT : 0x%08x ( 0x%08x + 0x%08x )" %
                (memBpHandler.pIatBase, self.winBr.procImageBase,
                 memBpHandler.pIatBase - self.winBr.procImageBase))
            self.winBr.dbiprintf(" -> IAT size : 0x%08x" %
                                 (memBpHandler.sizeIat))

        return 0
    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 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])
Exemplo n.º 20
0
def InitTracer():
    global DriverObject
    global ImageBase
    global NtImageEnd

    NtModule    = pykd.module("nt")
    NtImageBase = NtModule.begin()
    NtImageEnd  = NtModule.end()

    pykd.dbgCommand("ba e1 IopLoadDriver+4bd")
    pykd.dbgCommand("ba e1 IopLoadDriver+4c2")
    pykd.go()

    while(1):
        regPath = pykd.dbgCommand("du /c40 @rdx+10")
        if "VmpDriver.vmp" in regPath:
            print "[*] Find VMP Driver"
            DriverObject = pykd.reg("rcx")
            print "\t[-] Driver Object : 0x{:X}".format(DriverObject)
            ImageBase =pykd.ptrPtr(DriverObject+0x18)    # DriverObject.DriverStart
            print "\t[-] ImageBase Address : 0x{:X}".format(ImageBase)
            VMPTracingSub.GetSectionInfo(ImageBase)
            EntryPoint = ImageBase + VMPTracingSub.EntryPoint_Off
            strEntryPoint = hex(EntryPoint).rstrip("L")
            pykd.dbgCommand("ba e1 "+strEntryPoint)
            pykd.go()
            pykd.dbgCommand("bc 2")
            return

        pykd.go()
Exemplo n.º 21
0
def find_next_sym(next_bp, prev_bp, timeout):
    iters = 100
    found_sym = False
    sample_time = 0

    set_bp(next_bp, 0, 1)
    set_bp(prev_bp, 1, iters)
    while not is_complete():
        pykd.go()
        curr_bp = get_bp_hit()
        target_time = get_proc_run_time()
        log.debug("target time %0.2f", target_time)
        if curr_bp == 1:
            if target_time >= timeout:
                break
            iter_duration = target_time - sample_time
            if iter_duration < 0.5:  # optimization
                if iters < 25600:
                    iters *= 2
                    log.debug("iter duration: %0.2f, (x2) prev_bp iters: %d",
                              iter_duration, iters)
            elif iter_duration >= 0.5 and iter_duration < 0.85:  # optimization
                iters += 100
                log.debug("iter duration: %0.2f, (+100) prev_bp iters: %d",
                          iter_duration, iters)
            set_bp(prev_bp, 1, iters)
        elif curr_bp == 0:
            found_sym = True
            break
        else:
            log.debug("break not triggered by breakpoint")
            if pykd.dbgCommand(".lastevent").find(
                    "(!!! second chance !!!)") != -1:
                raise RuntimeError("Expected Timeout found Access violation!")
        sample_time = target_time

    pykd.removeBp(1)
    pykd.removeBp(0)
    return found_sym
    def testBreakpointCondition2(self):
        def makebpcallback(n):
            def bpcallback():
                if pykd.getParam("b") > n:
                    return pykd.eventResult.Break
                return pykd.eventResult.Proceed

            return bpcallback

        bp = pykd.setBp(
            self.targetModule.typedVar("CdeclFunc").getDebugStart(),
            makebpcallback(100))
        self.assertEqual(pykd.executionStatus.NoDebuggee, pykd.go())
Exemplo n.º 23
0
	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 testBreakpointHandler(self):
        class BreakpointHandler(pykd.eventHandler):
            def __init__(self):
                super(BreakpointHandler, self).__init__()
                self.count = 0

            def onBreakpoint(self, bpid_):
                self.count = self.count + 1
                return True

        handler = BreakpointHandler()
        bp = pykd.setBp(self.targetModule.CdeclFunc)
        self.assertEqual(pykd.executionStatus.Break, pykd.go())
        self.assertEqual(1, handler.count)
    def testBreakpointClass(self):
        class MyBreakpoint(pykd.breakpoint):
            def __init__(self, offset):
                super(MyBreakpoint, self).__init__(offset)
                self.count = 0

            def onHit(self):
                self.count = self.count + 1
                return True

        bp = MyBreakpoint(
            self.targetModule.typedVar("CdeclFunc").getDebugStart())
        self.assertEqual(pykd.executionStatus.Break, pykd.go())
        self.assertEqual(1, bp.count)
Exemplo n.º 26
0
def find_next_sym(next_bp, prev_bp, timeout):
    iters = 100
    found_sym = False
    sample_time = 0

    set_bp(next_bp, 0, 1)
    set_bp(prev_bp, 1, iters)
    while not is_complete():
        pykd.go()
        curr_bp = get_bp_hit()
        target_time = get_proc_run_time()
        log.debug("target time %0.2f", target_time)
        if curr_bp == 1:
            if target_time >= timeout:
                break
            iter_duration = target_time - sample_time
            if iter_duration < 0.5:  # optimization
                if iters < 25600:
                    iters *= 2
                    log.debug("iter duration: %0.2f, (x2) prev_bp iters: %d", iter_duration, iters)
            elif iter_duration >= 0.5 and iter_duration < 0.85:  # optimization
                iters += 100
                log.debug("iter duration: %0.2f, (+100) prev_bp iters: %d", iter_duration, iters)
            set_bp(prev_bp, 1, iters)
        elif curr_bp == 0:
            found_sym = True
            break
        else:
            log.debug("break not triggered by breakpoint")
            if pykd.dbgCommand(".lastevent").find("(!!! second chance !!!)") != -1:
                raise RuntimeError("Expected Timeout found Access violation!")
        sample_time = target_time

    pykd.removeBp(1)
    pykd.removeBp(0)
    return found_sym
Exemplo n.º 27
0
    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
Exemplo n.º 28
0
    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 setUp(self):
     self.processId = pykd.startProcess(target.appPath + " stacktest")
     pykd.go()  # skip initial breakpoint
Exemplo n.º 30
0
  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
Exemplo n.º 31
0
            self.out += hex(pykd.reg("r9")) + ") = "
            if self.bp_end == None:
                disas = pykd.dbgCommand("uf ntdll!RtlReAllocateHeap").split(
                    '\n')
                for i in disas:
                    if 'ret' in i:
                        self.ret_addr = i.split()[0]
                        break
                self.bp_end = pykd.setBp(pykd.expr(self.ret_addr),
                                         self.return_call_back)
            return False

    def return_call_back(self):
        log.write(self.out + hex(pykd.reg(return_reg)) + "\n")
        return False


log = open(home + "\log.log", "w+")

try:
    pykd.reg("rax")
except:
    arch_bits = 32
    return_reg = "eax"
    stack_pointer = "esp"

handle_allocate_heap()
handle_free_heap()
handle_realloc_heap()
pykd.go()
Exemplo n.º 32
0
 def run(self):
     while not self._event_handler.exceptionOccurred():
         pykd.go()
     self._logger.debug("Crash occurred")
     self._crash_occurred = True
Exemplo n.º 33
0
		return None
	if result_count > 1:
		print "[-] Warning, more than one result for", localAddr	
	return res.split()[0]
	
class handle_allocate_heap(pykd.eventHandler):
	def __init__(self):
		addr = get_address("ntdll!RtlAllocateHeap")
		if addr == None:
			return
		self.bp_init = pykd.setBp(int(addr, 16), self.enter_call_back)
		self.bp_end = None
		
	def enter_call_back(self,bp):
		print "RtlAllocateHeap called." 
		if self.bp_end == None:
			disas = pykd.dbgCommand("uf ntdll!RtlAllocateHeap").split('\n')
			for i in disas:
				if 'ret' in i:
					self.ret_addr = i.split()[0]
					break
			self.bp_end = pykd.setBp(int(self.ret_addr, 16), self.return_call_back)
		return False
	
	def return_call_back(self,bp):
		print "RtlAllocateHeap returned."
		return False

handle_allocate_heap()
pykd.go()
Exemplo n.º 34
0
 def run(self):
     while not self._event_handler.exceptionOccurred():
         pykd.go()
     self._logger.debug("Crash occurred")
     self._crash_occurred = True
Exemplo n.º 35
0
 def go(self):
     pykd.go()
Exemplo n.º 36
0
    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
Exemplo n.º 37
0
  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
Exemplo n.º 38
0
 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()