Example #1
0
 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()
Example #2
0
def intercept_wsmprovhost(pid,eventHandler):
    debug = Debug(eventHandler,bKillOnExit=True)
    try:
        debug.attach(int(pid))
        debug.loop()
    except Exception,e:
        print "Error: ",str(e)
Example #3
0
 def function():
     self.debugger = Debug(HookingEventHandler(self.hooks,
                                               self.api_hooks),
                           bKillOnExit=kill_process_on_exit,
                           bHostileCode=anti_anti_debugger)
     self.debugger.attach(pid)
     self._loop()
Example #4
0
 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)
Example #5
0
 def function():
     os.chdir(os.path.dirname(path))
     self.debugger = Debug(HookingEventHandler(self.hooks,
                                               self.api_hooks),
                           bKillOnExit=kill_process_on_exit,
                           bHostileCode=anti_anti_debugger)
     self.debugger.execv([path])
     self._loop()
Example #6
0
    def start_debug(self):

        self.debug = Debug(
            self.debug_loop, bKillOnExit=True
        )  #  If True debugged processes are killed when the debugger is stopped.
        self.debug.execv(
            command_line
        )  # execute target program (prameter command_line --> target program, mutate file)
        self.debug.loop()
Example #7
0
class Process(object):
    def __init__(self, api_hooks=None):
        System.request_debug_privileges()
        self.api_hooks = api_hooks
        self.hooks = []
        self.debugger = None

    def _loop(self):
        try:
            self.debugger.loop()
        except KeyboardInterrupt:
            self.debugger.stop()

    def hook_function(self,
                      address,
                      pre_callback=None,
                      post_callback=None,
                      signature=None):
        if not pre_callback and not post_callback:
            return

        self.hooks.append((address, pre_callback, post_callback, signature))

    def start(self,
              path,
              kill_process_on_exit=True,
              anti_anti_debugger=False,
              blocking=True):
        def function():
            os.chdir(os.path.dirname(path))
            self.debugger = Debug(HookingEventHandler(self.hooks,
                                                      self.api_hooks),
                                  bKillOnExit=kill_process_on_exit,
                                  bHostileCode=anti_anti_debugger)
            self.debugger.execv([path])
            self._loop()

        if blocking:
            function()
        start_new_thread(function)

    def attach(self,
               pid,
               kill_process_on_exit=False,
               anti_anti_debugger=False,
               blocking=True):
        def function():
            self.debugger = Debug(HookingEventHandler(self.hooks,
                                                      self.api_hooks),
                                  bKillOnExit=kill_process_on_exit,
                                  bHostileCode=anti_anti_debugger)
            self.debugger.attach(pid)
            self._loop()

        if blocking:
            function()
        start_new_thread(function)
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()
Example #9
0
class TraceInstructions(Thread):
    """
    Setups and starts the debugger used to trace assembly instructions.
    """
    def __init__(self, pid):
        """
        Initializes the thread.
        @param pid: PID of the original process to monitor
        """
        Thread.__init__(self)
        self.pid = pid

    def run(self):
        """
        Main thread procedure.
        """
        log = logging.getLogger("Debugger.TraceInstructions")

        if not os.path.exists(TRACE_PATH):
            try:
                os.mkdir(TRACE_PATH)
            except (IOError, os.error), why:
                log.error("Unable to create folder \"%s\": %s" %
                          (TRACE_PATH, why))
                return False

        debug = Debug(DumpInstruction(), bKillOnExit=True, bHostileCode=True)
        try:
            debug.attach(self.pid)
            debug.loop()
        finally:
            debug.stop()

        return True
def simple_debugger(argv):
    with Debug(ScriptExecutionMonitorEventHandler(),
               bKillOnExit=False) as debug:
        if len(argv) == 0:
            attached = False
            logging.info("Try to attach to WINWORD.EXE...")
            while not attached:
                for process in System():
                    filename = process.get_filename()
                    if filename and "WINWORD.EXE" in filename:
                        logging.info("Attaching to: %s (%d)" %
                                     (filename, process.get_pid()))
                        debug.attach(process.get_pid())
                        attached = True

            if attached:
                debug.loop()
            else:
                logging.error("Unabel to find a WINWORD.exe process")
        elif argv[0].isdigit():
            # attach via PID
            pid = int(argv[0])
            debug.attach(pid)
            logging.info("Attaching to: %d" % pid)
            debug.loop()
        else:
            logging.error("Usage: %s [PID]" % sys.argv[0])
