Exemple #1
0
def analyze_crash(cmd):
    """
    This is called with the command line (including the filename)
    which caused the crash before.
    It is a late analysis routine which sorts the crashes.
    """

    global file_info
    global victim_filename
    global crash_filename

    # TODO: This may not always be the case
    victim_filename, crash_filename = cmd
    print "=== [*] Analyzing %s" % crash_filename
    file_binary = fileops.get_base64_contents(crash_filename)

    if file_binary:
        file_info = (crash_filename, file_binary)

    # Instance a Debug object, passing it the event handler callback.
    debug = Debug(crash_event_handler, bKillOnExit = True)
    try:

        # Start a new process for debugging.
        debug.execv(cmd)

        # Wait for the debugee to finish.
        debug.loop()

    # Stop the debugger.
    finally:
        debug.stop()
Exemple #2
0
def main( argv ):

    # Parse the command line arguments
    options = parse_cmdline(argv)

    # Create the event handler object
    eventHandler = Tracer()
    eventHandler.options = options

    # Create the debug object
    debug = Debug(eventHandler, bHostileCode = options.hostile)
    try:

        # Attach to the targets
        for pid in options.attach:
            debug.attach(pid)
        for argv in options.console:
            debug.execv(argv, bConsole = True,  bFollow = options.follow)
        for argv in options.windowed:
            debug.execv(argv, bConsole = False, bFollow = options.follow)

        # Make sure the debugees die if the debugger dies unexpectedly
        debug.system.set_kill_on_exit_mode(True)

        # Run the debug loop
        debug.loop()

    # Stop the debugger
    finally:
        if not options.autodetach:
            debug.kill_all(bIgnoreExceptions = True)
        debug.stop()
Exemple #3
0
def main(argv):
    # Parse the command line arguments
    options = parse_cmdline(argv)

    # Create the event handler object
    eventHandler = Tracer()
    eventHandler.options = options

    # Create the debug object
    debug = Debug(eventHandler, bHostileCode=options.hostile)
    try:

        # Attach to the targets
        for pid in options.attach:
            debug.attach(pid)
        for argv in options.console:
            debug.execv(argv, bConsole=True, bFollow=options.follow)
        for argv in options.windowed:
            debug.execv(argv, bConsole=False, bFollow=options.follow)

        # Make sure the debugees die if the debugger dies unexpectedly
        debug.system.set_kill_on_exit_mode(True)

        # Run the debug loop
        debug.loop()

    # Stop the debugger
    finally:
        if not options.autodetach:
            debug.kill_all(bIgnoreExceptions=True)
        debug.stop()
def simple_debugger(address_file, program_file, arg_check):
    
    process = None
    debug = Debug(HitTracerEventHandler(address_file, program_file, arg_check))
    
    
    try:
        # Lookup currently running processes
        debug.system.scan_processes()
        
        for (process, name) in debug.system.find_processes_by_filename(program_file):
            print "[*] Found %d: %s" % (process.get_pid(), name)
            
            # Attach to it
            debug.attach(process.get_pid())
            
        if process == None:
            print "[*] Fatal. Process not found. Is it running?"
            sys.exit(1)
            
        # Wait for all debugees to finish
        debug.loop()
        
    # Cleanup actions
    finally:
        debug.stop()
def simple_debugger(argv):
    # Instance a Debug object.
    debug = Debug()
    try:
        # Start a new process for debugging.
        debug.execv(argv)
        # Launch the interactive debugger.
        debug.interactive()
    # Stop the debugger.
    finally:
        debug.stop()
    return
Exemple #6
0
def extract_payload(file_path):
    """
    Function that'll handle winappdbg debug
    :param file_path: path of QuantLoader
    :return: bool
    """
    debug = Debug(QHandler())
    try:
        debug.execv([file_path])
        debug.loop()
    finally:
        debug.stop()
Exemple #7
0
def simple_debugger(argv):

    # Instance a Debug object, passing it the MyEventHandler instance
    debug = Debug(MyEventHandler())
    try:

        debug.execv(argv)

        debug.loop()

    # Stop the debugger
    finally:
        debug.stop()
