首页
论坛
课程
招聘
[原创]使用Frida分析动态注册jni函数绑定流程
2020-11-3 09:42 7498

[原创]使用Frida分析动态注册jni函数绑定流程

2020-11-3 09:42
7498

前言

这是3W班7月份的练习题第一题。题目要求是分析总结动态注册jni函数时的流程,并编写frida脚本,达到能够跟踪测试apk中动态注册的jni函数的绑定流程的目标。

 

通过查看源码,使用Frida验证了部分绑定流程。加深了对之前使用的hook RegisterNative脚本原理的理解。

解题过程

按照hanbing老师的讲解,native函数有2次绑定。这里分别查看绑定

第一次绑定

Jni注册Demo

自己写Demo方便测试

1
2
3
4
public native String stringFromJNI();
public native String stringFromJNI2();
public native void RegisterFunc();
public native void Func();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
extern "C" JNIEXPORT jstring JNICALL
Java_com_cwuzao_nativedemo_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
 
extern "C" JNIEXPORT jstring JNICALL
Java_com_cwuzao_nativedemo_MainActivity_stringFromJNI2(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++2";
    return env->NewStringUTF(hello.c_str());
}
 
void F(JNIEnv *env, jobject thiz) {
    __android_log_print(4, "nativedemo", "Call Func");
}
 
__attribute__ ((visibility ("hidden"))) void RF(JNIEnv *env, jobject thiz) {
    //注册另外一个函数
    __android_log_print(4, "nativedemo", "Call RegisterFunc New");
 
    JNINativeMethod jniNativeMethod[] = {{"Func","()V", (void *) F}};
    jclass MainActivityjclass = env->FindClass("com/cwuzao/nativedemo/MainActivity");
    env->RegisterNatives(MainActivityjclass, jniNativeMethod,
                         sizeof(jniNativeMethod) / sizeof(JNINativeMethod));
}
 
JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env = nullptr;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) == JNI_OK) {
        __android_log_print(4, "nativedemo", "jni->%s",
                            "vm->GetEnv((void**)&env,JNI_VERSION_1_6) success");
    }
    JNINativeMethod jniNativeMethod[] = {{"RegisterFunc","()V", (void *) RF}};
    jclass MainActivityjclass = env->FindClass("com/cwuzao/nativedemo/MainActivity");
    env->RegisterNatives(MainActivityjclass, jniNativeMethod,sizeof(jniNativeMethod) / sizeof(JNINativeMethod));
 
    return JNI_VERSION_1_6;
}

初始化ArtMethod的安卓源码

从ClassLinker::DefineClass->ClassLinker::LoadClass->ClassLinker::LoadClassMembers进入到ArtMethod的初始化。

1
2
3
4
5
6
7
void ClassLinker::LoadClassMembers() {
 
for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
      ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
      LoadMethod(dex_file, it, klass, method);
      LinkCode(this, method, oat_class_ptr, class_def_method_index);
    }

这里就是主要看LinkCode方法中的method->IsNative()条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
if (method->IsNative()) {
  // Unregistering restores the dlsym lookup stub.
  method->UnregisterNative();
}
 
void ArtMethod::UnregisterNative() {
  CHECK(IsNative() && !IsFastNative()) << PrettyMethod();
  // restore stub to lookup native pointer via dlsym
  SetEntryPointFromJni(GetJniDlsymLookupStub());
}
 
extern "C" void* art_jni_dlsym_lookup_stub(JNIEnv*, jobject);
static inline const void* GetJniDlsymLookupStub() {
  return reinterpret_cast<const void*>(art_jni_dlsym_lookup_stub);
}
 
ENTRY art_jni_dlsym_lookup_stub
  // spill regs.
  ...
  bl  artFindNativeMethod
  ...
END art_jni_dlsym_lookup_stub
 
extern "C" const void* artFindNativeMethod() {
  ArtMethod* method = self->GetCurrentMethod(nullptr);
  void* native_code = soa.Vm()->FindCodeForNativeMethod(method);
  return method->RegisterNative(native_code, false);
}
 
// namespace art

根据上面代码HOOK分析

静态和动态注册的方法都会先进行UnregisterNative();第一次绑定art_jni_dlsym_lookup_stub,最后还是通过RegisterNative注册。

 