Example #11
0
def simple_debugger(argv):

    # Instance a Debug object using the "with" statement.
    # Note how we don't need to call "debug.stop()" anymore.
    with Debug(None, bKillOnExit = True) as debug:

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

            set_breakpoint(debug, 0x010153F6, breakpoint_010153F6)

            # set_breakpoint(debug, 0x40103B, breakpoint_40103B)

            set_breakpoint(debug, 0x010153FF, breakpoint_010153FF)

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

        except KeyboardInterrupt:
            logging.debug("Ctrl+C -ed.")

            # Stop debugging. This kills all debugged processes.
            debug.stop()

        # Stop the debugger.
        finally:
            debug.stop()
Example #12
0
def simple_debugger():
    handler = EventSift(MyEventHandler)
    # handler = MyEventHandler()  # try uncommenting this line...
    with Debug(handler) as debug:
        debug.execl("calc.exe")
        debug.execl("notepad.exe")
        debug.execl("charmap.exe")
        debug.loop()
Example #13
0
def simple_debugger(argv):
    # Instance a Debug object, passing it the MyEventHandler instance.
    with Debug(MyEventHandler(), bKillOnExit=True) as debug:
        # Start a new process for debugging.
        debug.execv(argv)

        # Wait for the debugee to finish.
        debug.loop()
Example #14
0
    def exit_process(self, event):
        print "Detached from %s" % self.name

        handler = EventSift(MyEventHandler)
        #handler = MyEventHandler()  # try uncommenting this line...
        with Debug(handler) as debug:
            debug.execl(self.name)
            debug.loop()
Example #15
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()
Example #16
0
    def each_with_type(self, target, file_type):
        self.paths = {
            'word': "{}\\{}".format(self.office_path, "WINWORD.EXE"),
            'rtf': "{}\\{}".format(self.office_path, "WINWORD.EXE"),
            'html': "{}\\{}".format(self.office_path, "WINWORD.EXE"),
            'excel': "{}\\{}".format(self.office_path, "EXCEL.EXE"),
            'powerpoint': "{}\\{}".format(self.office_path, "POWERPOINT.EXE"),
            'javascript': 'C:\\Windows\\system32\\wscript.exe',
            'vbscript': 'C:\\Windows\\system32\\wscript.exe'
        }

        self.files = set()
        self.results = {"actions": []}

        monkey = ClickThread()
        monkey.click_on(
            "Microsoft Excel", "Yes",
            "is in a different format than specified by the file extension")
        monkey.click_on(
            "Microsoft Word", "OK",
            "command cannot be performed because a dialog box is open")
        monkey.click_on("Microsoft Word", "No", "start Word in safe mode")
        monkey.click_on("Microsoft Word", "Yes", "caused a serious error")
        monkey.click_on("File In Use", "OK", "locked for editing")
        monkey.click_on("Microsoft Word", "Yes",
                        "that may refer to other files")
        monkey.click_on("Microsoft Excel", "Yes",
                        "that may refer to other files")
        monkey.click_on("Microsoft Word", "Yes", "Do you want to start")
        monkey.click_on("Microsoft Excel", "Yes", "Do you want to start")
        monkey.close("Activation Wizard")
        monkey.start()

        target = self.set_extension(target, file_type)
        args = [self.paths[file_type], target]

        pids = []
        maxtime = time() + self.timeout

        with Debug(self, bKillOnExit=False) as debug:
            debug.execv(args)

            pids = debug.get_debugee_pids()

            while debug and time() < maxtime:
                try:
                    debug.wait(1000)
                except WindowsError, e:
                    if e.winerror in (win32.ERROR_SEM_TIMEOUT,
                                      win32.WAIT_TIMEOUT):
                        continue
                    raise

                try:
                    debug.dispatch()
                finally:
                    debug.cont()
