Exemple #1
0
def kill_thread( pid, kill_tid=None ):
    System.request_debug_privileges()

    process = Process(pid)
    process.scan_threads()
    tmp = kill_tid.split(',')
    print tmp, ":", type(tmp), ":", len(tmp)

    for thread in process.iter_threads():
        thread.suspend()
        tid = thread.get_tid()

        try:
            if kill_tid is None or kill_tid == 0:
                hThread = thread.get_handle()
                win32.CloseHandle(hThread)
                win32.TerminateThread(hThread, -999)
            else:
                if len(tmp)>1:
                    for s in tmp:
                        if tid == int(s):
                            print "kill > ", pid, " > ", tid, " > ", kill_tid
                            hThread = thread.get_handle()

                            #win32.CloseHandle(hThread)
                            win32.TerminateThread(hThread, -999)
        except Exception, e:
            print e
            pass
        thread.resume()
Exemple #2
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()
Exemple #3
0
def print_api_address(pid, modName, procName):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process(pid)

    # Lookup it's modules.
    process.scan_modules()

    # Get the module.
    module = process.get_module_by_name(modName)
    if not module:
        print "Module not found: %s" % modName
        return

    # Resolve the requested API function address.
    address = module.resolve(procName)

    # Print the address.
    if address:
        print "%s!%s == 0x%.08x" % (modName, procName, address)
    else:
        print "Could not resolve %s in module %s" % (procName, modName)
def get_explorer_pid():
    # Request debug privileges.
    System.request_debug_privileges()

    # Scan for running processes.
    system = System()
    try:
        system.scan_processes()
        #system.scan_process_filenames()
    except WindowsError:
        system.scan_processes_fast()

    # For each running process...
    for process in system.iter_processes():
        try:

            pid = process.get_pid()

            if pid in (0, 4, 8):
                continue

            if dev:
                print "* Process:", process.get_filename(), "Pid:", pid, "Time:", process.get_running_time()
            if process.get_filename() == "explorer.exe":
                if process.get_running_time() < 300000:
                    return pid

        # Skip processes we don't have permission to access.
        except WindowsError, e:
            if e.winerror == ERROR_ACCESS_DENIED:
                continue
            raise
Exemple #5
0
def main():
    print "Process string extractor"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) != 2:
        script = os.path.basename(sys.argv[0])
        print "  %s <pid>" % script
        print "  %s <process.exe>" % script
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except Exception, e:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print "Process not found: %s" % sys.argv[1]
            return
        if len(pl) > 1:
            print "Multiple processes found for %s" % sys.argv[1]
            for p, n in pl:
                print "\t%s: %s" % (p.get_pid(), n)
            return
        pid = pl[0][0].get_pid()
        s.clear()
        del s
Exemple #6
0
def freeze_threads( pid, _tid=None ):
    System.request_debug_privileges()

    process = Process(pid)
    process.scan_threads()

    tmp = _tid.split(',')
    print tmp, ":", type(tmp), ":", len(tmp)

    for thread in process.iter_threads():
        tid = thread.get_tid()
        _tid = int(tid)
        if _tid is None or _tid == 0 :
            thread.suspend()
            print tid, " suspend()"
        else:
            if len(tmp)>1:
                for s in tmp:
                    if tid == int(s):
                        print tid, " suspend()"
                        thread.suspend()
            else:
                if tid == _tid:
                    print tid, " suspend()"
                    thread.suspend()
def print_thread_disassembly( tid ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Thread object.
    thread = Thread( tid )

    # Suspend the thread execution.
    thread.suspend()

    # Get the thread's currently running code.
    try:
        eip  = thread.get_pc()
        code = thread.disassemble_around( eip )

        # You can also do this:
        # code = thread.disassemble_around_pc()

        # Or even this:
        # process = thread.get_process()
        # code    = process.disassemble_around( eip )

    # Resume the thread execution.
    finally:
        thread.resume()

    # Display the disassembled code.
    print
    print CrashDump.dump_code( code, eip ),
Exemple #8
0
def main():
    print "Process string extractor"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) != 2:
        script = os.path.basename(sys.argv[0])
        print "  %s <pid>" % script
        print "  %s <process.exe>" % script
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except Exception, e:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print "Process not found: %s" % sys.argv[1]
            return
        if len(pl) > 1:
            print "Multiple processes found for %s" % sys.argv[1]
            for p, n in pl:
                print "\t%s: %s" % (p.get_pid(), n)
            return
        pid = pl[0][0].get_pid()
        s.clear()
        del s
def print_thread_disassembly(tid):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Thread object.
    thread = Thread(tid)

    # Suspend the thread execution.
    thread.suspend()

    # Get the thread's currently running code.
    try:
        eip = thread.get_pc()
        code = thread.disassemble_around(eip)

        # You can also do this:
        # code = thread.disassemble_around_pc()

        # Or even this:
        # process = thread.get_process()
        # code    = process.disassemble_around( eip )

    # Resume the thread execution.
    finally:
        thread.resume()

    # Display the disassembled code.
    print()
    print(CrashDump.dump_code(code, eip), end=' ')
