成熟的App會Hook本身

1、目標

李老闆: 奮飛呀,我都是本身了,還不是想怎麼玩就怎麼玩,還用Hook這麼麻煩嗎?android

奮飛:男人要對本身狠一點。git

我有一個 libtest.so,我調用它後,它會使用 android_log_print 輸出一些信息,我想讓它輸出的內容加點私貨。動手吧。github

  • so hook
  • Dobby

2、步驟

先把so調用起來

把so放在cpp的同級目錄 jniLibs下面。
而後跑起來,輸出:spa

2021-06-11 09:45:11.185 17916-18002/com.fenfei.dobbydemo D/mytest: call directly. 1
2021-06-11 09:45:11.185 17916-18002/com.fenfei.dobbydemo D/mytest: call from global ptr. 1
2021-06-11 09:45:11.185 17916-18002/com.fenfei.dobbydemo D/mytest: call from local ptr. 1
2021-06-11 09:45:11.185 17916-18002/com.fenfei.dobbydemo D/mytest: call from local ptr2. 1 (definitely failed when compiled with -O0)

咱們的目標就是在這些輸出裏面加點私貨。code

Dobby

https://github.com/jmpews/Dobby 是一個多平臺的Hook庫,反正很牛就對了。ci

git clone下來。get

整個文件夾放到 CMakeLists.txtnative-lib.cpp 同級目錄下面。it

而後編輯 CMakeLists.txt 文件io

# 這裏指定靜態連接,生成一個so;默認爲 ON,生成兩個so
set(GENERATE_SHARED OFF)
# 指定 dobby 庫目錄
set(DOBBY_SOURCE_DIR Dobby)
add_subdirectory(${DOBBY_SOURCE_DIR} dobby.out)
#end

......

# target_link_libraries 部分增長 dobby
target_link_libraries( # Specifies the target library.
                       native-lib
                       dobby

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

而後加上Hook代碼class

#include <android/log.h>
#include "Dobby/include/dobby.h"

static int (*orig_log_print)(int prio, const char* tag, const char* fmt, ...);
static int my_libtest_log_print(int prio, const char* tag, const char* fmt, ...)
{
    va_list ap;
    char buf[1024];
    int r;

    snprintf(buf, sizeof(buf), "[%s] %s", (NULL == tag ? "" : tag), (NULL == fmt ? "" : fmt));

    va_start(ap, fmt);
    r = __android_log_vprint(prio, "Dobby_libtest", buf, ap);
    va_end(ap);
    return r;
}

__attribute__((constructor)) static void ctor() {
    DobbyHook((void *) DobbySymbolResolver(NULL, "__android_log_print"), (void *) my_libtest_log_print,(void **) &orig_log_print);
}

跑起來,體驗一下。

2021-06-11 10:23:12.175 30447-30493/com.fenfei.dobbydemo D/Dobby_libtest: [mytest] call directly. 1
2021-06-11 10:23:12.175 30447-30493/com.fenfei.dobbydemo D/Dobby_libtest: [mytest] call from global ptr. 1
2021-06-11 10:23:12.175 30447-30493/com.fenfei.dobbydemo D/Dobby_libtest: [mytest] call from local ptr. 1
2021-06-11 10:23:12.175 30447-30493/com.fenfei.dobbydemo D/Dobby_libtest: [mytest] call from local ptr2. 1 (definitely failed when compiled with -O0)

私貨整進去了, mytest: 整成了 Dobby_libtest: [mytest]

3、總結

Hook是經久不衰的話題,除了Hook別人,Hook本身也是頗有意義的。

有的東西吧,外行人看起來很厲害,可是咱們內行人看起來吧,那真xxx不是通常的厲害