Example #17
0
def simple_debugger(pid):

    # Instance a Debug object, passing it the MyEventHandler instance.
    with Debug(MyEventHandler(), bKillOnExit=True) as debug:

        try:
            debug.attach(pid)
            debug.loop()
        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
Example #19
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()
Example #20
0
def simple_debugger(argv):

    # Instance a Debug object using the "with" statement.
    # Note how we don't need to call "debug.stop()" anymore.
    with Debug(MyEventHandler(), bKillOnExit=True) as debug:

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

        # Wait for the debugee to finish.
        debug.loop()
Example #21
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()
Example #22
0
def simple_debugger( pid ):

    # Instance a Debug object, passing it the MyEventHandler instance.
    with Debug( MyEventHandler(), bKillOnExit = False ) as debug:

        # Start a new process for debugging.

        debug.attach( pid )

        # Wait for the debugee to finish.
        debug.loop()
def analyzeCrashes():
    global threads, curr_input

    if not os.path.exists(crash_dir):
        logger.info('[!] ' + datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +
                    ' There are no crashing inputs to analyze!')
        return

    if len(threads) == 0:
        popup = PopUpKiller()
        popup_tid = thread.start_new_thread(popup.POPUpKillerThread, ())
        threads.append(popup_tid)

    for file in os.listdir(crash_dir):
        try:
            if file == "":
                continue
            curr_input = '{0}\\{1}'.format(crash_dir, file)
            logger.debug('[+] Generating symlink to {0}'.format(curr_input))
            if symlink(curr_input, refFile) == 1:  #make symbolic link
                continue
            #cmd = [PROG_NAME, PROG_ARGUMENTS, wordFile]
            cmd = [PROG_NAME, wordFile]
            logger.debug('[+]',
                         datetime.now().strftime("%Y:%m:%d::%H:%M:%S"),
                         'Executing : ', cmd)
            debug = Debug(AccessViolationHandlerWINAPPDBG, bKillOnExit=True)
            proc = debug.execv(cmd)
            wordGuard_tid = thread.start_new_thread(StillRunningWINAPPDBG,
                                                    (proc, ))
            threads.append(wordGuard_tid)
            debug.loop()
        except:
            pass
        finally:
            try:
                logger.debug(
                    '[+] Removing symlink from {0}'.format(curr_input))
                os.remove(refFile)
            except:
                pass
def simple_debugger(argv):

    with Debug(MyEventHandler(), bKillOnExit=True) as debug:
        try:
            # Start a new process for debugging.
            print('start', argv)
            debug.execv(argv)
            debug.loop()
        except:
            pass

    return c2_list
Example #25
0
def intercept_wsmprovhost(pid, eventHandler):
    debug = Debug(eventHandler, bKillOnExit=True)
    try:
        debug.attach(int(pid))
        debug.loop()
    except Exception, e:
        print "Error: ", str(e)
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()
Example #27
0
def simple_debugger(argv):
    # Instance a Debug object, passing it the MyEventHandler instance.
    with Debug(MyEventHandler(), bKillOnExit=True) as debug:
        # Start a new process for debugging.
        debug.execv(argv)

        # If you start the new process like this instead, the
        # debugger will automatically attach to the child processes.
        #
        # debug.execv( argv, bFollow = True )

        # Wait for the debugee to finish.
        debug.loop()
Example #28
0
 def execute(self):
     print "# {} Opening mutate file to target by bbcFuzzer".format(self.test_number)
     print(["{}".format(self.target_path), "{}\\{}.{}".format(self.mutate_path, self.test_number, self.file_type)])
     try:
         with Debug(self.check_crash, bKillOnExit = True) as _debug:
             self.debug_time = time.time()
             _debug.execv(["{}".format(self.target_path), "{}\\{}.{}".format(self.mutate_path, self.test_number, self.file_type)])
             _debug.loop()
     except WindowsError:
         self.communicationManager.alert("Failed execute")
         print "Failed execute"
     finally:
         self.add_test_number()