Exemple #10
0
def print_api_address( pid, modName, procName ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process( pid )

    # Lookup it's modules.
    process.scan_modules()

    # Get the module.
    module = process.get_module_by_name( modName )
    if not module:
        print "Module not found: %s" % modName
        return

    # Resolve the requested API function address.
    address = module.resolve( procName )

    # Print the address.
    if address:
        print "%s!%s == 0x%.08x" % ( modName, procName, address )
    else:
        print "Could not resolve %s in module %s" % (procName, modName)
Exemple #11
0
def print_state( process_name ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Find the first process that matches the requested name.
    system = System()
    process, filename = system.find_processes_by_filename( process_name )[ 0 ]

    # Suspend the process execution.
    process.suspend()
    try:

        # For each thread in the process...
        for thread in process.iter_threads():

            # Get the thread state.
            tid     = thread.get_tid()
            eip     = thread.get_pc()
            code    = thread.disassemble_around( eip )
            context = thread.get_context()

            # Display the thread state.
            print
            print "-" * 79
            print "Thread: %s" % HexDump.integer( tid )
            print
            print CrashDump.dump_registers( context )
            print CrashDump.dump_code( code, eip ),
            print "-" * 79

    # Resume the process execution.
    finally:
        process.resume()
class TSMonitorHandler:
    def __init__(self):
        self._system = System()
        self._system.request_debug_privileges()
        self._process = {}
        for process in self._system:
            self._process[process.get_pid()] = process

    def ping(self):
        print "function ping called."
        return 0

    def refresh(self):
        print "function refresh called."
        self.__init__()
        return 0

    def process(self, id):

        p = self._process[id]

        process = tsm.Process()
        process.id = id
        if id == 0:
            process.name = "System Idle Process"
        elif id == 4:
            process.name = "System"
        else:
            process.name = os.path.basename(p.get_filename())

        p.scan_threads()

        tids = p.get_thread_ids()
        #tids.sort()
        process.num_threads = len(tids)
        
        process.thread = []
        for tid in tids:
            # Suspend the thread executior
            try:
                th = p.get_thread(tid)
                th.suspend()
                stack_limit, stack_base = th.get_stack_range()
                thread = tsm.Thread()
                thread.id = tid
                thread.stack_size = stack_base - stack_limit
                process.thread.append(thread)

            except WindowsError:
                thread = tsm.Thread()
                thread.id = tid
                thread.stack_size = -1
                process.thread.append(thread)

            # Resume the thread execution
            finally:
                th.resume()

        return process
Exemple #13
0
def unfreeze_threads(pid):
    System.request_debug_privileges()

    process = Process(pid)
    #process.resume()
    process.scan_threads()
    for thread in process.iter_threads():
        thread.resume()
Exemple #14
0
def main():
    print("Process memory reader")
    print("by Mario Vilas (mvilas at gmail.com)")
    print

    if len(sys.argv) not in (4, 5):
        script = os.path.basename(sys.argv[0])
        print("  %s <pid> <address> <size> [binary output file]" % script)
        print("  %s <process.exe> <address> <size> [binary output file]" %
              script)
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print("Process not found: %s" % sys.argv[1])
            return
        if len(pl) > 1:
            print("Multiple processes found for %s" % sys.argv[1])
            for p, n in pl:
                print("\t%s: %s" % (HexDump.integer(p), n))
            return
        pid = pl[0][0].get_pid()

    try:
        address = HexInput.integer(sys.argv[2])
    except Exception:
        print("Invalid value for address: %s" % sys.argv[2])
        return

    try:
        size = HexInput.integer(sys.argv[3])
    except Exception:
        print("Invalid value for size: %s" % sys.argv[3])
        return

    p = Process(pid)
    data = p.read(address, size)
    ##    data = p.peek(address, size)
    print("Read %d bytes from PID %d" % (len(data), pid))

    if len(sys.argv) == 5:
        filename = sys.argv[4]
        open(filename, 'wb').write(data)
        print("Written %d bytes to %s" % (len(data), filename))
    else:
        if win32.sizeof(win32.LPVOID) == win32.sizeof(win32.DWORD):
            width = 16
        else:
            width = 8
        print
        print(HexDump.hexblock(data, address, width=width))
Exemple #15
0
def main():
    print "Process memory reader"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) not in (4, 5):
        script = os.path.basename(sys.argv[0])
        print "  %s <pid> <address> <size> [binary output file]" % script
        print "  %s <process.exe> <address> <size> [binary output file]" % script
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print "Process not found: %s" % sys.argv[1]
            return
        if len(pl) > 1:
            print "Multiple processes found for %s" % sys.argv[1]
            for p,n in pl:
                print "\t%s: %s" % (HexDump.integer(p),n)
            return
        pid = pl[0][0].get_pid()

    try:
        address = HexInput.integer(sys.argv[2])
    except Exception:
        print "Invalid value for address: %s" % sys.argv[2]
        return

    try:
        size = HexInput.integer(sys.argv[3])
    except Exception:
        print "Invalid value for size: %s" % sys.argv[3]
        return

    p = Process(pid)
    data = p.read(address, size)
##    data = p.peek(address, size)
    print "Read %d bytes from PID %d" % (len(data), pid)

    if len(sys.argv) == 5:
        filename = sys.argv[4]
        open(filename, 'wb').write(data)
        print "Written %d bytes to %s" % (len(data), filename)
    else:
        if win32.sizeof(win32.LPVOID) == win32.sizeof(win32.DWORD):
            width = 16
        else:
            width = 8
        print
        print HexDump.hexblock(data, address, width = width)
Exemple #16
0
def freeze_threads(pid):

    System.request_debug_privileges()

    process = Process(pid)

    process.scan_threads()

    for thread in process.iter_threads():
        thread.suspend()
Exemple #17
0
def show(search=None, wide=True):
    'show a table with the list of services'

    # Take a snapshot of the running processes.
    s = System()
    s.request_debug_privileges()
    try:
        s.scan_processes()
        s.scan_process_filenames()
    except WindowsError:
        s.scan_processes_fast()
    pid_list = s.get_process_ids()
    pid_list.sort()
    if not pid_list:
        print "Unknown error enumerating processes!"
        return

    # Get the filename of each process.
    filenames = dict()
    for pid in pid_list:
        p = s.get_process(pid)

        # Special process IDs.
        # PID 0: System Idle Process. Also has a special meaning to the
        #        toolhelp APIs (current process).
        # PID 4: System Integrity Group. See this forum post for more info:
        #        http://tinyurl.com/ycza8jo
        #        (points to social.technet.microsoft.com)
        #        Only on XP and above
        # PID 8: System (?) only in Windows 2000 and below AFAIK.
        #        It's probably the same as PID 4 in XP and above.
        if pid in (0, 4, 8):
            fileName = ""

        # Get the filename for all other processes.
        else:
            fileName = p.get_filename()
            if fileName:
                fileName = PathOperations.pathname_to_filename(fileName)
            else:
                fileName = ""

        # Remember the filename.
        filenames[pid] = fileName

    # Make the search string lowercase if given.
    if search is not None:
        search = search.lower()

    # Get the list of services.
    try:
        services = System.get_services()
    except WindowsError, e:
        print str(e)
        return
def show(search = None, wide = True):
    'show a table with the list of services'

    # Take a snapshot of the running processes.
    s = System()
    s.request_debug_privileges()
    try:
        s.scan_processes()
        s.scan_process_filenames()
    except WindowsError:
        s.scan_processes_fast()
    pid_list = s.get_process_ids()
    pid_list.sort()
    if not pid_list:
        print "Unknown error enumerating processes!"
        return

    # Get the filename of each process.
    filenames = dict()
    for pid in pid_list:
        p = s.get_process(pid)

        # Special process IDs.
        # PID 0: System Idle Process. Also has a special meaning to the
        #        toolhelp APIs (current process).
        # PID 4: System Integrity Group. See this forum post for more info:
        #        http://tinyurl.com/ycza8jo
        #        (points to social.technet.microsoft.com)
        #        Only on XP and above
        # PID 8: System (?) only in Windows 2000 and below AFAIK.
        #        It's probably the same as PID 4 in XP and above.
        if pid in (0, 4, 8):
            fileName = ""

        # Get the filename for all other processes.
        else:
            fileName = p.get_filename()
            if fileName:
                fileName = PathOperations.pathname_to_filename(fileName)
            else:
                fileName = ""

        # Remember the filename.
        filenames[pid] = fileName

    # Make the search string lowercase if given.
    if search is not None:
        search = search.lower()

    # Get the list of services.
    try:
        services = System.get_services()
    except WindowsError, e:
        print str(e)
        return
Exemple #19
0
def main(argv):

    # Print the banner.
    print "SelectMyParent: Start a program with a selected parent process"
    print "by Mario Vilas (mvilas at gmail.com)"
    print "based on a Didier Stevens tool (https://DidierStevens.com)"
    print

    # Check the command line arguments.
    if len(argv) < 3:
        script = os.path.basename(argv[0])
        print "  %s <pid> <process.exe> [arguments]" % script
        return

    # Request debug privileges.
    system = System()
    system.request_debug_privileges()

    # Parse the parent process argument.
    try:
        dwParentProcessId = HexInput.integer(argv[1])
    except ValueError:
        dwParentProcessId = None
    if dwParentProcessId is not None:
        dwMyProcessId = win32.GetProcessId( win32.GetCurrentProcess() )
        if dwParentProcessId != dwMyProcessId:
            system.scan_processes_fast()
            if not system.has_process(dwParentProcessId):
                print "Can't find process ID %d" % dwParentProcessId
                return
    else:
        system.scan_processes()
        process_list = system.find_processes_by_filename(argv[1])
        if not process_list:
            print "Can't find process %r" % argv[1]
            return
        if len(process_list) > 1:
            print "Too many processes found:"
            for process, name in process_list:
                print "\t%d:\t%s" % (process.get_pid(), name)
            return
        dwParentProcessId = process_list[0][0].get_pid()

    # Parse the target process argument.
    filename = argv[2]
    if not os.path.exists(filename):
        try:
            filename = win32.SearchPath(None, filename, '.exe')[0]
        except WindowsError, e:
            print "Error searching for %s: %s" % (filename, str(e))
            return
        argv = list(argv)
        argv[2] = filename
Exemple #20
0
def main(argv):

    # Print the banner.
    print "SelectMyParent: Start a program with a selected parent process"
    print "by Mario Vilas (mvilas at gmail.com)"
    print "based on a Didier Stevens tool (https://DidierStevens.com)"
    print

    # Check the command line arguments.
    if len(argv) < 3:
        script = os.path.basename(argv[0])
        print "  %s <pid> <process.exe> [arguments]" % script
        return

    # Request debug privileges.
    system = System()
    system.request_debug_privileges()

    # Parse the parent process argument.
    try:
        dwParentProcessId = HexInput.integer(argv[1])
    except ValueError:
        dwParentProcessId = None
    if dwParentProcessId is not None:
        dwMyProcessId = win32.GetProcessId(win32.GetCurrentProcess())
        if dwParentProcessId != dwMyProcessId:
            system.scan_processes_fast()
            if not system.has_process(dwParentProcessId):
                print "Can't find process ID %d" % dwParentProcessId
                return
    else:
        system.scan_processes()
        process_list = system.find_processes_by_filename(argv[1])
        if not process_list:
            print "Can't find process %r" % argv[1]
            return
        if len(process_list) > 1:
            print "Too many processes found:"
            for process, name in process_list:
                print "\t%d:\t%s" % (process.get_pid(), name)
            return
        dwParentProcessId = process_list[0][0].get_pid()

    # Parse the target process argument.
    filename = argv[2]
    if not ntpath.exists(filename):
        try:
            filename = win32.SearchPath(None, filename, '.exe')[0]
        except WindowsError, e:
            print "Error searching for %s: %s" % (filename, str(e))
            return
        argv = list(argv)
        argv[2] = filename
Exemple #21
0
def print_thread_context(tid):
    System.request_debug_privileges()

    thread = Thread(tid)
    thread.suspend()

    try:
        context = thread.get_context()
    finally:
        thread.resume()

    print
    print CrashDump.dump_registers(context)
 def testRunningProcesses(self):
     validator = MemoryValidatorClass()
     validator.Initialize("c:\\mem\\user\\")
     CounterMonitor.Start()
     System.request_debug_privileges()
     with UpdateCounterForScope("main"):
         system = System()
         system.scan_processes()
         totalProcesses = system.get_process_count()
         for processIndex, process in enumerate(system.iter_processes()):
             fileName = getattr(process, "fileName")
             pid = getattr(process, "dwProcessId")
             if not fileName or not pid:
                 continue
             validator.ImageName = fileName
             logging.info("---------------------------------------------")
             validator.Message = "[{}] fileName:{} pid:{}".format(processIndex, fileName, pid)
             logging.info(validator.Message)
             if not any(s in fileName for s in self.PROCESS_TO_SCAN):
                 continue
             print "------process {}/{} {}-------".format(processIndex, totalProcesses, fileName)
             with validator.ExceptionHandler("Failed comparing {0}".format(fileName)):
                 process.scan_modules()
                 mods = {}
                 for module in process.iter_modules():
                     baseDllName = ntpath.basename(module.get_filename().lower())
                     mod = {
                         "BaseDllName": baseDllName,
                         "FullDllName": module.get_filename().lower(),
                         "StartAddr": module.get_base(),
                         "EndAddr": module.get_base() + module.get_size(),
                         "SizeOfImage": module.get_size(),
                     }
                     if not mods.get(baseDllName):
                         mods[baseDllName] = []
                     mods[baseDllName].append(mod)
                 validator.BuildLoadedModuleAddressesFromWinAppDbg(mods)
                 totalMods = len(mods)
                 for modIndex, modList in enumerate(mods.itervalues()):
                     print "module {}/{} {}".format(modIndex, totalMods, modList[0]["BaseDllName"])
                     for modIndex, mod in enumerate(modList):
                         validator.InitializeModuleInfoFromWinAppDbg(mod)
                         with validator.ExceptionHandler("failed comparing {0}".format(mod)):
                             memoryData = process.read(validator.DllBase, validator.SizeOfImage)
                             if not memoryData:
                                 validator.Warn("failed to read memory data")
                                 continue
                             validator.CompareExe(memoryData, validator.FullDllPath)
     CounterMonitor.Stop()
     validator.DumpFinalStats()
 def testRunningProcesses(self):
     validator = MemoryValidatorClass()
     validator.Initialize('c:\\mem\\user\\')
     CounterMonitor.Start()
     System.request_debug_privileges()
     with UpdateCounterForScope('main'):
         system = System()
         system.scan_processes()
         totalProcesses = system.get_process_count()
         for processIndex, process in enumerate(system.iter_processes()):
             fileName = getattr(process, 'fileName')
             pid = getattr(process, 'dwProcessId')
             if not fileName or not pid:
                 continue
             validator.ImageName = fileName
             logging.info("---------------------------------------------")
             validator.Message = "[{}] fileName:{} pid:{}".format(processIndex, fileName, pid)
             logging.info(validator.Message)
             if not any(s in fileName for s in self.PROCESS_TO_SCAN):
                 continue
             print '------process {}/{} {}-------'.format(processIndex, totalProcesses, fileName)
             with validator.ExceptionHandler('Failed comparing {0}'.format(fileName)):
                 process.scan_modules()
                 mods = {}
                 for module in process.iter_modules():
                     baseDllName = ntpath.basename(module.get_filename().lower())
                     mod = {
                         'BaseDllName' : baseDllName,
                         'FullDllName' : module.get_filename().lower(),
                         'StartAddr' : module.get_base(),
                         'EndAddr' : module.get_base() + module.get_size(),
                         'SizeOfImage' : module.get_size()
                     }
                     if not mods.get(baseDllName):
                         mods[baseDllName] = []
                     mods[baseDllName].append(mod)
                 validator.BuildLoadedModuleAddressesFromWinAppDbg(mods)
                 totalMods = len(mods)
                 for modIndex, modList in enumerate(mods.itervalues()):
                     print 'module {}/{} {}'.format(modIndex, totalMods, modList[0]['BaseDllName'])
                     for modIndex, mod in enumerate(modList):
                         validator.InitializeModuleInfoFromWinAppDbg(mod)
                         with validator.ExceptionHandler('failed comparing {0}'.format(mod)):
                             memoryData = process.read(validator.DllBase, validator.SizeOfImage)
                             if not memoryData:
                                 validator.Warn('failed to read memory data')
                                 continue
                             validator.CompareExe(memoryData, validator.FullDllPath)
     CounterMonitor.Stop()
     validator.DumpFinalStats()
Exemple #24
0
def main():
    print("Process memory writer")
    print("by Mario Vilas (mvilas at gmail.com)")
    print()

    if len(sys.argv) < 4:
        script = os.path.basename(sys.argv[0])
        print("  %s <pid> <address> {binary input file / hex data}" % script)
        print("  %s <process.exe> <address> {binary input file / hex data}" %
              script)
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except Exception:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print("Process not found: %s" % sys.argv[1])
            return
        if len(pl) > 1:
            print("Multiple processes found for %s" % sys.argv[1])
            for p, n in pl:
                print("\t%s: %s" % (HexDump.integer(p), n))
            return
        pid = pl[0][0].get_pid()

    try:
        address = HexInput.integer(sys.argv[2])
    except Exception:
        print("Invalid value for address: %s" % sys.argv[2])
        return

    filename = ' '.join(sys.argv[3:])
    if os.path.exists(filename):
        data = open(filename, 'rb').read()
        print("Read %d bytes from %s" % (len(data), filename))
    else:
        try:
            data = HexInput.hexadecimal(filename)
        except Exception:
            print("Invalid filename or hex block: %s" % filename)
            return

    p = Process(pid)
    p.write(address, data)
    print("Written %d bytes to PID %d" % (len(data), pid))
Exemple #25
0
def main():
    print "Process memory writer"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) < 4:
        script = os.path.basename(sys.argv[0])
        print "  %s <pid> <address> {binary input file / hex data}" % script
        print "  %s <process.exe> <address> {binary input file / hex data}" % script
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except Exception:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print "Process not found: %s" % sys.argv[1]
            return
        if len(pl) > 1:
            print "Multiple processes found for %s" % sys.argv[1]
            for p,n in pl:
                print "\t%s: %s" % (HexDump.integer(p),n)
            return
        pid = pl[0][0].get_pid()

    try:
        address = HexInput.integer(sys.argv[2])
    except Exception:
        print "Invalid value for address: %s" % sys.argv[2]
        return

    filename = ' '.join(sys.argv[3:])
    if os.path.exists(filename):
        data = open(filename, 'rb').read()
        print "Read %d bytes from %s" % (len(data), filename)
    else:
        try:
            data = HexInput.hexadecimal(filename)
        except Exception:
            print "Invalid filename or hex block: %s" % filename
            return

    p = Process(pid)
    p.write(address, data)
    print "Written %d bytes to PID %d" % (len(data), pid)
