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 ),
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 copypasta(action, params, wait_state, doing_verb, done_verb): 'common code in a lot of methods here :)' try: target = params[0] # Do the requested action. status = System.get_service(target) try: name = System.get_service_display_name(target) except WindowsError: name = target print "%s service \"%s\"..." % (doing_verb, name) action(*params) # Wait for it to finish. timeout = 20 status = System.get_service(target) while status.CurrentState == wait_state: timeout -= 1 if timeout <= 0: print "Error: timed out." return time.sleep(0.5) status = System.get_service(target) # Done. print "Service %s successfully." % done_verb # On error show a message and quit. except WindowsError, e: print str(e) return
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)
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
def wait_for_service( service, wait_state, timeout = 20 ): descriptor = System.get_service( service ) while descriptor.CurrentState == wait_state: timeout -= 1 if timeout <= 0: raise RuntimeException( "Error: timed out." ) sleep( 0.5 ) descriptor = System.get_service( service )
def freeze_threads(pid): System.request_debug_privileges() process = Process(pid) #process.suspend() process.scan_threads() for thread in process.iter_threads(): thread.suspend()
def wait_for_service(service, wait_state, timeout=20): descriptor = System.get_service(service) while descriptor.CurrentState == wait_state: timeout -= 1 if timeout <= 0: raise RuntimeError("Error: timed out.") sleep(0.5) descriptor = System.get_service(service)
def main(): # Create a system snaphot. system = System() # Get the Desktop window. root = system.get_desktop_window() # Now show the window tree. show_window_tree(root)
def print_handle_caption(): system = System() for window in system.get_windows(): handle = HexDump.integer(window.get_handle()) caption = window.get_text() if not caption in None: print "%s\t%s" % (handle, caption)
def unfreeze_threads(pid): System.request_dubug_privileges() process = Process(pid) process.scan_thread() for thread in process.iter_threads(): thread.resume()
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 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
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 create_debugger(self): # Instance a debugger debug = Debug(self, bHostileCode = self.options.hostile) # Make sure the remote symbol store is set System.fix_symbol_store_path(remote = True, force = False) # Populate the snapshot of processes debug.system.scan() # Use this debugger self.start_using_debugger(debug)
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 create_debugger(self): # Instance a debugger debug = Debug(self, bHostileCode=self.options.hostile) # Make sure the remote symbol store is set System.fix_symbol_store_path(remote=True, force=False) # Populate the snapshot of processes debug.system.scan() # Use this debugger self.start_using_debugger(debug)
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))
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 simple_debugger(argv): with Debug(ScriptExecutionMonitorEventHandler(), bKillOnExit=False) as debug: if len(argv) == 0: attached = False logging.info("Try to attach to WINWORD.EXE...") while not attached: for process in System(): filename = process.get_filename() if filename and "WINWORD.EXE" in filename: logging.info("Attaching to: %s (%d)" % (filename, process.get_pid())) debug.attach(process.get_pid()) attached = True if attached: debug.loop() else: logging.error("Unabel to find a WINWORD.exe process") elif argv[0].isdigit(): # attach via PID pid = int(argv[0]) debug.attach(pid) logging.info("Attaching to: %d" % pid) debug.loop() else: logging.error("Usage: %s [PID]" % sys.argv[0])
def getpidexe(name): # get pid from process contain the name string system = System() for process in system: if process.get_filename() != None and name != None: if name.lower() in process.get_filename().lower(): return process.get_pid()
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 )
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 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
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
def service_list(): #services = System.get_services() services = System.get_active_services() for desc in services: print "%s : %s\t(%s)" % (desc.ServiceName, desc.DisplayName, service_type(desc.CurrentState))
def DebugProgram(filepath): #Instance a Debug object. debug_args = list() debug_args.insert(0,PROGRAM_PATH) debug_args.insert(len(debug_args),filepath) debug = Debug(AccessViolationHandlerWINAPPDBG, bKillOnExit = True) #debug.system.load_dbghelp("C:\\Program Files\\Debugging Tools for Windows (x86)\\dbghelp.dll") System.fix_symbol_store_path(symbol_store_path = "C:\\ProgramData\\Dbg\\sym",remote = True,force = True) #enter local symbol path here if you have downloaded symbols System.set_kill_on_exit_mode(True) try: # The execution time limit is 5 seconds. maxTime = time() + 5 # Start a new process for debugging. debug.execv(debug_args) # Wait for the debugee to finish. #debug.loop() # Loop while calc.exe is alive and the time limit wasn't reached. while debug and time() < maxTime: try: # Get the next debug event. debug.wait(1000) # 1 second accuracy # Show the current time on screen. #print time() # If wait() times out just try again. # On any other error stop debugging. except WindowsError, e: if e.winerror in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT): continue raise # Dispatch the event and continue execution. try: debug.dispatch() finally: debug.cont() # Stop the debugger. finally: debug.stop()
def run(self, target_file, save_path=None): """ Run the executable with the provided file, optionally saving all OLEv1 parts that are encountered. """ # TODO: Ensure target_file is readable opts = [self.executable, target_file] handler = CustomEventHandler(self._log) handler.save_path = save_path with Debug(handler, bKillOnExit=True) as debug: # Ensure the target application dies if the debugger is killed System.set_kill_on_exit_mode(True) max_time = time() + self.timeout try: debug.execv(opts) except WindowsError: self._log.error("Could not run Office application, check it is 32-bit") try: while debug.get_debugee_count() > 0 and time() < max_time: try: # Get the next debug event. debug.wait(1000) except WindowsError, exc: if exc.winerror in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT): continue raise # Dispatch the event and continue execution. try: debug.dispatch() finally: debug.cont() finally: debug.stop() return handler.objects
def test_windbg_version(): from winappdbg import System, win32 dbghelp = System.load_dbghelp() pathname = win32.GetModuleFileNameEx(-1, dbghelp._handle) sysroot = os.getenv("SystemRoot") system = os.path.join(sysroot, "System32") syswow = os.path.join(sysroot, "SysWoW64") if (pathname.lower().startswith(system.lower()) or pathname.lower().startswith(syswow.lower())): raise RuntimeError("WinDbg not found")
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 test_windbg_version(): from winappdbg import System, win32 dbghelp = System.load_dbghelp() pathname = win32.GetModuleFileNameEx(-1, dbghelp._handle) sysroot = os.getenv("SystemRoot") system = os.path.join(sysroot, "System32") syswow = os.path.join(sysroot, "SysWoW64") if pathname.lower().startswith(system.lower()) or pathname.lower().startswith(syswow.lower()): raise RuntimeError("WinDbg not found")
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 sys.exit(0) # 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 queue_initial_commands(self): # Queue the attach commands, if needed if self.options.attach: cmd = 'attach %s' % self.join_tokens(self.options.attach) self.cmdqueue.append(cmd) # Queue the windowed commands, if needed for argv in self.options.windowed: cmdline = System.argv_to_cmdline(argv) self.cmdqueue.append( 'windowed %s' % cmdline ) # Queue the console commands, if needed for argv in self.options.console: cmdline = System.argv_to_cmdline(argv) self.cmdqueue.append( 'console %s' % cmdline ) # Queue the continue command, if other commands were queued before if len(self.cmdqueue) > 0: self.cmdqueue.append('continue')
def queue_initial_commands(self): # Queue the attach commands, if needed if self.options.attach: cmd = 'attach %s' % self.join_tokens(self.options.attach) self.cmdqueue.append(cmd) # Queue the windowed commands, if needed for argv in self.options.windowed: cmdline = System.argv_to_cmdline(argv) self.cmdqueue.append('windowed %s' % cmdline) # Queue the console commands, if needed for argv in self.options.console: cmdline = System.argv_to_cmdline(argv) self.cmdqueue.append('console %s' % cmdline) # Queue the continue command, if other commands were queued before if len(self.cmdqueue) > 0: self.cmdqueue.append('continue')
def find_window(): # If two arguments are given, the first is the classname # and the second is the caption text. if len(sys.argv) > 2: classname = sys.argv[1] caption = sys.argv[2] if not classname: classname = None if not caption: caption = None window = System.find_window(classname, caption) # If only one argument is given, try the caption text, then the classname. else: try: window = System.find_window(windowName=sys.argv[1]) except WindowsError: window = System.find_window(className=sys.argv[1]) return window
def find_window(): # If two arguments are given, the first is the classname # and the second is the caption text. if len(sys.argv) > 2: classname = sys.argv[1] caption = sys.argv[2] if not classname: classname = None if not caption: caption = None window = System.find_window( classname, caption ) # If only one argument is given, try the caption text, then the classname. else: try: window = System.find_window( windowName = sys.argv[1] ) except WindowsError: window = System.find_window( className = sys.argv[1] ) return window
def getuserps_id(): # return all process under user/user process # only return pids system = System() userps = [] for process in system: try: if getwinuser() in getuname(process.get_pid()): userps.append((str(process.get_pid()))) except: pass return userps
def unfreeze_thread( 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.resume() print tid, " resume()" else: if len(tmp)>1: for s in tmp: if tid == int(s): print tid, " resume()" thread.resume()
def get_pid_by_name(name): system = System() for process in system: exe_path = process.get_image_name() if exe_path == None: continue procname = os.path.basename(exe_path) if procname == name: return process.get_pid() raise Exception("No Process named %(name)s is found" % locals())
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))
def getuserps(): # return all process under user/user process # return pids and process names system = System() userps = [] for process in system: try: if getwinuser() in getuname(process.get_pid()): userps.append((process.get_pid(), process.get_filename())) except: pass return userps
def get_processes_list(): """Take a snapshot and return the list of processes""" if sys.platform == 'win32': # (based on winappdbg examples) # Create a system snaphot system = System() # The snapshot is initially empty, so populate it system.scan_processes() process_ids = list(system.iter_process_ids()) # winappdbg does not include our pid, add it manually process_ids.append(get_current_process_id()) process_ids.sort() # Return the processes in the system snapshot (iterator) return (WinProcess(pid) for pid in process_ids) else: pids = psi.process.ProcessTable() return (LinuxProcess(pid) for pid in pids)
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()
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 ),
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()
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 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 test_windbg_version(): from winappdbg import System, win32 with warnings.catch_warnings(): warnings.simplefilter("ignore") dbghelp = System.load_dbghelp() if dbghelp is None: raise RuntimeError("WinDbg not found") pathname = win32.GetModuleFileNameEx(-1, dbghelp._handle) sysroot = os.getenv("SystemRoot") if not sysroot: sysroot = os.getenv("SYSTEMROOT") system = ntpath.join(sysroot, "System32") syswow = ntpath.join(sysroot, "SysWoW64") if (pathname.lower().startswith(system.lower()) or pathname.lower().startswith(syswow.lower()) ): raise RuntimeError("Microsoft SDK not found")
def restart_service( service ): try: # Get the display name. try: display_name = System.get_service_display_name( service ) except WindowsError: display_name = service # Get the service descriptor. descriptor = System.get_service( service ) # Is the service running? if descriptor.CurrentState != win32.SERVICE_STOPPED: # Tell the service to stop. print "Stopping service \"%s\"..." % display_name System.stop_service( service ) # Wait for the service to stop. wait_for_service( service, win32.SERVICE_STOP_PENDING ) print "Service stopped successfully." # Tell the service to start. print "Starting service \"%s\"..." % display_name System.start_service( service ) # Wait for the service to start. wait_for_service( service, win32.SERVICE_START_PENDING ) print "Service started successfully." # Show the new process ID. # This feature requires Windows XP and above. descriptor = System.get_service( service ) try: print "New process ID is: %d" % descriptor.ProcessId except AttributeError: pass # On error, show an error message. except WindowsError, e: if e.winerror == win32.ERROR_ACCESS_DENIED: print "Access denied! Is this an UAC elevated prompt?" else: print str(e)
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 show_services(): # Get the list of services. services = System.get_services() # You could get only the running services instead. # services = System.get_active_services() # For each service descriptor... for descriptor in services: # Print the service information, the easy way. # print str(descriptor) # You can also do it the hard way, accessing its members. print "Service name: %s" % descriptor.ServiceName print "Display name: %s" % descriptor.DisplayName if descriptor.ServiceType & win32.SERVICE_INTERACTIVE_PROCESS: print "Service type: Win32 GUI" elif descriptor.ServiceType & win32.SERVICE_WIN32: print "Service type: Win32" elif descriptor.ServiceType & win32.SERVICE_DRIVER: print "Service type: Driver" if descriptor.CurrentState == win32.SERVICE_CONTINUE_PENDING: print "Current status: RESTARTING..." elif descriptor.CurrentState == win32.SERVICE_PAUSE_PENDING: print "Current status: PAUSING..." elif descriptor.CurrentState == win32.SERVICE_PAUSED: print "Current status: PAUSED" elif descriptor.CurrentState == win32.SERVICE_RUNNING: print "Current status: RUNNING" elif descriptor.CurrentState == win32.SERVICE_START_PENDING: print "Current status: STARTING..." elif descriptor.CurrentState == win32.SERVICE_STOP_PENDING: print "Current status: STOPPING..." elif descriptor.CurrentState == win32.SERVICE_STOPPED: print "Current status: STOPPED" print
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 getPidByImg(img): system = System() system.scan_processes() for ( process, name ) in system.find_processes_by_filename( img ): return process.get_pid() return 0