def debug_ovas(ovas_pid, test_payload, test_char, good_chars):
    # Instance a Debug object.
    debug = Debug(functools.partial(bad_characters_handler, test_payload,
                                    test_char, good_chars),
                  bKillOnExit=True)
    try:
        # Attach to a running process.
        debug.attach(ovas_pid)

        # Wait for the debugee to finish.
        debug.loop()
    finally:
        # Stop the debugger.
        debug.stop()
Exemple #9
0
def simple_debugger( argv ):

    # Instance a Debug object, passing it the event handler callback.
    debug = Debug( my_event_handler, bKillOnExit = True )
    try:

        # Start a new process for debugging.
        debug.execv( argv )

        # Wait for the debugee to finish.
        debug.loop()

    # Stop the debugger.
    finally:
        debug.stop()
Exemple #10
0
def simple_debugger(argv):

    # Instance a Debug object, passing it the event handler callback.
    debug = Debug(my_event_handler, bKillOnExit=True)
    try:

        # Start a new process for debugging.
        debug.execv(argv)

        # Wait for the debugee to finish.
        debug.loop()

    # Stop the debugger.
    finally:
        debug.stop()
Exemple #11
0
def simple_debugger( argv ):

    # Instance a Debug object.
    debug = Debug()
    try:

        # Start a new process for debugging.
        debug.execv( argv )

        # Launch the interactive debugger.
        debug.interactive()

    # Stop the debugger.
    finally:
        debug.stop()
def DebugProgram(filepath):
	#Instance a Debug object.
	debug_args = list()
	debug_args.insert(0,PROGRAM_PATH)
	debug_args.insert(len(debug_args),filepath)

	debug = Debug(AccessViolationHandlerWINAPPDBG, bKillOnExit = True)
	#debug.system.load_dbghelp("C:\\Program Files\\Debugging Tools for Windows (x86)\\dbghelp.dll")
	System.fix_symbol_store_path(symbol_store_path = "C:\\ProgramData\\Dbg\\sym",remote = True,force = True) #enter local symbol path here if you have downloaded symbols
	System.set_kill_on_exit_mode(True)
	try:
		 # The execution time limit is 5 seconds.
		maxTime = time() + 5
		# Start a new process for debugging.
		debug.execv(debug_args)

		# Wait for the debugee to finish.
		#debug.loop()
		 # Loop while calc.exe is alive and the time limit wasn't reached.
		while debug and time() < maxTime:
			try:

				# Get the next debug event.
				debug.wait(1000)  # 1 second accuracy

				# Show the current time on screen.
				#print time()

			# If wait() times out just try again.
			# On any other error stop debugging.
			except WindowsError, e:
				if e.winerror in (win32.ERROR_SEM_TIMEOUT,
								  win32.WAIT_TIMEOUT):
					continue
				raise

			# Dispatch the event and continue execution.
			try:
				debug.dispatch()
			finally:
				debug.cont()
		# Stop the debugger.
	finally:
		debug.stop()
Exemple #13
0
def simple_debugger(argv):

    # Instance a Debug object, passing it the event handler callback.
    debug = Debug(my_event_handler, bKillOnExit=True)

    timer = threading.Timer(2.0, killProc, [
        os.path.basename(argv[0]),
    ])
    try:
        # Start a new process for debugging.
        debug.execv(argv)

        timer.start()
        # Wait for the debugee to finish.
        debug.loop()
    # Stop the debugger.
    finally:
        debug.stop()
    print " [*]kill timer"
    timer.cancel()  # cancle是每一轮fuzzing之后都会执行?
Exemple #14
0
def main(argv):
    options = parse_cmdline(argv)

    # Create the event handler object
    eventHandler = EventForwarder(MemoryWatcher, options)

    # Create the debug object
    debug = Debug(eventHandler, bKillOnExit=True)

    try:

        # Attach to the targets
        for pid in options.attach:
            logger.log_text("Attaching to %d" % pid)
            debug.attach(pid)

        # Run the debug loop
        debug.loop()

    # Stop the debugger
    finally:
        debug.stop()
