Ejemplo n.º 1
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()
Ejemplo n.º 2
0
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])
Ejemplo n.º 3
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()
Ejemplo n.º 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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
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
Ejemplo n.º 9
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()
Ejemplo n.º 10
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()
Ejemplo n.º 11
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()
Ejemplo n.º 12
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()
Ejemplo n.º 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()
Ejemplo n.º 14
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()
Ejemplo n.º 15
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()
Ejemplo n.º 16
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()
Ejemplo n.º 17
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()
Ejemplo n.º 18
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()
Ejemplo n.º 19
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()
    return
Ejemplo n.º 20
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()
Ejemplo n.º 21
0
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
Ejemplo n.º 22
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()
Ejemplo n.º 23
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()
Ejemplo n.º 24
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)
Ejemplo n.º 25
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()
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()
Ejemplo n.º 27
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()
Ejemplo n.º 29
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
Ejemplo n.º 30
0
def main_loop():
    debug_procList = []
    est_conn_procList, reverse_http_procList, cmd_procList, suspicious_veil_procList = extract_est_conn(
    )

    hookcounter = 0
    hookFlag = False
    detachflag = False
    mdlog.print_console(mdlog.INFO_LEVEL,
                        "-------- Start Monitoring ------------")

    while ((len(est_conn_procList) > 0) or (len(cmd_procList) > 0)):
        inScopeList = verify_debugger(debug_procList, est_conn_procList,
                                      reverse_http_procList, cmd_procList)
        mdlog.print_console(mdlog.INFO_LEVEL,
                            "[*] InscopeList: " + str(inScopeList))
        mdlog.print_console(mdlog.INFO_LEVEL,
                            "[*] Enumerating ESTABLISHED_Process")

        for proc in est_conn_procList:
            traceFlag = False
            try:
                if (proc.pid not in inScopeList):
                    #print "Established %d", proc.pid
                    traceFlag = find_meterpreter_trace(
                        proc.pid, DEFAULT_MEMORY_TRACE_LINE_LIMIT)
            except WindowsError, e:
                pass
            except Exception, e:
                mdlog.print_console(
                    mdlog.ERROR_LEVEL,
                    ("[-] Tracing PID:" + str(proc.pid) + " " + str(e)))

            if (traceFlag):
                mdlog.print_console(
                    mdlog.INFO_LEVEL, "[*] tcp_Meterpreter " + str(proc.pid) +
                    " " + str(proc.name) + " " + str(proc.connections()))
                myhandler = md_tcp_meterpreter.hook_handler()
                debug = Debug(myhandler, bKillOnExit=True)
                debug_procList.append([proc.pid, debug])
                thread = Thread(target=intercept_windowapi,
                                args=(debug, proc.pid))
                thread.start()
                time.sleep(1)  #sleep for smooth debugger console
                hookFlag = True