这里就可以先HOOK artFindNativeMethod查看返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var addr_ArtMethod_UnRegisterNative = libart.findExportByName("_ZN3art9ArtMethod16UnregisterNativeEv");
Interceptor.attach(addr_ArtMethod_UnRegisterNative, {
    onEnter: function(args){
        allocPrettyMethod.writeByteArray(allocPrettyMethodInit);
        PrettyMethod(addr_ArtMethod_PrettyMethod, args[0], allocPrettyMethod, 0x100);
        console.log("addr_ArtMethod_UnRegisterNative onEnter:",allocPrettyMethod.readCString());
    },
    onLeave: function(retval){
    }
});
 
var addr_artFindNativeMethod = libart.findExportByName("artFindNativeMethod");
Interceptor.attach(addr_artFindNativeMethod, {
    onEnter: function(args){
    },
    onLeave: function(retval){
        console.log("addr_artFindNativeMethod onLeave:", retval);
    }
});
var addr_FindCodeForNativeMethod = libart.findExportByName("_ZN3art9JavaVMExt23FindCodeForNativeMethodEPNS_9ArtMethodE");
Interceptor.attach(addr_FindCodeForNativeMethod, {
    onEnter: function(args){
        allocPrettyMethod.writeByteArray(allocPrettyMethodInit);
        PrettyMethod(addr_ArtMethod_PrettyMethod, args[1], allocPrettyMethod, 0x100);
        console.log("addr_FindCodeForNativeMethod onEnter:",allocPrettyMethod.readCString() );
    },
    onLeave: function(retval){
    }
});
1
2
3
4
5
dlopen: libart.so
libart-> [object Object]
addr_FindCodeForNativeMethod onEnter: java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI()
addr_FindSymbol: Java_com_cwuzao_nativedemo_MainActivity_stringFromJNI
addr_artFindNativeMethod onLeave: 0x7593752c0c

这里可以看到2个静态注册的stringFromJNI调用了绑定,但是stringFromJNI2没有绑定,因为程序中并没有调用stringFromJNI2,这里可以打印一下2个ArtMethod的差别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
addr_ArtMethod_UnRegisterNative onEnter: void com.cwuzao.nativedemo.MainActivity.Func()
addr_ArtMethod_UnRegisterNative onEnter: void com.cwuzao.nativedemo.MainActivity.RegisterFunc()
addr_ArtMethod_UnRegisterNative onEnter: void com.cwuzao.nativedemo.MainActivity.onCreate(android.os.Bundle)
addr_ArtMethod_UnRegisterNative onEnter: java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI()
addr_ArtMethod_UnRegisterNative onEnter: java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI2()
 
methodName-> public native java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI()
Func.getArtMethod->              0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF
75ae4c56c0  20 25 c8 12 01 01 00 08 00 00 00 00 b1 3b 00 00   %...........;..
75ae4c56d0  10 02 00 00 00 00 00 00 00 80 22 94 75 00 00 00  ..........".u...
75ae4c56e0  0c 2c 75 93 75 00 00 00 70 96 f1 ac 75 00 00 00  .,u.u...p...u...
 
methodName-> public native java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI2()
Func.getArtMethod->              0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF
75ae4c56f0  20 25 c8 12 01 01 00 08 00 00 00 00 b2 3b 00 00   %...........;..
75ae4c5700  11 02 00 00 00 00 00 00 00 80 22 94 75 00 00 00  ..........".u...
75ae4c5710  00 f5 f0 ac 75 00 00 00 70 96 f1 ac 75 00 00 00  ....u...p...u...
 
//调用一次stringFromJNI2
 
addr_FindCodeForNativeMethod onEnter: java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI2()
addr_FindSymbol: Java_com_cwuzao_nativedemo_MainActivity_stringFromJNI2
addr_artFindNativeMethod onLeave: 0x7593752d5c
 
methodName-> public native java.lang.String com.cwuzao.nativedemo.MainActivity.stringFromJNI2()
Func.getArtMethod->              0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF
75ae4c56f0  20 25 c8 12 01 01 00 08 00 00 00 00 b2 3b 00 00   %...........;..
75ae4c5700  11 02 00 00 00 00 00 00 00 80 22 94 75 00 00 00  ..........".u...
75ae4c5710  5c 2d 75 93 75 00 00 00 70 96 f1 ac 75 00 00 00  \-u.u...p...u...
 
//这ArtMethod在0x20处发生变化,打印调用前后stringFromJNI2 0x20的地址所在模块
 