Exemple #15
0
class WinAppDbgController(BaseController):
    '''
    WinAppDbgController controls a server process
    by starting it on setup making sure it stays up.
    It uses winappdbg to attach to the target processes.
    '''

    def __init__(self, name, process_path, process_args=[], sql_crash_db='sqlite:///crashes.sqlite', logger=None):
        '''
        :param name: name of the object
        :param process_path: path to the target executable
        :param process_args: arguments to pass to the process
        :param attach: try to attach if process path
        :param sql_crash_db: sql alchemy connection string to crash db (default:sqlite:///crashes.sqlite)
        :param logger: logger for this object (default: None)
        '''
        super(WinAppDbgController, self).__init__(name, logger)
        assert(process_path)
        assert(os.path.exists(process_path))
        self._process_path = process_path
        self._process_name = os.path.basename(process_path)
        self._process_args = process_args
        self._process = None
        self._sql_crash_db = sql_crash_db
        self._crash_event_complete = threading.Event()
        self._server_is_up = threading.Event()
        self._crash_event_complete.set()
        self._debug = Debug(lambda x: _my_event_handler(self, x), bKillOnExit=True)

    def _debug_server(self):
        '''
        debugger thread
        '''
        try:
            self._process = None
            # Start a new process for debugging.
            argv = [self._process_path] + self._process_args
            self.logger.debug('debugger starting server: %s' % argv)
            try:
                self._process = self._debug.execv(argv, bFollow=True)
            except WindowsError:
                self.logger.error('debug_server received exception', traceback.fmt_exc())
            self._pid = self._process.get_pid()
            self.logger.info('process started. pid=%d' % self._pid)

            # Wait for the debugee to finish.
            self._server_is_up.set()
            self._debug.loop()
        except:
            self.logger.error('Got an exception in _debug_server')
            self.logger.error(traceback.format_exc())
        # Stop the debugger.
        finally:
            self._debug.stop()
            self._process = None
            self._pid = -1
            self._crash_event_complete.set()

    def _start_server_thread(self):
        '''
        start the server thread
        '''
        self._server_is_up.clear()
        self.server_thread = FuncThread(self._debug_server)
        self.server_thread.start()
        self.logger.info('waiting for server to be up')
        self._server_is_up.wait()
        self.logger.info('server should be up')

    def _kill_all_processes(self):
        '''
        kill all processes with the same name
        :return: True if all matching processes were killed properly, False otherwise
        '''
        res = True
        # Lookup the currently running processes.
        self._debug.system.scan_processes()
        # For all processes that match the requested filename...
        for (process, name) in self._debug.system.find_processes_by_filename(self._process_name):
            process_pid = process.get_pid()
            self.logger.info('found process %s (%d) - trying to kill it' % (name, process_pid))
            try:
                process.kill()
                self.logger.info('successfully killed %s (%d)' % (name, process_pid))
            except:
                self.logger.error('failed to kill %s (%d) [%s]' % (name, process_pid, traceback.format_exc()))
                res = False
        return res

    def setup(self):
        '''
        Called at the beginning of a fuzzing session.
        Will start the server up.
        '''
        self._stop_process()
        self._start_server_thread()

    def teardown(self):
        self._stop_process()
        self._process = None
        super(WinAppDbgController, self).teardown()

    def pre_test(self, test_number):
        super(WinAppDbgController, self).pre_test(test_number)
        if not self._is_victim_alive():
            self.logger.error('victim is dead, restarting...')
            # self.report.failed('server is down during pre_test - failure it probably from previous test (%d)' % (test_number-1))
            self._restart()
            self._crash_event_complete.set()
        else:
            self.logger.debug('victim is alive (pid=%d)' % self._pid)

    def post_test(self):
        self.logger.debug('in')
        time.sleep(1)
        self.logger.debug('after sleep')
        res = self._crash_event_complete.wait()
        self.logger.debug('after wait')
        if not res:
            self.report.failed('incomplete crash detected')
        super(WinAppDbgController, self).post_test()
        self.logger.debug('out')

    def _stop_process(self):
        '''
        Stop the process (if running)
        '''
        return self._kill_all_processes()

    def _stop_process_old(self):
        '''
        :return: True if process was killed, False otherwise
        '''
        if self._is_victim_alive():
            self._process.kill()
            time.sleep(0.5)
            if self._is_victim_alive():
                self._process.kill()
                time.sleep(0.5)
                if self._is_victim_alive():
                    raise Exception('Failed to kill client process')
            self._debug.stop()
            return True
        else:
            self._debug.stop()
            return False

    def _restart(self):
        '''
        restart the process
        '''
        self._stop_process()
        self.server_thread.join(1)
        time.sleep(3)
        self._server_is_up.clear()
        self._start_server_thread()

    def _is_victim_alive(self):
        '''
        check if process running
        '''
        if self._process:
            self.logger.debug('process pid: %d' % self._pid)
            is_alive = self._process.is_alive()
            is_debugee_started = self._debug.is_debugee_started(self._pid)
            self.logger.debug('is_alive = %s' % is_alive)
            self.logger.debug('is_debugee_started = %s' % is_debugee_started)
            return (is_alive and is_debugee_started)
        else:
            self.logger.debug('_process is None')
        return False