Exemple #26
0
def print_label(pid, address):
    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process(pid)

    # Lookup it's modules.
    process.scan_modules()

    # Resolve the requested label address.
    label = process.get_label_at_address(address)

    # Print the label.
    print("%s == 0x%.08x" % (label, address))
Exemple #27
0
def print_label_address( pid, label ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process( pid )

    # Lookup it's modules.
    process.scan_modules()

    # Resolve the requested label address.
    address = process.resolve_label( label )

    # Print the address.
    print "%s == 0x%.08x" % ( label, address )
Exemple #28
0
def main():
    """TODO
    """
    print "...as script dumper for as3s.exe..."

    if len(sys.argv) != 2:
        print "usage: %s swf.as" % sys.argv[0]
        return

    try:
        s = System()
        s.request_debug_privileges()
        s.scan()
        p = s.find_processes_by_filename("as3s.exe")[0][0]
    except Exception, e:
        print "[-] oops..." % str(e)
        return
Exemple #29
0
def print_thread_disassembly(tid):
    System.request_debug_privileges()

    thread = Thread(tid)
    thread.suspend()

    try:
        eip = thread.get_pc()
        code = thread.disassemble_around(eip)
        #or code = thread.disassemble_around_pc()
        #or process = thread.get_process()
        #   code = process.disassemble_around(eip)
    finally:
        thread.resume()

    print
    print CrashDump.dump_code(code, eip)
def reslove_iat_pointers(pid, iat_ptrs):
    """Use winappdbg to resolve IAT pointers to their respective module and function names
    @param pid: process ID to connect to
    @param iat_ptrs: list of pointer addresses to be resolved
    """
    ######################################################################
    #
    # Attach to process and start using winappdbg
    #
    ######################################################################
    # Request debug privileges.
    System.request_debug_privileges()

    # Attach to process
    process = Process(pid)
    # Lookup the process modules.
    process.scan_modules()

    # imp_table[ <funct_pointer> ] = [ <module_name>, <function_name> ] 
    imp_table = {}
    for iat_ptr in iat_ptrs:
        # For each iat pointer get the function name as a label populated by winappdbg
        label = process.get_label_at_address(process.peek_dword(iat_ptr))
        module,function,offset = Process.split_label_strict(label)
        # Only add functions that have valid labels
        if function != None:
            imp_table[iat_ptr] = [module, function]

    assert len(imp_table) != 0, "Unable to find imports in code!"
    
    ######################################################################
    #
    # Because we may have missed some IAT pointers with our scanner we 
    # are going to attempt to locate the full mapped IAT directory in the 
    # section then enumerate ever pointer in the directory. And use that 
    # list instead. 
    #
    ######################################################################
    imp_table_new={}
    for iat_ptr in range(min(imp_table.keys()), max(imp_table.keys())+4, 4):
        # Resolve the requested label address.
        label = process.get_label_at_address(process.peek_dword(iat_ptr))
        module,function,offset = Process.split_label_strict(label)
        if function != None:
            imp_table_new[iat_ptr] = [module, function]
    return imp_table_new
Exemple #31
0
def main():
    """TODO
    """
    print "...as script dumper for as3s.exe..."

    if len(sys.argv) != 2:
        print "usage: %s swf.as" % sys.argv[0]
        return

    try:
        s = System()
        s.request_debug_privileges()
        s.scan()
        p = s.find_processes_by_filename("as3s.exe")[0][0]
    except Exception, e:
        print "[-] oops..." % str(e)
        return
Exemple #32
0
def list_thread( pid ):
    System.request_debug_privileges()

    process = Process(pid)
    process.scan_threads()

    list=[]
    for thread in process.iter_threads():
        tid = thread.get_tid()
        list.append(str(tid))
        try:
            print_thread_context( tid )
        except:
            pass
    pid_line = ','.join(list)
    print pid_line

    return pid_line
Exemple #33
0
def main():
    print "Process DLL injector"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) != 3:
        script = os.path.basename(sys.argv[0])
        print "Injects a DLL into a running process."
        print "  %s <pid> <library.dll>" % script
        print "  %s <process.exe> <library.dll>" % script
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except Exception:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print "Process not found: %s" % sys.argv[1]
            return
        if len(pl) > 1:
            print "Multiple processes found for %s" % sys.argv[1]
            for p,n in pl:
                print "\t%12d: %s" % (p,n)
            return
        pid = pl[0][0].get_pid()
    print "Using PID %d (0x%x)" % (pid, pid)

    dll = sys.argv[2]
    print "Using DLL %s" % dll

    p = Process(pid)
    b = p.get_bits()
    if b != System.bits:
        print (
            "Cannot inject into a %d bit process from a %d bit Python VM!"
            % (b, System.bits)
        )
        return
    p.scan_modules()
    p.inject_dll(dll)