Example #29
0
class Process(object):
    def __init__(self, api_hooks=None):
        System.request_debug_privileges()
        self.api_hooks = api_hooks
        self.hooks = []
        self.debugger = None

    def _loop(self):
        try:
            self.debugger.loop()
        except KeyboardInterrupt:
            self.debugger.stop()

    def hook_function(self, address, pre_callback=None, post_callback=None, signature=None):
        if not pre_callback and not post_callback:
            return

        self.hooks.append((address, pre_callback, post_callback, signature))

    def start(self, path, kill_process_on_exit=True, anti_anti_debugger=False, blocking=True):
        def function():
            os.chdir(os.path.dirname(path))
            self.debugger = Debug(HookingEventHandler(self.hooks, self.api_hooks), bKillOnExit=kill_process_on_exit, bHostileCode=anti_anti_debugger)
            self.debugger.execv([path])
            self._loop()

        if blocking:
            function()
        start_new_thread(function)

    def attach(self, pid, kill_process_on_exit=False, anti_anti_debugger=False, blocking=True):
        def function():
            self.debugger = Debug(HookingEventHandler(self.hooks, self.api_hooks), bKillOnExit=kill_process_on_exit, bHostileCode=anti_anti_debugger)
            self.debugger.attach(pid)
            self._loop()

        if blocking:
            function()
        start_new_thread(function)
Example #30
0
    def create_debugger(self):

        # Instance a debugger
        debug = Debug(self, bHostileCode=self.options.hostile)

        # Make sure the remote symbol store is set
        System.fix_symbol_store_path(remote=True, force=False)

        # Populate the snapshot of processes
        debug.system.scan()

        # Use this debugger
        self.start_using_debugger(debug)
Example #31
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()
def run_within_debugger_with_timeout(args):
    print '[+]    running testcase...'
    with Debug(crash_handler, bKillOnExit=True) as debug:
        debug.execv(args, bConsole=True)
        System.set_kill_on_exit_mode(True)
        maxTime = time.time() + 15
        while debug and time.time() < maxTime:
            try:
                debug.wait(1000)
            except WindowsError, e:
                if e.winerror in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT):
                    continue
                raise
            try:
                debug.dispatch()
            finally:
                debug.cont()
Example #33
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()
Example #34
0
 def monitor(self):
     _killer = Debug()
     while True:
         if int(time.time()) - int(self.debug_time) > 10:
             try:
                 for (process, name) in _killer.system.find_processes_by_filename(os.path.split(self.target_path)[1]):
                     if not process:
                         sleep(5)
                 self.kill_test_process()
             except (WindowsError, AttributeError):
                 sleep(5)
                 self.kill_test_process()
             #for (process, name) in _killer.system.find_processes_by_filename(os.path.split(self.target_path)[1]):
             #    _killer.kill(process.get_pid())
             #    print "Kill {} {}".format(process.get_pid(), name)
             
             break
Example #35
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()
Example #36
0
 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)
Example #37
0
def main( ):
	
	set_logger()

	args = parse_args()	
	pid = get_pid(args)

	logging.debug( "about to connect to pid %(pid)s" % locals() )

	dbg = None
	try:

		dbg = Debug( event_handler.RPCEventHandler(), bKillOnExit = False)
		dbg.attach(pid)
		dbg.loop()

	finally:
		if dbg != None:
			logging.debug ("About to detach from pid %(pid)s" % locals() )
			dbg.detach(pid)
		
		logging.info("Finished")
Example #38
0
 def function():
     os.chdir(os.path.dirname(path))
     self.debugger = Debug(HookingEventHandler(self.hooks, self.api_hooks), bKillOnExit=kill_process_on_exit, bHostileCode=anti_anti_debugger)
     self.debugger.execv([path])
     self._loop()
Example #39
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()
        else:
            event.debug.pmf.append("Path","contains", value, "EXCLUDE")
    elif subsystem == 3:
        #Registry
        if semantics[semantic] == 'REG_ALLOW_READONLY':
            event.debug.pmf.append("Path","contains", value, "EXCLUDE")
        elif  semantics[semantic] == 'REG_ALLOW_ANY':
            event.debug.pmf.append("Path","contains", value, "INCLUDE")
    else:
        pass