Exemple #16
0
class WinAppDbgTarget(ServerTarget):
    def __init__(self,
                 name,
                 process_path,
                 process_args=[],
                 sql_crash_db="sqlite:///crashes.sqlite",
                 logger=None):
        """
        :param name: name of the object
        :param process_path: path to the target executable
        :param process_args: arguments to pass to the process
        :param sql_crash_db: sql alchemy connection string to crash db (default:sqlite:///crashes.sqlite)
        :param logger: logger for this object (default: None)
        """
        super(WinAppDbgTarget, self).__init__(name, logger)
        assert process_path
        assert (os.path.exists(process_path))
        self._process_path = process_path
        self._process_name = os.path.basename(process_path)
        self._process_args = process_args
        self._process = None
        self._sql_crash_db = sql_crash_db
        self._crash_event_complete = threading.Event()
        self._server_is_up = threading.Event()
        self._crash_event_complete.set()
        self._debug = Debug(lambda x: _my_event_handler(self, x),
                            bKillOnExit=True)

    def _debug_server(self):
        """
        debugger thread
        """
        try:
            self._process = None
            # Start a new process for debugging.
            argv = [self._process_path] + self._process_args
            self.logger.debug("debugger starting server: %s" % argv)
            try:
                self._process = self._debug.execv(argv, bFollow=True)
            except WindowsError:
                self.logger.error("debug_server received exception",
                                  traceback.fmt_exc())
            self._pid = self._process.get_pid()
            self.logger.info("process started. pid=%d" % self._pid)

            # Wait for the debugee to finish.
            self._server_is_up.set()
            self._debug.loop()
        except:
            self.logger.error("Got an exception in _debug_server")
            self.logger.error(traceback.format_exc())
        # Stop the debugger.
        finally:
            self._debug.stop()
            self._process = None
            self._pid = -1
            self._crash_event_complete.set()

    def _start_server_thread(self):
        """
        start the server thread
        """
        self._server_is_up.clear()
        self.server_thread = FuncThread(self._debug_server)
        self.server_thread.start()
        self.logger.info("waiting for server to be up")
        self._server_is_up.wait()
        self.logger.info("server should be up")

    def _kill_all_processes(self):
        """
        kill all processes with the same name
        :return: True if all matching processes were killed properly, False otherwise
        """
        res = True
        # Lookup the currently running processes.
        self._debug.system.scan_processes()
        # For all processes that match the requested filename...
        for (process, name) in self._debug.system.find_processes_by_filename(
                self._process_name):
            process_pid = process.get_pid()
            self.logger.info("found process %s (%d) - trying to kill it" %
                             (name, process_pid))
            try:
                process.kill()
                self.logger.info("successfully killed %s (%d)" %
                                 (name, process_pid))
            except:
                self.logger.error("failed to kill %s (%d) [%s]" %
                                  (name, process_pid, traceback.format_exc()))
                res = False
        return res

    def teardown(self):
        self._stop_process()
        self._process = None
        super(WinAppDbgTarget, self).teardown()

    def pre_test(self, test_number):
        super(WinAppDbgTarget, self).pre_test(test_number)
        if not self._is_victim_alive():
            self.logger.error("victim is dead, restarting...")
            # self.report.failed("server is down during pre_test - failure it probably from previous test (%d)" % (test_number-1))
            self._restart()
            self._crash_event_complete.set()
        else:
            self.logger.debug("victim is alive (pid=%d)" % self._pid)

    def post_test(self, test_num):
        self.logger.debug("in")
        time.sleep(1)
        self.logger.debug("after sleep")
        res = self._crash_event_complete.wait()
        self.logger.debug("after wait")
        if not res:
            self.report.failed("incomplete crash detected")
        super(WinAppDbgTarget, self).post_test(test_num)
        self.logger.debug("out")

    def _send_to_target(self, data):
        """
        this is the key off windbgtarget
        :param data: data is the file path
        """
        self.logger.info("send called")
        """
        starting
        """
        self._process_args = []  # this may need implement
        self._start_server_thread()

    def _stop_process(self):
        """
        Stop the process (if running)
        """
        return self._kill_all_processes()

    def _stop_process_old(self):
        """
        :return: True if process was killed, False otherwise
        """
        if self._is_victim_alive():
            self._process.kill()
            time.sleep(0.5)
            if self._is_victim_alive():
                self._process.kill()
                time.sleep(0.5)
                if self._is_victim_alive():
                    raise Exception("Failed to kill client process")
            self._debug.stop()
            return True
        else:
            self._debug.stop()
            return False

    def _restart(self):
        """
        restart the process
        """
        self._stop_process()
        # self.server_thread.join(1)

        time.sleep(3)
        self._server_is_up.clear()
        self._start_server_thread()

    def _is_victim_alive(self):
        """
        check if process running
        """
        if self._process:
            self.logger.debug("process pid: %d" % self._pid)
            is_alive = self._process.is_alive()
            is_debugee_started = self._debug.is_debugee_started(self._pid)
            self.logger.debug("is_alive = %s" % is_alive)
            self.logger.debug("is_debugee_started = %s" % is_debugee_started)
            return is_alive and is_debugee_started
        else:
            self.logger.debug("_process is None")
        return False