Exemple #34
0
def main():
    print("Process DLL injector")
    print("by Mario Vilas (mvilas at gmail.com)")
    print

    if len(sys.argv) != 3:
        script = os.path.basename(sys.argv[0])
        print("Injects a DLL into a running process.")
        print("  %s <pid> <library.dll>" % script)
        print("  %s <process.exe> <library.dll>" % script)
        return

    System.request_debug_privileges()

    try:
        pid = HexInput.integer(sys.argv[1])
    except Exception:
        s = System()
        s.scan_processes()
        pl = s.find_processes_by_filename(sys.argv[1])
        if not pl:
            print("Process not found: %s" % sys.argv[1])
            return
        if len(pl) > 1:
            print("Multiple processes found for %s" % sys.argv[1])
            for p,n in pl:
                print("\t%12d: %s" % (p,n))
            return
        pid = pl[0][0].get_pid()
    print("Using PID %d (0x%x)" % (pid, pid))

    dll = sys.argv[2]
    print("Using DLL %s" % dll)

    p = Process(pid)
    b = p.get_bits()
    if b != System.bits:
        print(()
            "Cannot inject into a %d bit process from a %d bit Python VM!"
            % (b, System.bits)
        )
        return
    p.scan_modules()
    p.inject_dll(dll)
def find_hook_pid( procname ):
    global gpid
    global xp
    global oldpid

    s = System()
    s.request_debug_privileges()
    
    try:
        s.scan_processes()
        s.scan_process_filenames()
    except WindowsError:
        s.scan_processes_fast()
        
    pid_list = s.get_process_ids()
    pid_list.sort(reverse=True)
    
    if not pid_list:
        print "Unknown error enumerating processes!"
        # s = raw_input()
        sys.exit(1)
    
    for pid in pid_list:
        p = s.get_process(pid)
        fileName = p.get_filename()
        fname = str(fileName).lower()
        if dev:
            print "Process:", fname, "Pid:", pid
        if fname.find(procname) >= 0:
            if int(pid) != int(gpid):
                oldpid = gpid
                gpid = pid
                if procname.find("svchost.exe") >= 0:
                    gpid = int(get_svchost_pid())
                    return gpid
                elif procname.find("explorer.exe") >= 0:
                    gpid = int(get_explorer_pid())
                    return gpid
                else:
                    return pid
    return 0