if __name__ == '__main__':
    print "Wellcome. Using Winappdbg version", version
    #Instantiate the debugger
    debug = Debug(bKillOnExit=True, bHostileCode=True)
    #Build the basic set of filter rules
    pmf = PMF('policy.pmf')
    pmf.clear()
    pmf.append('Process Name','is', 'Procmon.exe', 'EXCLUDE')
    pmf.append('Process Name','is', 'System', 'EXCLUDE')
    pmf.append('Operation','begins with', 'IRP_MJ_', 'EXCLUDE')
    pmf.append('Operation','begins with', 'FASTIO_', 'EXCLUDE')
    pmf.append('Result','begins with', 'FAST IO', 'EXCLUDE')
    pmf.append('Path','ends with', 'pagefile.sys', 'EXCLUDE')
    pmf.append('Path','ends with', '$Mft', 'EXCLUDE')
    pmf.append('Path','ends with', '$MftMirr', 'EXCLUDE')
    pmf.append('Path','ends with', '$LogFile', 'EXCLUDE')
    pmf.append('Path','ends with', '$Volume', 'EXCLUDE')
    pmf.append('Path','ends with', '$AttrDef', 'EXCLUDE')
    pmf.append('Path','ends with', '$Root', 'EXCLUDE')
Example #41
0
class WinBasic:
    debugger = None
    mainProc = None
    alwaysCatchExceptions = [
        win32.STATUS_ACCESS_VIOLATION,
        win32.STATUS_ILLEGAL_INSTRUCTION,
        win32.STATUS_ARRAY_BOUNDS_EXCEEDED,
    ]

    def __init__(self, killOnExit=True):
        self.debugger = Debug(bKillOnExit=killOnExit)
        self.mainProcs = []

    def run(self, executable, children=True):
        tmp = self.debugger.execv(executable, bFollow=children)
        self.mainProcs.append(tmp)
        return tmp.get_pid()

    def attachPid(self, pid):
        self.mainProcs.append(self.debugger.attach(pid))

    def attachImg(self, img):
        self.debugger.system.scan_processes()
        for (process, name) in self.debugger.system.find_processes_by_filename(img):
            self.attachPid(process.get_pid())

    def close(self, kill=True, taskkill=True, forced=True):
        pids = self.debugger.get_debugee_pids()

        self.debugger.detach_from_all(True)
        for pid in pids:
            if kill:
                try:
                    proc = self.debugger.system.get_process(pid)
                    proc.kill()
                except:
                    pass

                    # Taskkill
            if taskkill and not forced:
                subprocess.call(["taskkill", "/pid", str(pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if taskkill and forced:
                subprocess.call(["taskkill", "/f", "/pid", str(pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    def waitForCrash(self, waitTime=4, checkAlive=False):
        event = None
        endDebuging = False
        endTime = time() + waitTime

        while time() < endTime:
            if checkAlive:
                for proc in self.mainProcs:
                    if not proc.is_alive():
                        return None

            try:
                event = self.debugger.wait(1000)
            except WindowsError, e:
                if e.winerror in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT):
                    continue
                raise

            crash = self.handler(event)
            if crash != None:
                return crash
            else:
                try:
                    self.debugger.dispatch()
                except:
                    pass
                finally:
                    self.debugger.cont()
        return None
Example #42
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
found		= 0
filename 	= "navicat.exe"
process_pid = 0
memory_dump	= []

def b2h(str):
    return ''.join(["%02X " % ord(x) for x in str]).strip()

def h2b(str):
	bytes = []
	str = ''.join(str.split(" "))
	for i in range(0, len(str), 2):
		bytes.append(chr(int(str[i:i+2], 16)))
	return ''.join(bytes)

debug = Debug()
try:
	print "[~] Searching for pid by process name '%s'.." % (filename)
	time.sleep(1)
	debug.system.scan_processes()
	for (process, process_name) in debug.system.find_processes_by_filename(filename):
		process_pid = process.get_pid()
	if process_pid is not 0:
		print "[+] Found process with pid #%d" % (process_pid)
		time.sleep(1)
		print "[~] Trying to read memory for pid #%d" % (process_pid)
		
		process = Process(process_pid)
		for address in process.search_bytes('\x00\x90\x18\x00\x00\x00\x00\x00\x00\x00'):
			memory_dump.append(process.read(address,30))
		memory_dump.pop(0)
Example #44
0
class Coverage:
	verbose = False
	bbFiles = {}
	bbFilesBreakpints = []
	bbFilesData = {}
	bbOriginalName = {}
	modules = []
	fileOutput = None
		
	#Construct
	def __init__(self):
		self.debugger = Debug( bKillOnExit = True )
		
	def setVerbose(self, val):
		self.verbose = val
		
	#cuts after .
	def cutDot(self, input):
		if (input.find(".") == -1):
			return input
		return input[0:input.find(".")]

	#load basic blocks
	def loadBB(self, baseBbDir):
		self.bbFiles = {}
		count = 0
		print "baseBbDir:"+baseBbDir
		for bbFile in os.listdir(baseBbDir):
			print "bbFile:" + bbFile
			f = open(baseBbDir + "/" + bbFile, "r")
			fname = f.readline().strip().lower()
			#fname = f.readline().strip()
			fnameOrig = fname
			if ".dll" not in fname and ".exe" not in fname:  #Stupid hack to avoid problems in loading libs with other extensions then .dll
				fname = self.cutDot(fname) + ".dll"
			self.bbOriginalName[fname] = fnameOrig
			self.bbFiles[fname] = count
			self.bbFilesBreakpints.append({})
			rvaHighest = 0
			for line in f:
				try:
					rva = int(line[0:8], 16)
					val = int(line[18:20], 16)
					self.bbFilesBreakpints[count][rva] = val
					if rva > rvaHighest:
						rvaHighest = rva
				except Exception:
					continue
			self.bbFilesData[fname] = [rvaHighest + 10, count]
			if self.verbose:
				print "Loaded breakpoints for %s with index %02X" % (fname, count)
			count += 1
			f.close()
	
	#Register module (original exe image or dll)
	def registerModule(self, filename, baseaddr):
		filename = filename.lower()
		if ".dll" not in filename and ".exe" not in filename:  #Stupid hack to avoid problems in loading libs with other extensions then .dll
			filename = self.cutDot(filename) + ".dll"
		if filename not in self.bbFiles:
			return
		if self.verbose:
			print "  Image %s has breakpoints defined" % filename
		self.modules.append([baseaddr,baseaddr+self.bbFilesData[filename][0], self.bbFilesData[filename][1]])
		if self.verbose:
			print "  Image has breakpoints from %08X to %08X with index %02X" % (baseaddr,baseaddr+self.bbFilesData[filename][0],self.bbFilesData[filename][1])
		
	#Handle a breakpoint
	def breakpoint(self, location):
		index = None
		for i in xrange(len(self.modules)):
			if location>=self.modules[i][0] and location<=self.modules[i][1]:
				index = i
				break
		if index == None:
			return None	
		rva = location - self.modules[index][0]
		index = self.modules[index][2]
		if rva not in self.bbFilesBreakpints[index]:
			return None
		self.fileOutput.write("%02X|%08X\n" % (index, rva))
		return self.bbFilesBreakpints[index][rva]
		
	def startFileRec(self, filename):
		self.modules = []
		self.fileOutput = open(filename, "w")
		for image in self.bbFiles:
			self.fileOutput.write("%s|%02X\n" % (self.bbOriginalName[image], self.bbFiles[image]))
		
	def endFileRec(self):
		self.fileOutput.close()		
	
	#Start program
	def start(self, execFile, waitTime = 6, recFilename = "output.txt", kill = True):	
		self.startFileRec(recFilename)
		mainProc = self.debugger.execv( execFile, bFollow = True )
		event = None
		endTime = time() + waitTime
		while time() < endTime:
			if not mainProc.is_alive():
				break
			try:
				event = self.debugger.wait(1000)
			except WindowsError, e:
				if e.winerror in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT):
					continue
				raise
			
			if event.get_event_code() == win32.LOAD_DLL_DEBUG_EVENT:
				module = event.get_module()
				if self.verbose:
					print "DLL %s loaded on base %08X" % (module.get_name(), module.get_base())
				self.registerModule(self.cutDot(module.get_name())+".dll", module.get_base())
			elif event.get_event_code() == win32.CREATE_PROCESS_DEBUG_EVENT:
				tmp = event.get_filename().split("\\")
				modName = tmp[len(tmp)-1]
				if self.verbose:
					print "Process %s loaded on base %08X" % (modName, event.raw.u.CreateProcessInfo.lpBaseOfImage)
				self.registerModule(modName,event.raw.u.CreateProcessInfo.lpBaseOfImage)
			elif event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT and event.get_exception_code() == win32.STATUS_BREAKPOINT:
				pc = event.get_thread().get_pc()-1
				val = self.breakpoint(pc)
				if val != None:
					event.get_process().write(pc, chr(val))
					event.get_thread().set_pc(pc)
					endTime = time() + waitTime
					
			try:
				self.debugger.dispatch()
			except:
				pass
			finally:
				self.debugger.cont()
		self.endFileRec()
		if kill:
			self.kill()
Example #45
0
           print i.replace('\x00','')
        
        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()
Example #46
0
 def createDebugger(self, command):
     debug = Debug(self.debuggerEventHandler, bKillOnExit=True)
     argv = command.split()
     debug.execv(argv)
     debug.loop()
     
    aThread = event.get_thread()
    aThread.set_register("Eax", r_eax)
    aThread.set_register("Ecx", r_ecx)
    aThread.set_register("Edx", r_edx)
    aThread.set_register("Eip", 0x004DC395)


# Specify a dictionary here
words = open("dic.txt", "r").readlines()
print "[+] Words Loaded: ", len(words)

# Specify a key file
keyfile = "pwsafe.key"

try:
    debug = Debug()

    # Start a new process for debugging
    # Allocate 20 bytes for the words

    if os.path.isfile(keyfile):
        print "[+] Keyfile Loaded: '" + keyfile + "'"
        aProcess = debug.execv(["KeePass.exe", "Database.kdb", "-keyfile:" + keyfile, "-pw:".ljust(WORD_SIZE + 4)])
    else:
        print "[+] Specified keyfile '" + keyfile + "' does not exist, ignoring argument"
        aProcess = debug.execv(["KeePass.exe", "Database.kdb", "-pw:".ljust(WORD_SIZE + 4)])

    # Set the breakpoints
    debug.break_at(aProcess.get_pid(), 0x004DC395, action_0)
    debug.break_at(aProcess.get_pid(), 0x004D77A0, action_1)
    debug.break_at(aProcess.get_pid(), 0x004D6684, action_2)
Example #48
0
 def __init__(self, killOnExit=True):
     self.debugger = Debug(bKillOnExit=killOnExit)
     self.mainProcs = []
Example #49
0
	def __init__(self):
		self.debugger = Debug( bKillOnExit = True )
Example #50
0
    myevent = MyEventHandler()
    myevent.dir = dir
    myevent.report = report
    myevent.myself = os.path.basename(sys.argv[1])

    if options.functions:
        hooks = parse_hook_spec(options.functions)
        if len(hooks) == 0:
            sys.exit()
        else:
            myevent.set_hooks(hooks)


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

    try:

        if options.pid:
            debug.attach(options.pid)
            print_threads_and_modules(options.pid, debug)
        elif options.program:
            procs = list_processes(options.program)

            if len(procs) == 0:
                print "[E] no matching process"
            elif len(procs) == 1:
                debug.attach(procs[0].get_pid())
                print_threads_and_modules(procs[0].get_pid(), debug)
            else:
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from winappdbg import Debug

import sys

# Get the process filename from the command line.
filename = sys.argv[1]

# Instance a Debug object.
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 ):
        print process.get_pid(), name

        # Attach to the process.
        debug.attach( process.get_pid() )

    # Wait for all the debugees to finish.
    debug.loop()
Example #52
0
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

# This line is needed in Python 2.5 to use the "with" statement.
from __future__ import with_statement

from winappdbg import Debug

import sys

# Instance a Debug object, set the kill on exit property to True.
debug = Debug( bKillOnExit = True )

# The user can stop debugging with Control-C.
try:
    print "Hit Control-C to stop debugging..."

    # Start a new process for debugging.
    debug.execv( sys.argv[ 1 : ] )

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

# If the user presses Control-C...
except KeyboardInterrupt:
    print "Interrupted by user."
Example #53
0
 def function():
     self.debugger = Debug(HookingEventHandler(self.hooks, self.api_hooks), bKillOnExit=kill_process_on_exit, bHostileCode=anti_anti_debugger)
     self.debugger.attach(pid)
     self._loop()
Example #54
0
        print "CreateFileW: %s" % (fname)
   
    # The post_ functions are called upon exiting the API
    
    def post_CreateFileW(self, event, retval):
        if retval:
            print 'Suceeded (handle value: %x)' % (retval)
        else:
            print 'Failed!'

if __name__ == "__main__":

    if len(sys.argv) < 2 or not os.path.isfile(sys.argv[1]):
        print "\nUsage: %s <File to monitor> [arg1, arg2, ...]\n" % sys.argv[0]
        sys.exit()

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

    try:
        # Start a new process for debugging
        p = debug.execv(sys.argv[1:], bFollow=True)

        # Wait for the debugged process to finish
        debug.loop()

    # Stop the debugger
    finally:
        debug.stop()

Example #55
0
class MyEventHandler( EventHandler ):
    
    def load_dll( self, event ):

        module = event.get_module() # modulebis gatoleba
        if module.match_name("nss3.dll"): # vnaxulobt tu aris nss3.dll
            pid = event.get_pid()  
            address = module.resolve( "PR_Write" )  # vigebt PR_Write funqcii misamart
            print '[+] Found  PR_Write  at addr ' + str(address)
            event.debug.hook_function( pid, address, preCB=PR_Write, postCB=None ,paramCount=3,signature=None)
            # movaxditon egred wodebuli funqciis mokauweba (hook) rodesac kodi sheexeba breakpoint -is
            # da funqciis 3 parametris mnishvneloba gadavcet chvnes call back funqcias romelsac igeve saxeli vuwodet PR_Write






while True:
    time.sleep(2) # yovel 2 wamshi sheamowmos aris tu ara gashvebui firefox brauzeri
    debug = Debug(MyEventHandler()) # vqmnit degub obieqts
    if debug.system.find_processes_by_filename( "firefox.exe" ): # tu ar aris jer firefox gashebuli velodebit
        time.sleep(3) # rom agmoachens rom gashvebulia daicados 3 wami ( rom yvelaferi chaitvirtos da erro ar miigot )
        try:
            for ( process, name ) in debug.system.find_processes_by_filename( "firefox.exe" ): # vigebt procesis shesabamis PID -s da saxels 
                print '[+] Found Firefox PID is ' +  str (process.get_pid())
            debug.attach( process.get_pid() ) # vaketebt procesiss Attach -s
            debug.loop()
        finally:
            debug.stop()
Example #56
0
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from winappdbg import Debug

import sys

# Get the process ID from the command line.
pid = int( sys.argv[1] )

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

    # Attach to a running process.
    debug.attach( pid )

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

# Stop the debugger.
finally:
    debug.stop()
def action_0( event ):
    global debug
    aThread = event.get_thread()
    aProcess = event.get_process()
    r_eax = aThread.get_register("Eax")
    r_ecx = aThread.get_register("Ecx")
    r_edx = aThread.get_register("Edx")
    debug.dont_break_at(aProcess.get_pid() , 0x0043F90F)


words = open('dic.txt', "r").readlines() #lengthall
print "[+] Words Loaded:",len(words)

try:
    debug = Debug()
    # Start a new process for debugging
    p = debug.execv( ['TrueCrypt.exe', '/v', 'test.tc', '/lx', '/p', "".ljust(WORD_SIZE) ,'/q', '/s'])

    debug.break_at(p.get_pid() , 0x0043F90F, action_0) #save state
    debug.break_at(p.get_pid() , 0x0043F929, action_1) #save buffer addres
    debug.break_at(p.get_pid() , 0x0043F93E, action_2) #check result, restore state, change eip

    # Wait for the debugee to finish
    t1 = time.clock() 
    debug.loop()

finally:
    debug.stop()

print 'Finished in ' + repr(time.clock() - t1) + ' seconds!'