Exemple #17
0
        
        found = []
        # Looking for Password:
        pass_pattern = '([0-9]\x00){4}\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x07\x00\x00'
        for address in process.search_regexp( pass_pattern ):
                 found += [process.read(address[0]-3,16)]
        if found:
            print '\nPassword:'******'[0-9]{4}',i.replace('\x00',''))[0]
            print pwd
        else:
            print re.findall('[0-9]{4}',found[0].replace('\x00',''))[0]
        
        return found

debug = Debug()
try:
        # Lookup the currently running processes.
        debug.system.scan_processes()
        # For all processes that match the requested filename...
        for ( process, name ) in debug.system.find_processes_by_filename( filename ):
                pid = process.get_pid()

        memory_search(pid)
           
finally:
        debug.stop()
Exemple #18
0
class CEdenEternalDebugger():
    def __init__(self,pFilename):
        System.request_debug_privileges()  
        self.hSendAddress = "0x2"
        self.hRecvAddress = "0x4"
        self.bQueueStarted = False
        self.bStartLog = False
        self.bSend = False
        self.bBlock = False
        self.lBlockSend = []
        self.lBlockRecv =[]
        self.lBlock = []
        try:
            self.oDebug = Debug(self.handlerEvent)
            self.oDebug.system.scan_processes()
            for ( process, name ) in self.oDebug.system.find_processes_by_filename( pFilename ):
                self.oDebug.attach(process.get_pid())
                stackDbg.put("MSG_INJECTED")
                self.bQueueStarted = True
                self.checkThread = threading.Thread(target=self.handleQueue)
                self.checkThread.start()
                self.oDebug.loop()
        finally:
            stackDbg.put("MSG_NOT_INJECTED")
            self.bQueueStarted = False
            self.oDebug.stop()

    def handleQueue(self):
        while self.bQueueStarted:
            sMsg = gui.stackGui.get()
            if(sMsg == "MSG_START_LOG"):
                self.bStartLog = True
            elif(sMsg == "MSG_STOP_LOG"):
                self.bStartLog = False
            elif(sMsg == "MSG_EXIT"):
                self.oDebug.stop()
            elif(sMsg[:8] == "MSG_SEND"):
                sSend = sMsg.split('|')
                self.bSend = True
                self.sSendMsg = sSend[1]
            elif(sMsg[:9] == "MSG_BLOCK"):
                sBlock = sMsg[10:]
                split = sBlock.split('|')
                if(split[0]=="[C->S]"):
                    self.lBlockSend.append(split[1])
                elif(split[0]=="[S->C]"):
                    self.lBlockRecv.append(split[1])

            elif(sMsg == "MSG_RBLOCK"):
                self.bBlock = True
                   
            elif(sMsg == "MSG_SBLOCK"):
                self.bBlock = False
                del self.lBlock[:] 
                del self.lBlockRecv[:]
                del self.lBlockSend[:] 


    def handlerEvent(self,event):
         nPid = event.get_pid()
         if(self.bStartLog ==True):
             event.debug.break_at(nPid,self.hSendAddress,self.recvOutPackets) 
             event.debug.break_at(nPid,self.hRecvAddress,self.recvInPackets)
         else:
             event.debug.dont_break_at(nPid,self.hSendAddress) 
             event.debug.dont_break_at(nPid,self.hRecvAddress)

    def recvOutPackets(self,event):
        nPid = event.get_pid()
        oProcess = Process(nPid)

        if(self.bStartLog ==True):
            stackMem = event.get_thread().get_sp()
            address = event.get_process().read_pointer( stackMem+0x4 )
            
            if(oProcess.is_address_readable(address)):
                hPacket = self.checkOutPacket(address,oProcess)
                if(self.bBlock==True):
                    if(len(self.lBlockSend)>0):
                        for pck in self.lBlockSend:
                            if(hPacket == pck):
                                bytes = len(hPacket)/2
                                packie = hPacket[:4]
                                for i in range(0,bytes-2):
                                    packie +="00"
                                if(len(packie) % 2 == 0):
                                    blockPacket = binascii.unhexlify(packie)
                                    oProcess.write(address,blockPacket)
                                else:
                                    packie +="0"
                                    blockPacket = binascii.unhexlify(packie)
                                    oProcess.write(address,blockPacket)
                                hPacket = self.checkOutPacket(address,oProcess)
                if(hPacket[:2]=="01"):
                    if(self.bSend==True):
                        sSendPacket = self.sendPacket(oProcess,address)
   
                        if(sSendPacket!="NOWRITE"):
                            if(sSendPacket!=None):
                                stackDbg.put("SND|"+sSendPacket)
                        else:
                            stackDbg.put("SND|"+hPacket)
                    else:
                        stackDbg.put("SND|"+hPacket)
                else:
                    stackDbg.put("SND|"+hPacket)

        else:
            event.debug.dont_break_at(nPid,self.hSendAddress) 


    def recvInPackets(self,event):
        nPid = event.get_pid()
        oProcess = Process(nPid)

        if(self.bStartLog ==True):

            #RECV_LENGTH_ADDRESS = 0x0018FC04
            #RECV_ADDRESS = 0x0018FC10
            RECV_LENGTH_ADDRESS = 0x0018FC14
            RECV_ADDRESS = 0x0018FC20
            if(oProcess.is_address_readable(RECV_ADDRESS)):
                    address = oProcess.read_pointer(RECV_ADDRESS)
                    if(oProcess.is_address_readable(address)):
                        sLength = oProcess.read(RECV_LENGTH_ADDRESS,1)
                        nLength = int(toHex(sLength),16)
                        if(nLength>0):
                            file = open("config/recv.cfg", "r") 
                            hPacket = self.checkInPacket(address,oProcess,nLength)

                            if(self.bBlock==True):
                                if(len(self.lBlockRecv)>0):
                                    for pck in self.lBlockRecv:
                                        if(hPacket == pck):
                                            bytes = len(hPacket)/2
                                            packie = ""
                                            for i in range(0,bytes):
                                                packie +="00"
                                            print packie
                                            blockPacket = binascii.unhexlify(packie)
                                            oProcess.write(address,blockPacket)
                                            hPacket = self.checkInPacket(address,oProcess,nLength)
                            if(hPacket[0:4]=='2901'):
                                stackDbg.put("RCV|"+hPacket)
                                self.recvQuests(hPacket)
                            elif(hPacket[0:4]=='5401'): 
                                stackDbg.put("RCV|"+hPacket)
                                self.editQuests(hPacket)
                            elif(hPacket[0:2]=='36'):
                                stackDbg.put("RCV|"+hPacket)
                            else:
                                stackDbg.put("RCV|"+hPacket)
                        
        else:
            event.debug.dont_break_at(nPid,self.hRecvAddress)


    def checkOutPacket(self,pAddress,pProcess):
        sLength = pProcess.read(pAddress-2,1)
        nLength = int(toHex(sLength),16)
        sPacket = pProcess.read(pAddress,nLength)
        hPacket = HexDump.hexadecimal(sPacket)
        return hPacket
        
    def checkInPacket(self,pAddress,pProcess,pLength):
        sPacket = pProcess.read(pAddress,pLength)
        hPacket = HexDump.hexadecimal(sPacket)
        return hPacket

    def recvQuests(self,pPacket):
        i = 8
        sQuests = ""
        bRecv = True
        while bRecv:
            sWord = pPacket[i:i+4]
            i +=8
            if(sWord=="0106"):
                bRecv = False
            else:
                sQuests +=sWord
            
        i = 0
        for z in range(len(sQuests)/4):
            sLeft = sQuests[i*4:(i*4)+2]
            sRight = sQuests[(i*4)+2:(i*4)+4]
            sID = sRight + sLeft
            stackDbg.put("QUEST_RCV|"+sID)
            i += 1                                  

    def editQuests(self,pPacket):
        sQuest = pPacket[6:10]
        sAction = pPacket[14:16]
        sLeft = sQuest[:2]
        sRight = sQuest[2:]
        sID = sRight+sLeft
        stackDbg.put("EDIT_QUEST|"+sID+"|"+sAction)

    def sendPacket(self,pProcess,pAddress):
        sText = self.sSendMsg
        sPackets = sText.split("\n")
        nLength = len(sPackets)
                        
        global nPacketCounter 
            
        sHeader = "1a00"
        try:
            sSendPacket = sHeader+str(sPackets[nPacketCounter])
            if(str(sPackets[nPacketCounter])!=""):
                if((len(sSendPacket)/2)<26):
                    for i in range(1, 31-(len(sSendPacket)/2)):
                        sSendPacket +="00"
                hPacket = binascii.unhexlify(sSendPacket)
                pProcess.write(pAddress-2,hPacket)

            nPacketCounter += 1

            if nPacketCounter == nLength-1: 
                self.bSend=False
                self.sSendMsg = ""
                nPacketCounter = 0

            if(str(sPackets[nPacketCounter])!=""):
                return sSendPacket[4:]
            else:
                return "NOWRITE"

        except IndexError:
            print "packet sending error!"
            self.bSend = False
            self.sSendMsg = ""
            nPacketCounter = 0