Exemple #36
0
def print_label_address(pid, label):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process(pid)

    # Lookup it's modules.
    process.scan_modules()

    # Resolve the requested label address.
    address = process.resolve_label(label)

    # titles = [i for i in process.search("Trying to change notepad text\0")]
    # msg = [k for k in 'New text here ! \0']
    # for i in range(len(msg)):
    #     process.poke(46859072 + i * 2, msg[i].encode())

    # Print the address.
    print("%s == 0x%.08x" % (label, address))
Exemple #37
0
def unfreeze_threads( pid ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process( pid )

    # This would also do the trick...
    #
    #   process.resume()
    #
    # ...but let's do it the hard way:

    # Lookup the threads in the process.
    process.scan_threads()

    # For each thread in the process...
    for thread in process.iter_threads():

        # Resume the thread execution.
        thread.resume()
Exemple #38
0
def print_thread_context( tid ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Thread object.
    thread = Thread( tid )

    # Suspend the thread execution.
    thread.suspend()

    # Get the thread context.
    try:
        context = thread.get_context()

    # Resume the thread execution.
    finally:
        thread.resume()

    # Display the thread context.
    print()
    print (CrashDump.dump_registers( context ),)
Exemple #39
0
def print_thread_context( tid ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Thread object.
    thread = Thread( tid )

    # Suspend the thread execution.
    thread.suspend()

    # Get the thread context.
    try:
        context = thread.get_context()

    # Resume the thread execution.
    finally:
        thread.resume()

    # Display the thread context.
    print
    print CrashDump.dump_registers( context ),
Exemple #40
0
def unfreeze_threads( pid ):

    # Request debug privileges.
    System.request_debug_privileges()

    # Instance a Process object.
    process = Process( pid )

    # This would also do the trick...
    #
    #   process.resume()
    #
    # ...but let's do it the hard way:

    # Lookup the threads in the process.
    process.scan_threads()

    # For each thread in the process...
    for thread in process.iter_threads():

        # Resume the thread execution.
        thread.resume()
Exemple #41
0
def print_alnum_jump_addresses(pid):

    # Request debug privileges so we can inspect the memory of services too.
    System.request_debug_privileges()

    # Suspend the process so there are no malloc's and free's while iterating.
    process = Process(pid)
    process.suspend()
    try:

        # For each executable alphanumeric address...
        for address, packed, module in iterate_alnum_jump_addresses(process):

            # Format the address for printing.
            numeric = HexDump.address(address, process.get_bits())
            ascii   = repr(packed)

            # Format the module name for printing.
            if module:
                modname = module.get_name()
            else:
                modname = ""

            # Try to disassemble the code at this location.
            try:
                code = process.disassemble(address, 16)[0][2]
            except NotImplementedError:
                code = ""

            # Print it.
            print numeric, ascii, modname, code

    # Resume the process when we're done.
    # This is inside a "finally" block, so if the program is interrupted
    # for any reason we don't leave the process suspended.
    finally:
        process.resume()
Exemple #42
0
def print_alnum_jump_addresses(pid):

    # Request debug privileges so we can inspect the memory of services too.
    System.request_debug_privileges()

    # Suspend the process so there are no malloc's and free's while iterating.
    process = Process(pid)
    process.suspend()
    try:

        # For each executable alphanumeric address...
        for address, packed, module in iterate_alnum_jump_addresses(process):

            # Format the address for printing.
            numeric = HexDump.address(address, process.get_bits())
            ascii = repr(packed)

            # Format the module name for printing.
            if module:
                modname = module.get_name()
            else:
                modname = ""

            # Try to disassemble the code at this location.
            try:
                code = process.disassemble(address, 16)[0][2]
            except NotImplementedError:
                code = ""

            # Print it.
            print numeric, ascii, modname, code

    # Resume the process when we're done.
    # This is inside a "finally" block, so if the program is interrupted
    # for any reason we don't leave the process suspended.
    finally:
        process.resume()
Exemple #43
0
def parse_cmdline( argv ):

    # Help message and version string
    version = (
              "Process execution tracer\n"
              "by Mario Vilas (mvilas at gmail.com)\n"
              "%s\n"
              ) % winappdbg.version
    usage = (
            "\n"
            "\n"
            "  Create a new process (parameters for the target must be escaped):\n"
            "    %prog [options] -c <executable> [parameters for the target]\n"
            "    %prog [options] -w <executable> [parameters for the target]\n"
            "\n"
            "  Attach to a running process (by filename):\n"
            "    %prog [options] -a <executable>\n"
            "\n"
            "  Attach to a running process (by ID):\n"
            "    %prog [options] -a <process id>"
            )
##    formatter = optparse.IndentedHelpFormatter()
##    formatter = optparse.TitledHelpFormatter()
    parser = optparse.OptionParser(
                                    usage=usage,
                                    version=version,
##                                    formatter=formatter,
                                  )

    # Commands
    commands = optparse.OptionGroup(parser, "Commands")
    commands.add_option("-a", "--attach", action="append", type="string",
                        metavar="PROCESS",
                        help="Attach to a running process")
    commands.add_option("-w", "--windowed", action="callback", type="string",
                        metavar="CMDLINE", callback=callback_execute_target,
                        help="Create a new windowed process")
    commands.add_option("-c", "--console", action="callback", type="string",
                        metavar="CMDLINE", callback=callback_execute_target,
                        help="Create a new console process [default]")
    parser.add_option_group(commands)

    # Tracing options
    tracing = optparse.OptionGroup(parser, "Tracing options")
    tracing.add_option("--trace", action="store_const", const="trace",
                                                               dest="mode",
                      help="Set the single step mode [default]")
    if System.arch == win32.ARCH_I386:
        tracing.add_option("--branch", action="store_const", const="branch",
                                                                   dest="mode",
                          help="Set the step-on-branch mode (doesn't work on virtual machines)")
        tracing.add_option("--syscall", action="store_const", const="syscall",
                                                                   dest="mode",
                          help="Set the syscall trap mode")
##    tracing.add_options("--module", action="append", metavar="MODULES",
##                                                            dest="modules",
##                   help="only trace into these modules (comma-separated)")
##    debugging.add_option("--from-start", action="store_true",
##                  help="start tracing when the process is created [default]")
##    debugging.add_option("--from-entry", action="store_true",
##                  help="start tracing when the entry point is reached")
    parser.add_option_group(tracing)

    # Debugging options
    debugging = optparse.OptionGroup(parser, "Debugging options")
    debugging.add_option("--autodetach", action="store_true",
                  help="automatically detach from debugees on exit [default]")
    debugging.add_option("--follow", action="store_true",
                  help="automatically attach to child processes [default]")
    debugging.add_option("--trusted", action="store_false", dest="hostile",
                  help="treat debugees as trusted code [default]")
    debugging.add_option("--dont-autodetach", action="store_false",
                                                         dest="autodetach",
                  help="don't automatically detach from debugees on exit")
    debugging.add_option("--dont-follow", action="store_false",
                                                             dest="follow",
                  help="don't automatically attach to child processes")
    debugging.add_option("--hostile", action="store_true",
                  help="treat debugees as hostile code")
    parser.add_option_group(debugging)

    # Defaults
    parser.set_defaults(
        autodetach  = True,
        follow      = True,
        hostile     = False,
        windowed    = list(),
        console     = list(),
        attach      = list(),
##        modules     = list(),
        mode        = "trace",
    )

    # Parse and validate the command line options
    if len(argv) == 1:
        argv = argv + [ '--help' ]
    (options, args) = parser.parse_args(argv)
    args = args[1:]
    if not options.windowed and not options.console and not options.attach:
        if not args:
            parser.error("missing target application(s)")
        options.console = [ args ]
    else:
        if args:
            parser.error("don't know what to do with extra parameters: %s" % args)

    # Get the list of attach targets
    system = System()
    system.request_debug_privileges()
    system.scan_processes()
    attach_targets = list()
    for token in options.attach:
        try:
            dwProcessId = HexInput.integer(token)
        except ValueError:
            dwProcessId = None
        if dwProcessId is not None:
            if not system.has_process(dwProcessId):
                parser.error("can't find process %d" % dwProcessId)
            try:
                process = Process(dwProcessId)
                process.open_handle()
                process.close_handle()
            except WindowsError, e:
                parser.error("can't open process %d: %s" % (dwProcessId, e))
            attach_targets.append(dwProcessId)
        else:
            matched = system.find_processes_by_filename(token)
            if not matched:
                parser.error("can't find process %s" % token)
            for process, name in matched:
                dwProcessId = process.get_pid()
                try:
                    process = Process(dwProcessId)
                    process.open_handle()
                    process.close_handle()
                except WindowsError, e:
                    parser.error("can't open process %d: %s" % (dwProcessId, e))
                attach_targets.append( process.get_pid() )
Exemple #44
0
def main(argv):
    script = os.path.basename(argv[0])
    params = argv[1:]

    print "Process killer"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(params) == 0 or '-h' in params or '--help' in params or \
                                                     '/?' in params:
        print "Usage:"
        print "    %s <process ID or name> [process ID or name...]"
        print
        print "If a process name is given instead of an ID all matching processes are killed."
        exit()

    # Scan for active processes.
    # This is needed both to translate names to IDs, and to validate the user-supplied IDs.
    s = System()
    s.request_debug_privileges()
    s.scan_processes()

    # Parse the command line.
    # Each ID is validated against the list of active processes.
    # Each name is translated to an ID.
    # On error, the program stops before killing any process at all.
    targets = set()
    for token in params:
        try:
            pid = HexInput.integer(token)
        except ValueError:
            pid = None
        if pid is None:
            matched = s.find_processes_by_filename(token)
            if not matched:
                print "Error: process not found: %s" % token
                exit()
            for (process, name) in matched:
                targets.add(process.get_pid())
        else:
            if not s.has_process(pid):
                print "Error: process not found: 0x%x (%d)" % (pid, pid)
                exit()
            targets.add(pid)
    targets = list(targets)
    targets.sort()
    count = 0

    # Try to terminate the processes using the TerminateProcess() API.
    next_targets = list()
    for pid in targets:
        next_targets.append(pid)
        try:
            # Note we don't really need to call open_handle and close_handle,
            # but it's good to know exactly which API call it was that failed.
            process = Process(pid)
            process.open_handle()
            try:
                process.kill(-1)
                next_targets.pop()
                count += 1
                print "Terminated process %d" % pid
                try:
                    process.close_handle()
                except WindowsError, e:
                    print "Warning: call to CloseHandle() failed: %s" % str(e)
            except WindowsError, e:
                print "Warning: call to TerminateProcess() failed: %s" % str(e)
        except WindowsError, e:
            print "Warning: call to OpenProcess() failed: %s" % str(e)
Exemple #45
0
def main(argv):
    'Main function.'

    # Print the banner.
    print "Process enumerator"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    # Parse the command line options.
    (options, argv)  = parse_cmdline(argv)
    showFilenameOnly = not options.full_path
    searchString     = options.search

    # Windows filenames are case insensitive.
    if searchString:
        searchString = searchString.lower()

    # Take a snapshot of the running processes.
    s = System()
    s.request_debug_privileges()
    try:
        s.scan_processes()
        if not showFilenameOnly:
            s.scan_process_filenames()
    except WindowsError:
        s.scan_processes_fast()
    pid_list = s.get_process_ids()
    pid_list.sort()
    if not pid_list:
        print "Unknown error enumerating processes!"
        return

    # Get the filename of each process.
    filenames = dict()
    for pid in pid_list:
        p = s.get_process(pid)
        fileName = p.get_filename()

        # Special process IDs.
        # PID 0: System Idle Process. Also has a special meaning to the
        #        toolhelp APIs (current process).
        # PID 4: System Integrity Group. See this forum post for more info:
        #        http://tinyurl.com/ycza8jo
        #        (points to social.technet.microsoft.com)
        #        Only on XP and above
        # PID 8: System (?) only in Windows 2000 and below AFAIK.
        #        It's probably the same as PID 4 in XP and above.
        if pid == 0:
            fileName = "[System Idle Process]"
        elif pid == 4:
            fileName = "[System Integrity Group]"
        elif pid == 8:
            fileName = "[System]"

        # Filename not available.
        elif not fileName:
            fileName = ""

        # Get the process pathname instead, if requested.
        elif showFilenameOnly:
            fileName = PathOperations.pathname_to_filename(fileName)

        # Filter the output with the search string.
        if searchString and searchString not in fileName.lower():
            continue

        # Remember the filename.
        filenames[pid] = fileName

    # Get the window captions if requested.
    # TODO: show window handles too if possible
    captions = dict()
    if options.windows:
        for w in s.get_windows():
            try:
                pid = w.get_pid()
                text = w.get_text()
            except WindowsError:
                continue
            try:
                captions[pid].add(text)
            except KeyError:
                capset = set()
                capset.add(text)
                captions[pid] = capset

    # Get the services if requested.
    services = dict()
    if options.services:
        try:
            for descriptor in s.get_services():
                try:
                    services[descriptor.ProcessId].add(descriptor.ServiceName)
                except KeyError:
                    srvset = set()
                    srvset.add(descriptor.ServiceName)
                    services[descriptor.ProcessId] = srvset
        except WindowsError, e:
            print "Error getting the list of services: %s" % str(e)
            return
Exemple #46
0
 def __init__(self, api_hooks=None):
     System.request_debug_privileges()
     self.api_hooks = api_hooks
     self.hooks = []
     self.debugger = None
            if process.get_module_at_address(mbi.BaseAddress) is None:
                runtime_code = runtime_code_dict.setdefault(
                    "0x%x-0x%x" %
                    (mbi.BaseAddress, mbi.BaseAddress + mbi.RegionSize),
                    RuntimeCodeInfo(
                        mbi.BaseAddress, mbi.RegionSize,
                        process.read(mbi.BaseAddress, mbi.RegionSize)))
                runtime_code.add_process(
                    "%s" % (os.path.basename(process.get_filename())),
                    process.get_pid())


# RELEVANT_PROCSS_LIST = set(["outlook.exe","chrome.exe", "iexplore.exe", "firefox.exe", "AcroRd32.exe", "explorer.exe"])
RELEVANT_PROCSS_LIST = set(["chrome.exe", "iexplore.exe", "firefox.exe"])
# Now we can enumerate the running processes.
System.request_debug_privileges()


def scan_processes():
    runtime_code_dict = {}
    # Create a system snaphot.
    number_of_scanned_processes = 0
    system = System()
    for process in system:
        if process.get_filename() and os.path.basename(
                process.get_filename()).lower() in RELEVANT_PROCSS_LIST:
            try:
                scan_process_memory(process, runtime_code_dict)
                number_of_scanned_processes += 1
            except:
                pass
Exemple #48
0
def main():
    print "Process memory map"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) < 2 or '-h' in sys.argv or '--help' in sys.argv:
        script = os.path.basename(sys.argv[0])
        print "Usage:"
        print "  %s <pid>..." % script
        print "  %s <process.exe>..." % script
        return

    s = System()
    s.request_debug_privileges()
    s.scan_processes()

    targets = set()
    for token in sys.argv[1:]:
        try:
            pid = HexInput.integer(token)
            if not s.has_process(pid):
                print "Process not found: %s" % token
                return
            targets.add(pid)
        except ValueError:
            pl = s.find_processes_by_filename(token)
            if not pl:
                print "Process not found: %s" % token
                return
            for p, n in pl:
                pid = p.get_pid()
                targets.add(pid)

    targets = list(targets)
    targets.sort()

    for pid in targets:
        process = Process(pid)
        fileName = process.get_filename()
        memoryMap = process.get_memory_map()
        mappedFilenames = process.get_mapped_filenames()
        if fileName:
            print "Memory map for %d (%s):" % (pid, fileName)
        else:
            print "Memory map for %d:" % pid
        print
        ##        print CrashDump.dump_memory_map(memoryMap),
        print CrashDump.dump_memory_map(memoryMap, mappedFilenames)

        readable = 0
        writeable = 0
        executable = 0
        private = 0
        mapped = 0
        image = 0
        total = 0
        for mbi in memoryMap:
            size = mbi.RegionSize
            if not mbi.is_free():
                total += size
            if mbi.is_readable():
                readable += size
            if mbi.is_writeable():
                writeable += size
            if mbi.is_executable():
                executable += size
            if mbi.is_private():
                private += size
            if mbi.is_mapped():
                mapped += size
            if mbi.is_image():
                image += size
        width = len(number(total))
        print("  %%%ds bytes of readable memory" % width) % number(readable)
        print("  %%%ds bytes of writeable memory" % width) % number(writeable)
        print("  %%%ds bytes of executable memory" %
              width) % number(executable)
        print("  %%%ds bytes of private memory" % width) % number(private)
        print("  %%%ds bytes of mapped memory" % width) % number(mapped)
        print("  %%%ds bytes of image memory" % width) % number(image)
        print("  %%%ds bytes of total memory" % width) % number(total)
        print
Exemple #49
0
# POSSIBILITY OF SUCH DAMAGE.

from winappdbg import System, Table
from winappdbg.win32 import PROCESS_DEP_ENABLE, \
                            PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION, \
                            ERROR_ACCESS_DENIED

# Prepare the table.
header = ( " PID ", "DEP ", "DEP-ATL ", "Permanent ", "Filename " )
separator = [ " " * len(x) for x in header ]
table = Table()
table.addRow( *header )
table.addRow( *separator )

# Request debug privileges.
System.request_debug_privileges()

# Scan for running processes.
system = System()
try:
    system.scan_processes()
    #system.scan_process_filenames()
except WindowsError:
    system.scan_processes_fast()

# For each running process...
for process in system.iter_processes():
    try:

        # Get the process ID.
        pid = process.get_pid()
Exemple #50
0
def parse_cmdline(argv):
    # Help message and version string
    version = ("Process execution tracer\n"
               "by Mario Vilas (mvilas at gmail.com)\n"
               "%s\n") % winappdbg.version
    usage = (
        "\n"
        "\n"
        "  Create a new process (parameters for the target must be escaped):\n"
        "    %prog [options] -c <executable> [parameters for the target]\n"
        "    %prog [options] -w <executable> [parameters for the target]\n"
        "\n"
        "  Attach to a running process (by filename):\n"
        "    %prog [options] -a <executable>\n"
        "\n"
        "  Attach to a running process (by ID):\n"
        "    %prog [options] -a <process id>")
    ##    formatter = optparse.IndentedHelpFormatter()
    ##    formatter = optparse.TitledHelpFormatter()
    parser = optparse.OptionParser(
        usage=usage,
        version=version,
        ##                                    formatter=formatter,
    )

    # Commands
    commands = optparse.OptionGroup(parser, "Commands")
    commands.add_option("-a",
                        "--attach",
                        action="append",
                        type="string",
                        metavar="PROCESS",
                        help="Attach to a running process")
    commands.add_option("-w",
                        "--windowed",
                        action="callback",
                        type="string",
                        metavar="CMDLINE",
                        callback=callback_execute_target,
                        help="Create a new windowed process")
    commands.add_option("-c",
                        "--console",
                        action="callback",
                        type="string",
                        metavar="CMDLINE",
                        callback=callback_execute_target,
                        help="Create a new console process [default]")
    parser.add_option_group(commands)

    # Tracing options
    tracing = optparse.OptionGroup(parser, "Tracing options")
    tracing.add_option("--trace",
                       action="store_const",
                       const="trace",
                       dest="mode",
                       help="Set the single step mode [default]")
    if System.arch == win32.ARCH_I386:
        tracing.add_option(
            "--branch",
            action="store_const",
            const="branch",
            dest="mode",
            help=
            "Set the step-on-branch mode (doesn't work on virtual machines)")
        tracing.add_option("--syscall",
                           action="store_const",
                           const="syscall",
                           dest="mode",
                           help="Set the syscall trap mode")
    ##    tracing.add_options("--module", action="append", metavar="MODULES",
    ##                                                            dest="modules",
    ##                   help="only trace into these modules (comma-separated)")
    ##    debugging.add_option("--from-start", action="store_true",
    ##                  help="start tracing when the process is created [default]")
    ##    debugging.add_option("--from-entry", action="store_true",
    ##                  help="start tracing when the entry point is reached")
    parser.add_option_group(tracing)

    # Debugging options
    debugging = optparse.OptionGroup(parser, "Debugging options")
    debugging.add_option(
        "--autodetach",
        action="store_true",
        help="automatically detach from debugees on exit [default]")
    debugging.add_option(
        "--follow",
        action="store_true",
        help="automatically attach to child processes [default]")
    debugging.add_option("--trusted",
                         action="store_false",
                         dest="hostile",
                         help="treat debugees as trusted code [default]")
    debugging.add_option(
        "--dont-autodetach",
        action="store_false",
        dest="autodetach",
        help="don't automatically detach from debugees on exit")
    debugging.add_option("--dont-follow",
                         action="store_false",
                         dest="follow",
                         help="don't automatically attach to child processes")
    debugging.add_option("--hostile",
                         action="store_true",
                         help="treat debugees as hostile code")
    parser.add_option_group(debugging)

    # Defaults
    parser.set_defaults(
        autodetach=True,
        follow=True,
        hostile=False,
        windowed=list(),
        console=list(),
        attach=list(),
        ##        modules     = list(),
        mode="trace",
    )

    # Parse and validate the command line options
    if len(argv) == 1:
        argv = argv + ['--help']
    (options, args) = parser.parse_args(argv)
    args = args[1:]
    if not options.windowed and not options.console and not options.attach:
        if not args:
            parser.error("missing target application(s)")
        options.console = [args]
    else:
        if args:
            parser.error("don't know what to do with extra parameters: %s" %
                         args)

    # Get the list of attach targets
    system = System()
    system.request_debug_privileges()
    system.scan_processes()
    attach_targets = list()
    for token in options.attach:
        try:
            dwProcessId = HexInput.integer(token)
        except ValueError:
            dwProcessId = None
        if dwProcessId is not None:
            if not system.has_process(dwProcessId):
                parser.error("can't find process %d" % dwProcessId)
            try:
                process = Process(dwProcessId)
                process.open_handle()
                process.close_handle()
            except WindowsError as e:
                parser.error("can't open process %d: %s" % (dwProcessId, e))
            attach_targets.append(dwProcessId)
        else:
            matched = system.find_processes_by_filename(token)
            if not matched:
                parser.error("can't find process %s" % token)
            for process, name in matched:
                dwProcessId = process.get_pid()
                try:
                    process = Process(dwProcessId)
                    process.open_handle()
                    process.close_handle()
                except WindowsError as e:
                    parser.error("can't open process %d: %s" %
                                 (dwProcessId, e))
                attach_targets.append(process.get_pid())
    options.attach = attach_targets

    # Get the list of console programs to execute
    console_targets = list()
    for vector in options.console:
        if not vector:
            parser.error("bad use of --console")
        filename = vector[0]
        if not ntpath.exists(filename):
            try:
                filename = win32.SearchPath(None, filename, '.exe')[0]
            except WindowsError as e:
                parser.error("error searching for %s: %s" % (filename, str(e)))
            vector[0] = filename
        console_targets.append(vector)
    options.console = console_targets

    # Get the list of windowed programs to execute
    windowed_targets = list()
    for vector in options.windowed:
        if not vector:
            parser.error("bad use of --windowed")
        filename = vector[0]
        if not ntpath.exists(filename):
            try:
                filename = win32.SearchPath(None, filename, '.exe')[0]
            except WindowsError as e:
                parser.error("error searching for %s: %s" % (filename, str(e)))
            vector[0] = filename
        windowed_targets.append(vector)
    options.windowed = windowed_targets

    # If no targets were set at all, show an error message
    if not options.attach and not options.console and not options.windowed:
        parser.error("no targets found!")

    return options
Exemple #51
0
def main():
    print "Process memory map"
    print "by Mario Vilas (mvilas at gmail.com)"
    print

    if len(sys.argv) < 2 or "-h" in sys.argv or "--help" in sys.argv:
        script = os.path.basename(sys.argv[0])
        print "Usage:"
        print "  %s <pid>..." % script
        print "  %s <process.exe>..." % script
        return

    s = System()
    s.request_debug_privileges()
    s.scan_processes()

    targets = set()
    for token in sys.argv[1:]:
        try:
            pid = HexInput.integer(token)
            if not s.has_process(pid):
                print "Process not found: %s" % token
                return
            targets.add(pid)
        except ValueError:
            pl = s.find_processes_by_filename(token)
            if not pl:
                print "Process not found: %s" % token
                return
            for p, n in pl:
                pid = p.get_pid()
                targets.add(pid)

    targets = list(targets)
    targets.sort()

    for pid in targets:
        process = Process(pid)
        fileName = process.get_filename()
        memoryMap = process.get_memory_map()
        mappedFilenames = process.get_mapped_filenames()
        if fileName:
            print "Memory map for %d (%s):" % (pid, fileName)
        else:
            print "Memory map for %d:" % pid
        print
        ##        print CrashDump.dump_memory_map(memoryMap),
        print CrashDump.dump_memory_map(memoryMap, mappedFilenames)

        readable = 0
        writeable = 0
        executable = 0
        private = 0
        mapped = 0
        image = 0
        total = 0
        for mbi in memoryMap:
            size = mbi.RegionSize
            if not mbi.is_free():
                total += size
            if mbi.is_readable():
                readable += size
            if mbi.is_writeable():
                writeable += size
            if mbi.is_executable():
                executable += size
            if mbi.is_private():
                private += size
            if mbi.is_mapped():
                mapped += size
            if mbi.is_image():
                image += size
        width = len(number(total))
        print ("  %%%ds bytes of readable memory" % width) % number(readable)
        print ("  %%%ds bytes of writeable memory" % width) % number(writeable)
        print ("  %%%ds bytes of executable memory" % width) % number(executable)
        print ("  %%%ds bytes of private memory" % width) % number(private)
        print ("  %%%ds bytes of mapped memory" % width) % number(mapped)
        print ("  %%%ds bytes of image memory" % width) % number(image)
        print ("  %%%ds bytes of total memory" % width) % number(total)
        print