https://zhuanlan.zhihu.com/p/101401252
https://frida.re/docs/javascript-api/
frida调用的时候,一定要注意时机,这是最容易被忽略的一点,有时候,so还没有被加载,可是程序已经写好了,这个时候就会出现bug,所以加上判断和循环监听是最靠谱的
常见API setImmediate 是 JavaScript 中一个异步 API,它用于将指定的函数(在此例中为 Start_Hook)排入事件队列,并在当前执行栈清空后尽快执行。它类似于 setTimeout(fn, 0),但是有一个区别:setImmediate 确保在事件循环的当前阶段 之后尽早执行,而 setTimeout(fn, 0) 会将回调推迟到下一个事件循环的定时器阶段 。
这个异步API是指 :调用一个函数时,程序不会等待函数执行完成,而是继续执行后续操作。当函数执行完成时,会通过回调、事件等机制通知程序结果。
setTimeout 配合so没有被加载的情况使用,起到循环监听的效果
(function waitAndHook ( ) { var libName = "libabstr.so" ; var base = Module .findBaseAddress (libName); if (base) { }else { setTimeout (waitAndHook, 100 ); } })()
Java.perform(function () { … }) 也是顶层调用的一部分,但 Frida 会先等到 Java 虚拟机加载完毕后,再进入这个回调。
Java .perform (function ( ){ });
:确保代码在Java虚拟机的主线程中执行,这是Hook Java方法的前提条件。
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Java.use(className)</font>Java.use只能对已经注册到默认类加载器 PathClassLoader 或指定加载过的加载器中的类生效,如果你 要加载的类是动态加载的,会抛出ClassNotFoundException错误
var Secure = Java .use ("com.nctf.simplelogin.Secure" );Secure .checkRoot .implementation = function ( ) { return false ; };
获取对Java类的引用,用于修改其方法实现。
hexdump() 用于将内存中的数据按 16 进制形式打印出来,方便分析加密、base64表、key、数据结构等。
一般用于对于指针的话,就打印出来,效果如下
hexdump (ptrOrArrayBuffer, options)
{ offset : 0 , length : 64 , header : true , ansi : false }
示例
var data = Memory .readByteArray (ptr ("0x12345678" ), 64 );console .log (hexdump (data, { offset : 0 , length : 64 , header : true , ansi : true }));
Java枚举方法 var mai=Java .use ("com.example.test.MainActivity" );var clazz = mai.class ;var methods = clazz.getDeclaredMethods ();for (var i=0 ;i<methods.length ;i++){ var method = methods[i]; console .log (method.toString ()); }
Module.findExportByName(name, symbol) 用于获取某个模块中导出的符号地址(函数/变量),常用于 hook 系统函数如 dlopen、memcpy 等
var addr = Module .findExportByName ("libdl.so" , "dlopen" );
如果模块名是null,表示搜索所有已加载的模块
Module .findExportByName (null , "open" );
这里的Module。一定是Module,不能是Process.findModuleByName(”ca.so“)的实例
Module.getBaseAddress(name) / Module.findBaseAddress(name) 获取模块在内存中的加载基址,方便计算函数偏移地址。
var base = Module .findBaseAddress ("libtarget.so" );var func=base.add (0x222 );console .log ("libtarget.so base address: " + base);
new NativePointer 返回的是一个指针值,比如这个new NativePointer(mainlibaddr.add(0xB49D0)).readInt()
就是去读取这个指针上的值
Module.getModuleByName(name) 获取详细模块结构信息(base、size、path)
var module = Process .getModuleByName ("libtarget.so" );console .log (JSON .stringify (module ));
输出
{ "name" : "libtarget.so" , "base" : "0x7f6e300000" , "size" : 270336 , "path" : "/data/app/.../libtarget.so" }
Module.enumerateSymbols(name) 获取模块中所有符号(函数名、地址、类型),配合关键字匹配查找你想 hook 的函数。
var symbols = Module .enumerateSymbols ("libtarget.so" );symbols.forEach (function (sym ) { if (sym.name .indexOf ("base64" ) !== -1 ) { console .log (sym.name + " => " + sym.address ); } });
打印调用堆栈(Java) function printStack (tag ) { var Log = Java .use ('android.util.Log' ); var Exception = Java .use ('java.lang.Exception' ); var exception = Exception .$new(); var stack = Log .getStackTraceString (exception); console .log ('[' .concat (tag, '] Stack trace:' )); console .log (stack); exception.$dispose(); }
tag是标签而已
这样就可以看到调用情况
打印调用堆栈(native) function aaaa ( ) { var libapp = Module .findBaseAddress ("libapp.so" ); if ( libapp) { console .log ('libapp.base: ' , libapp); Interceptor .attach (libapp.add (0x28bea8 ), { onEnter : function (args ) { console .log ('magical_girl$EditView_MyEditTextState::check_28bea8' ); console .log (Thread .backtrace (this .context , Backtracer .ACCURATE ) .map (addr => addr.toString ()) .join ('\n' )); }, onLeave : function (ret ) { console .log ('ret check_28bea8' ); console .log (Thread .backtrace (this .context , Backtracer .ACCURATE ) .map (addr => addr.toString ()) .join ('\n' )); hexdump (ret); } }); }else { setTimeout (aaaa,100 ); } } aaaa ()
Interceptor.attach(addr, {…}) 用于 hook 任意函数,拦截其执行并可访问参数、返回值、寄存器。
onEnter)并不会在注入时被调用——它们只是被挂在目标函数上,只有在目标函数真正被调用时才会触发。
一旦你在顶层注册了 Interceptor.attach,它会持续生效,拦截所有后续的 strcmp 调用,直到你的脚本被卸载或目标进程退出。
Interceptor .attach (addr, { onEnter : function (args ) { console .log ("called with arg0: " + args[0 ]); this .arg0 = args[0 ]; }, onLeave : function (retval ) { console .log ("returned: " + retval); } });
访问寄存器: 在 ARM64 架构下, **w8**** 是 **x8** 的低 32 位。Frida 只提供 **x8** ,你应该这么写:!!**
Interceptor.attach(addr, { onEnter: function () { console.log("X0 register: " + this.context.x0); } });
打印符号信息 onEnter (log, args, state ) { var adw=Module .findBaseAddress ("libcreateso.so" ) var func=adw.add (0x00828 ); log (DebugSymbol .fromAddress (func).name ,'sub_828()' );
Frida 函数替换 Interceptor .replace (targetAddr, new NativeCallback (function ( ) { console .log ("Successfully" ); return 0 ; }, 'int' , []));
RPC远程调用 这个哥们写的案例不错
【frida逆向开发】frida-rpc远程调用某安app方法获取token_frida rpc-CSDN博客
其实frida的用途特别广泛,比如什么可以注入elf进行主动调用爆破等等。
这里涉及到主动调用,介绍一些RPC吧
Frida RPC ,全程是(Remote Procedure Call)
在frida 中,RPC是一种让你的JavaScript脚本,暴露出可以被外部(Python端)调用接口的方法
本来 Frida 的 JavaScript 脚本只能自己运行, 有了 RPC 后,Python 脚本可以主动调用你定义在 agent 里的方法 ,就像直接远程控制一样!
rpc.exports = { hello : function ( ) { console .log ("Hello from agent!" ); return "Hello done!" ; }, add : function (a, b ) { return a + b; } };
你定义了两个方法:hello 和 add
这些方法就会被自动暴露给外部(比如 Python端)使用
import fridasession = frida.get_usb_device().attach('目标进程名' ) with open ('agent.js' ) as f: script = session.create_script(f.read()) script.load() print (script.exports.hello())print (script.exports.add(3 , 4 ))
这种RPC就是方便爆破,批量调用的优点
、import frida def on_message (message, data ): if message['type' ] == 'send' : print (message['payload' ]) elif message['type' ] == 'error' : print (message['stack' ]) session = frida.get_usb_device().attach('com.roysue.roysueapplication' ) source = """ rpc.exports = { add: function (a, b) { return a + b; }, sub: function (a, b) { return new Promise(function (resolve) { setTimeout(function () { resolve(a - b); }, 100); }); } }; """ script = session.create_script(source) script.on('message' , on_message) script.load() print (script.exports.add(2 , 3 ))print (script.exports.sub(5 , 3 ))session.detach()
Process对象 Process.id Process.id返回附加目标进程的PID
Process.isDebuggerAttached() 检测当前是否对目标进程已经附加
Process.enumerateModules() 枚举当前已经加载的模块,返回模块对象的数组
function frida_Process ( ) { Java .perform (function ( ) { var process_Obj_Module_Arr = Process .enumerateModules (); for (var i = 0 ; i < process_Obj_Module_Arr.length ; i++) { console .log ("" ,process_Obj_Module_Arr[i].name ); } }); } setImmediate (frida_Process,0 );
Process.enumerateThreads() 枚举当前所有的线程
索引属性含义 1id线程id2state当前运行状态有 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">running, stopped, waiting, uninterruptible or halted</font>3context带有键 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">pc</font>和 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">sp</font>的对象,它们是分别为 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">ia32/x64/arm</font>指定 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">EIP/RIP/PC和ESP/RSP/SP</font>的 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">NativePointe</font>r对象。也可以使用其他处理器特定的密钥,例如 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">eax、rax、r0、x0</font>等。
function frida_Process ( ) { Java .perform (function ( ) { var enumerateThreads = Process .enumerateThreads (); for (var i = 0 ; i < enumerateThreads.length ; i++) { console .log ("" ); console .log ("id:" ,enumerateThreads[i].id ); console .log ("state:" ,enumerateThreads[i].state ); console .log ("context:" ,JSON .stringify (enumerateThreads[i].context )); } }); } setImmediate (frida_Process,0 );
Process.getCurrentThreadId() <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">Process.getCurrentThreadId()</font>:获取此线程的操作系统特定 <font style="color:rgb(25, 27, 31);background-color:rgb(248, 248, 250);">ID</font> 作为数字
findModuleByAddress 一般可能是获得了so中的函数或者线程地址,然后这个去解析得到module对象
Module对象
Module.load() 加载so文件,返回一个Module对象
function frida_Module ( ) { Java .perform (function ( ) { const hooks = Module .load ('libhello.so' ); console .log ("模块名称:" ,hooks.name ); console .log ("模块地址:" ,hooks.base ); console .log ("大小:" ,hooks.size ); console .log ("文件系统路径" ,hooks.path ); }); } setImmediate (frida_Module,0 );输出如下: 模块名称: libhello.so 模块地址: 0xdf2d3000 大小: 24576 文件系统路径 /data/app/com.roysue .roysueapplication -7adQZoYIyp5t3G5Ef5wevQ==/lib/ arm/libhello.so
enumerateImports() 会枚举模块中所有的import函数
function frida_Module ( ) { Java .perform (function ( ) { const hooks = Module .load ('libhello.so' ); var Imports = hooks.enumerateImports (); for (var i = 0 ; i < Imports .length ; i++) { console .log ("type:" ,Imports [i].type ); console .log ("name:" ,Imports [i].name ); console .log ("module:" ,Imports [i].module ); console .log ("address:" ,Imports [i].address ); } }); } setImmediate (frida_Module,0 );输出如下: [Google Pixel ::com.roysue .roysueapplication ]-> type : function name : __cxa_atexitmodule : /system/ lib/libc.so address : 0xf58f4521 type : function name : __cxa_finalizemodule : /system/ lib/libc.so address : 0xf58f462d type : function name : __stack_chk_failmodule : /system/ lib/libc.so address : 0xf58e2681 ...
enumerateExports() function frida_Module ( ) { Java .perform (function ( ) { const hooks = Module .load ('libhello.so' ); var Exports = hooks.enumerateExports (); for (var i = 0 ; i < Exports .length ; i++) { console .log ("type:" ,Exports [i].type ); console .log ("name:" ,Exports [i].name ); console .log ("address:" ,Exports [i].address ); } }); } setImmediate (frida_Module,0 );输出如下: [Google Pixel ::com.roysue .roysueapplication ]-> type : function name : Java _com_roysue_roysueapplication_hellojni_getSumaddress : 0xdf2d411b type : function name : unw_save_vfp_as_Xaddress : 0xdf2d4c43 type : function address : 0xdf2d4209 type : function ...
enumerateSymbols() 用来枚举一个模块的符号表
来枚举指定模块(比如 libc.so、libUE4.so)中导出的符号(函数名、变量名等)。
function frida_Module ( ) { Java .perform (function ( ) { const hooks = Module .load ('libc.so' ); var Symbol = hooks.enumerateSymbols (); for (var i = 0 ; i < Symbol .length ; i++) { console .log ("isGlobal:" ,Symbol [i].isGlobal ); console .log ("type:" ,Symbol [i].type ); console .log ("section:" ,JSON .stringify (Symbol [i].section )); console .log ("name:" ,Symbol [i].name ); console .log ("address:" ,Symbol [i].address ); } }); } setImmediate (frida_Module,0 );输出如下: isGlobal : true type : function section : {"id" :"13.text" ,"protection" :"r-x" }name : _Unwind_GetRegionStartaddress : 0xf591c798 isGlobal : true type : function section : {"id" :"13.text" ,"protection" :"r-x" }name : _Unwind_GetTextRelBaseaddress : 0xf591c7cc ...
Memory
var base = ptr (0x12340000 );var offset = 0x5678 ;var addr = base.add (offset);var value = Memory .readU32 (addr);console .log ("读取到的值是: " + value);console .log ("---------------------" );Interceptor .attach (Module .findExportByName (null , "some_function" ), { onEnter : function (args ) { var addr = args[0 ]; var value = Memory .readUtf8String (addr); console .log ("参数内容: " + value); } });
这个API就是去读对应地址指向的值
Frida Javascript api #Memory 与 #MemoryAccessMonitor (中文版)
太多了,用到再学吧
Memory.protect 修改保护属性,常跟nop一起用
function hook ( ) { var adr = Module .getBaseAddress ("libfrida0xb.so" ); var target =adr.add (0x15248 ); console .log ("function address:" , target); Memory .protect (adr, 0x1000 , "rwx" ); var writer = new Arm64Writer (target); try { writer.putNop (); writer.flush (); console .log ("Success!!" ); } finally { writer.dispose (); } } function main ( ) { Java .perform (function ( ) { hook (); }); } setImmediate (main);
字符串 Memory .protect (this .context .x0 , Process .pointerSize , 'rwx' ); var replace_str="" for (var i=0 ;i<s.length ;i++){ replace_str+="0" } this .context .x0 .writeUtf8String (replace_str);
内存读写监控 function hook_dex_dec_enter_in_main_elf ( ){ var module = Process .findModuleByName ("libjiagu_64.so" ); Interceptor .attach (module .base .add (0x1346B4 ), { onEnter : function (args ) { MemoryAccessMonitor .enable ( { base :this .context .x0 .add (0x8 ), size :40 },{ onAccess : function (details ) { console .log (details.operation ) console .log (get_addr_in_so (details.from )); } } ) }, onLeave : function (ret ) { } }); }