[AOSP on msm8996::com.cwuzao.nativedemo]-> Process.findModuleByAddress(0x75acf0f500)
{
    "base": "0x75aca2d000",
    "name": "libart.so",
    "path": "/system/lib64/libart.so",
    "size": 6041600
}
[AOSP on msm8996::com.cwuzao.nativedemo]-> Process.findModuleByAddress(0x7593752d5c)
{
    "base": "0x7593744000",
    "name": "libnative-lib.so",
    "path": "/data/app/com.cwuzao.nativedemo-UgxLVJ25_JE-ydv0Rl_x2A==/lib/arm64/libnative-lib.so",
    "size": 212992
}
 
[AOSP on msm8996::com.cwuzao.nativedemo]-> console.log(hexdump(ptr(0x75acf0f500)))
             0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF
75acf0f500  fd 7b bf a9 fd 03 00 91 e6 1f bf 6d e4 17 bf 6d  .{.........m...m
75acf0f510  e2 0f bf 6d e0 07 bf 6d e6 1f bf a9 e4 17 bf a9  ...m...m........
75acf0f520  e2 0f bf a9 e0 07 bf a9 d7 01 ff 97 f1 03 00 aa  ................
75acf0f530  e0 07 c1 a8 e2 0f c1 a8 e4 17 c1 a8 e6 1f c1 a8  ................
75acf0f540  e0 07 c1 6c e2 0f c1 6c e4 17 c1 6c e6 1f c1 6c  ...l...l...l...l
75acf0f550  fd 7b c1 a8 51 00 00 b4 20 02 1f d6 c0 03 5f d6  .{..Q... ....._.
 
//0x75acf0f500这段hex可以转成arm汇编就是art_jni_dlsym_lookup_stub
 
//0x7593752d5c-0x7593744000就是stringFromJNI2的代码位置
 
addr_FindCodeForNativeMethod onEnter: void com.cwuzao.nativedemo.MainActivity.Func()
addr_FindSymbol: Java_com_cwuzao_nativedemo_MainActivity_Func
addr_FindSymbol: Java_com_cwuzao_nativedemo_MainActivity_Func__
addr_FindSymbol: Java_com_cwuzao_nativedemo_MainActivity_Func
addr_FindSymbol: Java_com_cwuzao_nativedemo_MainActivity_Func__
addr_artFindNativeMethod onLeave: 0x0
 
//运行到这里程序崩溃了

这里可以看出几点

  1. 静态注册和动态注册都会调用UnRegisterNative,并设置EntryPoint(0x20)为art_jni_dlsym_lookup_stub
  2. 静态注册首次调用时会运行art_jni_dlsym_lookup_stub,通过addr_FindSymbol查找符号并注册后真正运行jni方法
  3. 静态注册其实只是注册了art_jni_dlsym_lookup_stub,通过Java_xxx这种固定的函数名自动绑定,如果查找不到,则会程序崩溃,比如直接调用Func()

动态注册的第二次绑定

查看ArtMethod在绑定前后的差别

1
2
3
4
5
6
7
8
9
10
11
12
13
Java.perform(function(){
        var className = "com.cwuzao.nativedemo.MainActivity";
        var classResult = Java.use(className).class;
        var methodArr = classResult.getDeclaredMethods();
        for(var i=0;i<methodArr.length;i++){
            var methodName = methodArr[i].toString();
            console.log("methodName->",methodName);
            if(methodName.indexOf(".Func(") > -1 ){
                var artmethod = methodArr[i].getArtMethod();
                console.log("Func.getArtMethod->",hexdump(ptr(artmethod)));
            }
        }
    });
1
2
3
4
5
6
7
8
9
Func.getArtMethod->            0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF
9a9918e0  48 e6 93 9a 01 01 00 00 00 00 00 00 54 3b 00 00  H...........T;..
9a9918f0  13 02 00 00 00 00 00 00 00 80 b5 6d 7b 00 00 00  ...........m{...
9a991900  00 e0 23 70 00 00 00 00 40 44 b5 6d 7b 00 00 00  ..#p....@D.m{...
 
Func.getArtMethod->            0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF
9a9918e0  48 e6 93 9a 01 01 00 00 00 00 00 00 54 3b 00 00  H...........T;..
9a9918f0  13 02 00 00 00 00 00 00 00 80 b5 6d 7b 00 00 00  ...........m{...
9a991900  7c 44 99 6d 7b 00 00 00 40 44 b5 6d 7b 00 00 00  |D.m{...@D.m{...

和上方静态注册一样,也就是0x20处地址发生变化。从art模块的art_jni_dlsym_lookup_stub换成了自己so文件的地址,下面分析就是修改的流程。

跟踪RegisterNatives

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static jint RegisterNatives(JNIEnv* env, jclass java_class, const JNINativeMethod* methods, jint method_count) {
  return RegisterNativeMethods(env, java_class, methods, method_count, true);
}
 
static jint RegisterNativeMethods(JNIEnv* env, jclass java_class, const JNINativeMethod* methods,jint method_count, bool return_errors) {
   for (jint i = 0; i < method_count; ++i) {
      const void* fnPtr = methods[i].fnPtr;
      const void* final_function_ptr = m->RegisterNative(fnPtr, is_fast);
   }
}
 
const void* ArtMethod::RegisterNative(const void* native_method, bool is_fast) {
  Runtime::Current()->GetRuntimeCallbacks()->RegisterNativeMethod(this,
                                                                  native_method,
                                                                  /*out*/&new_native_method);
  SetEntryPointFromJni(new_native_method);
  return new_native_method;
}

这里和静态注册一样也是走到了SetEntryPointFromJni,查看具体流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void SetEntryPointFromJni(const void* entrypoint) {
  DCHECK(IsNative());
  SetEntryPointFromJniPtrSize(entrypoint, kRuntimePointerSize);
}
 
ALWAYS_INLINE void SetEntryPointFromJniPtrSize(const void* entrypoint, PointerSize pointer_size) {
  SetDataPtrSize(entrypoint, pointer_size);
}
 
ALWAYS_INLINE void SetDataPtrSize(const void* data, PointerSize pointer_size) {
  DCHECK(IsImagePointerSize(pointer_size));
  SetNativePointer(DataOffset(pointer_size), data, pointer_size);
}
 
...

涉及的方法还是比较多,大多数是ALWAYS_INLINE修饰,IDA查不到符号SetEntryPointFromJni,直接查看ArtMethod::RegisterNative末尾

1
2
3
4
5
6
7
8
9
10
11
12
13
14
v25 = (art::RuntimeCallbacks *)art::Runtime::GetRuntimeCallbacks(MEMORY[0]);
art::RuntimeCallbacks::RegisterNativeMethod(v25, v5, v7, &v27);
result = v27;
*((_QWORD *)v5 + 4) = v27;
*(_QWORD *)(v4 + 40);
return result;
 
//v27应该就是具体指针,但是这里比较奇怪就是+4,查看汇编
 
.text:00000000000DD1B4                 BL              _ZN3art16RuntimeCallbacks20RegisterNativeMethodEPNS_9ArtMethodEPKvPPv ; art::RuntimeCallbacks::RegisterNativeMethod(art::ArtMethod *,void const*,void **)
.text:00000000000DD1B8                 LDR             X0, [SP,#0x70+var_68]
.text:00000000000DD1BC                 STR             X0, [X19,#0x20]  //0x20和上面对应上
.text:00000000000DD1C0                 LDR             X8, [X23,#0x28]
.text:00000000000DD1C4                 LDR             X9, [SP,#0x70+var_48]

查看libart反编译源码发现这里其实就2步,0x20也和上面对应上了。

 

SetEntryPointFromJni(new_native_method),其实已经被优化成几句汇编了,主要就是STR X0, [X19,#0x20]

 

这里也就验证了之前ArtMethod+0x20是EntryPoint,也可以通过源码计算内存偏移

测试不通过RegisterNative设置ArtMethod+0x20值

1
2
3
4
5
6
7
8
9
10
11
12
if(methodName.indexOf(".Func()") > -1 ){
    var artmethod = methodArr[i].getArtMethod();
    console.log("Func.getArtMethod->",hexdump(ptr(artmethod)));
    //获取指针
    var libNative =  Process.findModuleByName("libnative-lib.so");
    var addr_F = libNative.base.add(0xf47c); //写死值,也可以查询符号表
    console.log("addr_F->", addr_F);
    //修改地址
    var result = ptr(artmethod).add(0x20).writePointer(addr_F);
    console.log("Func.getArtMethod update->",hexdump(ptr(artmethod)));
    break;
}

这样修改后的确可以调用,没有报错。

hook给定的测试APP

1
2
3
4
5
6
7
8
9
10
11
12
var addr_ArtMethod_RegisterNative = libart.findExportByName("_ZN3art9ArtMethod14RegisterNativeEPKvb");
Interceptor.attach(addr_ArtMethod_RegisterNative, {
    onEnter: function(args){
        this.arg0 = args[0]; //this
        allocPrettyMethod.writeByteArray(allocPrettyMethodInit);
        PrettyMethod(addr_ArtMethod_PrettyMethod, args[0], allocPrettyMethod, 0x100);
        console.log("ArtMethod_RegisterNative onEnter:",allocPrettyMethod.readCString(),this.arg0, args[1], args[2]);
    },
    onLeave: function(retval){
        // console.log("ArtMethod_RegisterNative onLeave:",this.arg0);
    }
});
1
2
3
4
5
6
7
8
9
10
ArtMethod_RegisterNative onEnter: java.lang.String com.jg.bh.BH.getCloundTag(android.content.Context) 0xe9d4def4 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: java.lang.String com.jg.bh.BH.getMsg(android.content.Context) 0xe9d4df14 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: void com.jg.bh.BH.install(android.content.Context) 0xe9d4df34 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: void com.jg.bh.BH.updateConfig(android.content.Context, java.lang.String) 0xe9d4df94 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: java.lang.String com.jg.bh.proxy.MyProxy.getEnable(android.content.Context) 0xe9d4e094 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: java.lang.String com.jg.bh.proxy.MyProxy.getMetaRow(android.content.Context) 0xe9d4e0b4 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: java.lang.Object com.jg.bh.proxy.MyProxy.getProxyObject(java.lang.Object, java.lang.reflect.InvocationHandler) 0xe9d4e0d4 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: java.lang.String com.jg.bh.proxy.MyProxy.getVersion(android.content.Context) 0xe9d4e0f4 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: void com.jg.bh.proxy.MyProxy.installAll(android.content.Context) 0xe9d4e114 0xd1b503f1 0x0
ArtMethod_RegisterNative onEnter: java.lang.Object com.jg.bh.proxy.MyProxy.newProxyInstance(java.lang.ClassLoader, java.lang.Class[], java.lang.reflect.InvocationHandler) 0xe9d4e134 0xd1b503f1 0x0

正常打印,第二个参数是注册地址


[2022夏季班]《安卓高级研修班(网课)》月薪三万班招生中~

收藏
点赞1
打赏
分享
最新回复 (7)
雪    币: 6282
活跃值: 活跃值 (801)
能力值: ( LV4,RANK:156 )
在线值:
发帖
回帖
粉丝
月落之汀 活跃值 1 2020-11-3 14:38
2
0
例子是熟悉的数字加固吧,不同的是,我直接写rom里面打log了
雪    币: 614
活跃值: 活跃值 (634)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
mb_foyotena 活跃值 2020-11-3 21:16
3
0
月落之汀 例子是熟悉的数字加固吧,不同的是,我直接写rom里面打log了
666
雪    币: 8220
活跃值: 活跃值 (3766)
能力值: ( LV8,RANK:134 )
在线值:
发帖
回帖
粉丝
hanbingle 活跃值 2 2020-11-4 12:55
4
0
在对app进行逆向分析过程中,jni函数往往是非常关键的。不管是jni函数地址的绑定,还是jni函数的调用和执行过程,都离不开ART的支持。得益于Android的开源,可以通过对源码进行阅读,一窥jni函数的注册原理,自然也就知道了静态注册的jni函数为什么必须按照固定的格式来定义函数名,同时又必须导出;而对于动态注册的jni函数的最终绑定的地址,也可以很容易定位。文章使用frida来对jni函数注册的整个流程进行了深入研究,可见已经彻底掌握了jni函数的整个注册原理和流程。
雪    币: 1
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
mb_kgpxcdre 活跃值 2020-12-12 13:09
5
0
你好 完整代码可以发一下吗
雪    币: 2357
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
webhacker 活跃值 2021-2-23 13:49
6
0
感谢分享,收藏学习!
雪    币: 248
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
@=llfly 活跃值 2021-3-31 10:44
7
0
感谢分享,收藏学习!
雪    币:
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
mb_cstihucu 活跃值 2021-11-29 10:38
8
0
你好 完整代码可以发一下吗。
我对文章里的allocPrettyMethod 这个从哪里来的不了解。
游客
登录 | 注册 方可回帖
返回