def spawn_app(process): print('Spawning %s app.' % process) pid = frida.spawn(shutil.which(process)) frida.resume(pid) time.sleep(5) print('Spawned.') return 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 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 __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 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 start_persistence_process(self): ''' TODO implement stdout sink ''' self.pid = frida.spawn(self.args) self.session = frida.attach(self.pid) self._load_client_scripts() self.resume()
def __start_process(self, tmout): self.pid = frida.spawn(self.args) self.session = frida.attach(self.pid) self._load_inp_cli() self._load_executor_cli() self.bcov.load(self.session) self.resume() self.exec_one = self.__exec_one return self.__exec_one(tmout)
def run(self): while len(self._procstack) > 0: name = self._procstack.pop() print("[*] Attaching to: " + name) pid = frida.spawn([name]) session = frida.attach(pid) session.on('detached', self.on_detached) script = session.create_script(code) script.on('message', lambda m, d: self.on_message(m, d)) script.load() frida.resume(pid) with self._lock: self._cond.wait() frida.shutdown()
def spawn(cmd, tgt_addr, code): global script, pid_bytes pid = frida.spawn(cmd) session = frida.attach(pid) script = session.create_script(code) script.load() script.exports.setupshm(shm_id) script.exports.settarget(tgt_addr, MAX_LEN) pid_bytes = struct.pack("I", pid) return pid
def start_process(self, cmd, args): print("FridaAgent start_process called!") #cmd = "C:\\Users\\A0502571\\AppData\\Local\\Programs\\Python\\Python37-32\\python.exe" # using sysnative to force x64 process #args = [ cmd, "C:\\Users\A0502571\\Desktop\\private\\2019.07.15\\friTCP\\Cataclysm_Version\\friTCP\\ikeeby_socket_test\\client.py" ] cmd_args = [cmd, args] int_pid = frida.spawn(cmd_args) pid = str(int_pid) self.session_list[pid] = frida.attach(int_pid) self.script_list[pid] = {} self.inject_script(pid) frida.resume(int_pid) return pid
def eval_script(self, target_script, debug=False, enable_shell=False, disable_dns=False, disable_send=False, disable_com=False): # create the command args cmd = [self.wsh_host, target_script] # spawn the process pid = frida.spawn(cmd) session = frida.attach(pid) # attach to the session with open("wsh_hooker.js") as fp: script_js = fp.read() self.script = session.create_script(script_js, name="wsh_hooker.js") self.script.on('message', self.on_message) self.script.load() # Set Script variables print ' [*] Setting Script Vars...' self.script.post({"type": "set_script_vars", "debug": 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) # Keep process open raw_input(" [!] Running Script. Ctrl+Z to detach from instrumented program.\n\n") # print("[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n") # sys.stdin.read() # Kill it with fire frida.kill(pid)
def main(): args = init_args() resume_proc = not args.pid if args.find_proc: pid = device.get_process(default_proc_name).pid resume_proc = False else: pid = args.pid or frida.spawn([args.exe, "-w"], cwd=default_exe_path) session = frida.attach(int(pid)) session.enable_debugger() with open("main.js", "r") as f: script = session.create_script(f.read()) script.on("message", on_message) script.load() if resume_proc: frida.resume(pid) while True: cmd = sys.stdin.read() if cmd: handle_cmd(cmd.rstrip(), script)
def spawn_binary(self): if not self.pid: if self.binary[:2] == './': self.binary = self.binary[2:] self.pid = frida.spawn(self.binary) self.debug("Spawned binay {} with pid {}".format( self.binary, self.pid)) self.pid = int(self.pid) self.session = frida.attach(self.pid) self.debug("Attached to process {}".format(self.pid)) self.load_script() if self.error: self.warn("error") self.session.detach() self.info("An error occoured while attaching!") sys.exit(-1) self.log('Tracing binary press control-D to terminate....') sys.stdin.read() try: self.log('Detaching, this might take a second...') if self.kill: frida.kill(self.pid) self.log('Killing process {}'.format(self.pid)) self.session.detach() except frida.ProcessNotFoundError: self.log('Process already terminated') self.debug("Call Overview:") self.debug(str(self.calls)) with open(self.out_file, "w+") as self.out_file: result = dict() result["deviVersion"] = 0.1 result["calls"] = self.calls json.dump(result, self.out_file)
def main(proc): if checkIfProcessRunning(proc): print('[+] Process %s is running!' % proc) session = frida.attach(proc) else: print('[!] Process %s was not running!' % proc) print('[+] Running process %s!' % proc) session = frida.spawn(proc) session = frida.attach(proc) '''print(type(session))''' script = session.create_script(""" var Mutex_addr = Module.findExportByName("kernel32.dll", "CreateMutexA") console.log('[+] CreateMutex addr: ' + Mutex_addr); Interceptor.attach(Mutex_addr, { onEnter: function (args) { console.log("[+] Entering to createMutex") console.log('[+] lpName: ' + Memory.readUtf8String(args[2])); }, onLeave: function (retval) { } }); """) script.on('message', on_message) script.load() try: frida.resume(proc) except: pass sys.stdin.read()
def main(target_process): pid = frida.spawn([target_process]) session = frida.attach(pid) script_file = open("example.js", "r") script = session.create_script(script_file.read()) def on_message(message, data): new_data = call_erlamsa(data)[:11] print(str(data) + ' erlamsed to ' + str(new_data)) script.post(message = {'type': 'input'}, data = new_data) script.on('message', on_message) script.load() frida.resume(pid) print("[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n") sys.stdin.read() session.detach()
def fuzz(): global args, device, script, session, pid, sock, code, app_name, server_address, env import frida try: if args.U: device = frida.get_usb_device() if args.s: pid = device.spawn(args.t, env=env) session = device.attach(pid) else: session = device.attach(app_name) else: if args.s: pid = frida.spawn(args.t, stdio='pipe', env=env) session = frida.attach(pid) else: session = frida.attach(app_name) except Exception as e: print(e) os._exit(0) script = session.create_script(code, runtime='v8') script.on('message', on_message) script.load() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGALRM, signal_handler) establish_sock() try: script.exports.fuzzer() except (frida.core.RPCException, frida.InvalidOperationError) as e: print(e) os._exit(0)
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 __init__(self,cmd): self.pid=frida.spawn(cmd) self.session=frida.attach(self.pid)
import time import os def wait_polling(pid): try: while True: try: os.kill(pid, 0) #signal 0 does nothing except OSError: return time.sleep(1) except KeyboardInterrupt: exit(1337) with open("foo_compiled.js") as f: code = f.read() pid = frida.spawn(["./bin/foo"]) session = frida.attach(pid) session.enable_jit() script = session.create_script(code) script.load() frida.resume(pid) wait_polling(pid)
import sys import time import frida def on_message(message, data): print(message) pid = frida.spawn(['./test']) session = frida.attach(pid) js = r""" var cnt = 0; function copy_file(fd, path) { // FIXME: this step often fails var uis = new UnixInputStream(fd); // Only leave file name for absolute path var out_file_name = path.substr(path.lastIndexOf('/') + 1) + (cnt++).toString() + '.dump'; console.log('out_file_name: ', out_file_name); var out_file = new File(out_file_name, "wb"); // FIXME: we get nothing in out_file var buffer = uis.read(5); out_file.write(buffer); console.log('buffer: ', buffer); // while (buffer = uis.read(1024)) { // out_file.write(buffer);
import frida import sys # Create and suspend process pid = frida.spawn('crackme0x02') # Create a Frida session and attach to our process session = frida.attach(pid) # Create JavaScript to be injected into our process script = session.create_script(""" // Hook address instead of function Interceptor.attach(ptr('0x8048448'), { onEnter: function(args) { // Prints context as JSON, useful for debugging purposes //console.log(JSON.stringify(this.context)); // Read value of EAX from thread context var password = this.context.eax.toInt32(); // Send password to Python message handler send('Correct password is ' + password); send('Press Ctrl+D to detach from process'); }, }); // Hook main function which starts at 0x80483e4 Interceptor.attach(ptr('0x80483e4'), { onEnter: function(args) { // For some reason. args don't contain any values.
if shm_str: shm_id = int(shm_str) #shm = multiprocessing.shared_memory.SharedMemory(shm_id) ptr = shmat(shm_id, 0, 0) shm = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_byte)) else: ba = bytearray(b"\x00" * MAP_SIZE) shm = memoryview(ba) os.write(FORKSRV_FD + 1, b"\x00"*4) payload = b"0000" tgt_addr = 0x0000000000401156 pid = frida.spawn(["./test"]) session = frida.attach(pid) script = session.create_script(code) script.load() script.exports.settarget(tgt_addr) fake_pid = b"\x66\x00\x00\x00" while True: if len(os.read(FORKSRV_FD, 4)) != 4: os.exit(2) if os.write(FORKSRV_FD + 1, fake_pid) != 4: os.exit(5)
#!/usr/bin/env python2 import frida import sys import time pid = frida.spawn("./be-quick-or-be-dead-3") print("pid =", pid) session = frida.attach(pid) # Replace the "calculate_key()" function with a function that directly # returns calc(0x11965). script = session.create_script(""" 'use strict'; Interceptor.replace(ptr('0x400792'), new NativeCallback(function(n) { return 0x9e22c98e; },'int64', ['int64'])); """) def on_message(message, data): print(message) script.on('message', on_message) done = False def on_detached_with_reason(reason):
import frida with open('./main.js', 'r', encoding='utf8') as f: code = f.read() pid = frida.spawn('./Newbie_calculations.exe') session = frida.attach(pid) script = session.create_script(code) script.load() frida.resume(pid)
def main(target_process): pid = frida.spawn([target_process]) session = frida.attach(pid) script = session.create_script(""" var seekoffset=0; var seeklength=0; var processname=""; var op = recv('param', function(value) { var v = value.payload.split(","); processname = v[0]; run(); }); function run() { var proc=Module.findBaseAddress(processname); var base=Process.findRangeByAddress(proc); var fileptr=Module.findExportByName("kernel32","SetFilePointer"); var readfileptr=Module.findExportByName("kernel32","ReadFile"); /*Memory.scan(base.base, 0x100000, "55????5D????FFFFFFE9", { onMatch: function(address,size) { console.log("Found MAlloc: "+ptr(address).toString(16)); Interceptor.attach(ptr(address), { // When function is called, print out its parameters onEnter: function (args) { console.log("Entered at :"+address.toString(16)) this.length=args[0].toInt32(); if (args[0]<0x16000) { var subsize=args[0] Interceptor.attach(readfileptr, { onEnter: function (args) { console.log(''); console.log('[+] ReadFileLength: ' + args[2]); if (args[2].toString(16)==subsize.toString(16)) { console.log('[+] Subsize: ' + subsize); args[2]=ptr(seeklength); console.log('[+] New ReadFileLength: ' + args[2]); } } }); args[0]=ptr(seeklength); console.log('[+] New DLength: ' + args[0]); } }, onLeave: function (retval) { } }); }, onComplete: function() { } });*/ Memory.scan(base.base, 0x100000, "D1B5E39E", { onMatch: function(address,size) { var z=0; for (z=address-50;z<address;z++) { var h=Memory.readU8(ptr(z)); if (h==0x55) { console.log("Detected AES: "+ptr(z).toString(16)); Interceptor.attach(ptr(z), { // Intercept calls to our SetAesDecrypt function // When function is called, print out its parameters onEnter: function (args) { console.log(''); console.log('[+] AES-Length: ' + args[0]); console.log('[+] AES-EDX: ' + Memory.readU32(this.context.edx).toString(16)); // Plaintext this.length=args[0].toInt32(); this.xx=this.context.edx; }, // When function is finished onLeave: function (retval) { dumpAddr('Data', this.xx, 16); // Print out data array, which will contain de/encrypted data as output var dt=Memory.readByteArray(this.xx,this.length); send('Output',dt); console.log("Writing data."); } }); break; } } }, onComplete: function() { } }); /*Interceptor.attach(fileptr, { onEnter: function (args) { console.log(''); if (args[1]>0x0 && args[1]<0xFFFF0000) { console.log('[+] Seek: ' + args[1]); args[1]=ptr(seekoffset); } }, // When function is finished onLeave: function (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 })); } """) script.on('message', on_message) script.load() script.post({'type': 'param', 'payload': str(target_process)}) frida.resume(pid) print( "[!] Ctrl+C on Windows/cmd.exe to detach from instrumented program.\n\n" ) sys.stdin.read() session.detach()
def main(): DESCR = """Frida Fuzzer All In One [%s] base on frida-fuzzer """ % __version__ opt = argparse.ArgumentParser( description=DESCR, formatter_class=argparse.RawTextHelpFormatter) opt.add_argument("-i", action="store", help="Folder with initial seeds") opt.add_argument("-o", action="store", help="Output folder with intermediate seeds and crashes") opt.add_argument("-U", action="store_true", help="Connect to USB") opt.add_argument("-debug", action="store_true", help="Enable javascript debugger") opt.add_argument( "-N", action="store", help= "Connect to Network (e.g.: 192.168.111.34:27042, frida-server -l 192.168.111.34:27042)" ) opt.add_argument("-spawn", action="store_true", help="Spawn instead of attach") opt.add_argument("-script", action="store", default="fuzzer-agent.js", help="Script filename (default is fuzzer-agent.js)") opt.add_argument("-runtime", action="store", default="v8", help="Runtime for javascript (default is v8)") opt.add_argument('target', nargs=argparse.REMAINDER, help="Target program/pid (and arguments if spwaning)") args = opt.parse_args() if len(args.target) == 0: print(" >> Target not specified!") exit(1) if args.o is None: output_folder = tempfile.mkdtemp(prefix="frida_fuzz_out_") print(" >> Temporary output folder :", output_folder) else: output_folder = args.o if os.path.exists(output_folder): print(" >> %s already exists!" % output_folder) shutil.rmtree(output_folder) os.mkdir(output_folder) if args.i and not os.path.exists(args.i): print(" >> args.in doesn't exists!") exit(1) if args.script and not os.path.exists(args.script): print(" >> args.script doesn't exists!") exit(1) app_name = args.target[0] try: app_name = int(app_name) pid = app_name except: pass # not a PID with open(args.script) as f: code = f.read() if args.U: # for usb channel device = frida.get_usb_device() if args.spawn: pid = device.spawn(args.target) session = device.attach(pid) else: session = device.attach(app_name) elif args.N: device = frida.get_device_manager().add_remote_device(args.N) if args.spawn: pid = device.spawn(args.target) session = device.attach(pid) else: session = device.attach(app_name) else: if args.spawn: if os.getenv("FRIDA_FUZZER_CHILD_OUT"): pid = frida.spawn(args.target) else: pid = frida.spawn(args.target, stdio="pipe") session = frida.attach(pid) else: session = frida.attach(app_name) def signal_handler(sig, frame): print(" >> Exiting...") if args.spawn and not args.U and not args.N: print(" >> Killing", pid) os.kill(pid, signal.SIGKILL) try: script.unload() session.detach() except: pass os._exit(0) signal.signal(signal.SIGINT, signal_handler) #https://bbs.pediy.com/thread-254695.htm if args.debug: session.enable_debugger() script = session.create_script(code, runtime=args.runtime) script.on('message', on_message) script.load() script.exports.interceptortarget() import sys sys.stdin.read() script.exports.allocmutatormemory(4096) payload = "test!" mutator_hex = script.exports.mutatorbypayload(payload.encode().hex()) #mutator_hex = script.exports.execute(b'cat jswrite | ./radamsa'.hex(), b'r'.hex()) print(mutator_hex)
def __init__(self, cmd, out_file="dump.bin"): self.pid = frida.spawn(cmd) self.session = frida.attach(self.pid) self.dump = {} self.out_file = out_file self.raw = False
import sys import frida t = ''' function initStalker() { Stalker.trustThreshold = 0; var t = Process.enumerateThreads()[0] Stalker.follow(t.id, { transform: function(iterator) { var lolol = new NativePointer(123) while (iterator.next() != null) iterator.keep(); } }) } initStalker() ''' pid = frida.spawn([r'bin32\Release\test_bin.exe']) session = frida.attach(pid) script = session.create_script(t) script.load() input('>') frida.resume(pid) sys.stdin.read()
#!/usr/bin/python3 import frida import sys import json def on_message(message, data): if (message['type'] == 'send'): print(message['payload']) def on_detached(): sys.exit(0) pid = frida.spawn(['ba321ad38f1d52cc0a8b94807fda8ff7.exe']) session = frida.attach(pid) script = session.create_script(""" var funcStart=new NativePointer('0x01204B4'); var funcEnd=new NativePointer('0x0123DA4'); function varToStr(ptr) { var type=ptr.add(0x0c).readU32(); if(type==1) return ptr.readU32().toString(); if(type==2) return ptr.readU64().toString(); if(type==3) return ptr.readDouble().toString();
def spawn_and_hook(program, port=8080, filter="true"): pid = frida.spawn(program) hook(pid, port, filter) frida.resume(pid)