class WinAppDbgTarget(ServerTarget):
    def __init__(self,
                 name,
                 process_path,
                 process_args=[],
                 sql_crash_db='sqlite:///crashes.sqlite',
                 logger=None):
        '''
        :param name: name of the object
        :param process_path: path to the target executable
        :param process_args: arguments to pass to the process
        :param attach: try to attach if process path
        :param sql_crash_db: sql alchemy connection string to crash db (default:sqlite:///crashes.sqlite)
        :param logger: logger for this object (default: None)
        '''
        super(WinAppDbgTarget, self).__init__(name, logger)
        assert (process_path)
        assert (os.path.exists(process_path))
        self._process_path = process_path
        self._process_name = os.path.basename(process_path)
        self._process_args = process_args
        self._process = None
        self._sql_crash_db = sql_crash_db
        self._crash_event_complete = threading.Event()
        self._server_is_up = threading.Event()
        self._crash_event_complete.set()
        self._debug = Debug(lambda x: _my_event_handler(self, x),
                            bKillOnExit=True)

    def _debug_server(self):
        '''
        debugger thread
        '''
        try:
            self._process = None
            # Start a new process for debugging.
            argv = [self._process_path] + self._process_args
            self.logger.debug('debugger starting server: %s' % argv)
            try:
                self._process = self._debug.execv(argv, bFollow=True)
            except WindowsError:
                self.logger.error('debug_server received exception',
                                  traceback.fmt_exc())
            self._pid = self._process.get_pid()
            self.logger.info('process started. pid=%d' % self._pid)

            # Wait for the debugee to finish.
            self._server_is_up.set()
            self._debug.loop()
        except:
            self.logger.error('Got an exception in _debug_server')
            self.logger.error(traceback.format_exc())
        # Stop the debugger.
        finally:
            self._debug.stop()
            self._process = None
            self._pid = -1
            self._crash_event_complete.set()

    def _start_server_thread(self):
        '''
        start the server thread
        '''
        self._server_is_up.clear()
        self.server_thread = FuncThread(self._debug_server)
        self.server_thread.start()
        self.logger.info('waiting for server to be up')
        self._server_is_up.wait()
        self.logger.info('server should be up')

    def _kill_all_processes(self):
        '''
        kill all processes with the same name
        :return: True if all matching processes were killed properly, False otherwise
        '''
        res = True
        # Lookup the currently running processes.
        self._debug.system.scan_processes()
        # For all processes that match the requested filename...
        for (process, name) in self._debug.system.find_processes_by_filename(
                self._process_name):
            process_pid = process.get_pid()
            self.logger.info('found process %s (%d) - trying to kill it' %
                             (name, process_pid))
            try:
                process.kill()
                self.logger.info('successfully killed %s (%d)' %
                                 (name, process_pid))
            except:
                self.logger.error('failed to kill %s (%d) [%s]' %
                                  (name, process_pid, traceback.format_exc()))
                res = False
        return res

    def teardown(self):
        self._stop_process()
        self._process = None
        super(WinAppDbgTarget, self).teardown()

    def pre_test(self, test_number):
        # we need kill all process before fuzzing
        super(WinAppDbgTarget, self).pre_test(test_number)
        self._stop_process()

    def post_test(self, test_num):
        self.logger.debug('in')
        time.sleep(1)
        self.logger.debug('after sleep')
        res = self._crash_event_complete.wait()
        self.logger.debug('after wait')
        if not res:
            self.report.failed('incomplete crash detected')
        super(WinAppDbgTarget, self).post_test(test_num)
        self.logger.debug('out')

    def _send_to_target(self, data):
        '''
        this is the key off windbgtarget
        :param data: data is the file path
        '''
        self.logger.info('send called')
        '''
        starting
        '''
        self._process_args = [data]  # this may need implement
        self._start_server_thread()

    def _stop_process(self):
        '''
        Stop the process (if running)
        '''
        return self._kill_all_processes()

    def _stop_process_old(self):
        '''
        :return: True if process was killed, False otherwise
        '''
        if self._is_victim_alive():
            self._process.kill()
            time.sleep(0.5)
            if self._is_victim_alive():
                self._process.kill()
                time.sleep(0.5)
                if self._is_victim_alive():
                    raise Exception('Failed to kill client process')
            self._debug.stop()
            return True
        else:
            self._debug.stop()
            return False

    def _restart(self):
        '''
        restart the process
        '''
        self._stop_process()
        self.server_thread.join(1)
        time.sleep(3)
        self._server_is_up.clear()
        self._start_server_thread()

    def _is_victim_alive(self):
        '''
        check if process running
        '''
        if self._process:
            self.logger.debug('process pid: %d' % self._pid)
            is_alive = self._process.is_alive()
            is_debugee_started = self._debug.is_debugee_started(self._pid)
            self.logger.debug('is_alive = %s' % is_alive)
            self.logger.debug('is_debugee_started = %s' % is_debugee_started)
            return (is_alive and is_debugee_started)
        else:
            self.logger.debug('_process is None')
        return False