diff --git a/native/src/zygisk/entry.cpp b/native/src/zygisk/entry.cpp index 5b306bbd8..aed9a7fb3 100644 --- a/native/src/zygisk/entry.cpp +++ b/native/src/zygisk/entry.cpp @@ -34,15 +34,6 @@ static void sanitize_environ() { prctl(PR_SET_MM, PR_SET_MM_ENV_END, cur, 0, 0); } -[[gnu::destructor]] [[maybe_unused]] -static void zygisk_cleanup_wait() { - if (self_handle) { - // Wait 10us to make sure none of our code is executing - timespec ts = { .tv_sec = 0, .tv_nsec = 10000L }; - nanosleep(&ts, nullptr); - } -} - extern "C" void unload_first_stage() { ZLOGD("unloading first stage\n"); unmap_all(HIJACK_BIN); diff --git a/native/src/zygisk/gen_jni_hooks.py b/native/src/zygisk/gen_jni_hooks.py index 978179cad..7a759b4d5 100755 --- a/native/src/zygisk/gen_jni_hooks.py +++ b/native/src/zygisk/gen_jni_hooks.py @@ -95,9 +95,7 @@ class ForkAndSpec(JNIHook): for a in self.args: if a.set_arg: decl += ind(1) + f'args.{a.name} = &{a.name};' - decl += ind(1) + 'HookContext ctx;' - decl += ind(1) + 'ctx.env = env;' - decl += ind(1) + 'ctx.args = { &args };' + decl += ind(1) + 'HookContext ctx(env, &args);' decl += ind(1) + f'ctx.{self.base_name()}_pre();' decl += ind(1) + self.orig_method() + '(' decl += ind(2) + f'env, clazz, {self.name_list()}' @@ -233,8 +231,8 @@ def gen_jni_def(clz, methods): def gen_jni_hook(): decl = '' - decl += ind(0) + 'unique_ptr hookAndSaveJNIMethods(const char *className, const JNINativeMethod *methods, int numMethods) {' - decl += ind(1) + 'unique_ptr newMethods;' + decl += ind(0) + 'static JNINativeMethod *hookAndSaveJNIMethods(const char *className, const JNINativeMethod *methods, int numMethods) {' + decl += ind(1) + 'JNINativeMethod *newMethods = nullptr;' decl += ind(1) + 'int clz_id = -1;' decl += ind(1) + 'int hook_cnt = 0;' decl += ind(1) + 'do {' @@ -249,8 +247,8 @@ def gen_jni_hook(): decl += ind(1) + '} while (false);' decl += ind(1) + 'if (hook_cnt) {' - decl += ind(2) + 'newMethods = make_unique(numMethods);' - decl += ind(2) + 'memcpy(newMethods.get(), methods, sizeof(JNINativeMethod) * numMethods);' + decl += ind(2) + 'newMethods = new JNINativeMethod[numMethods];' + decl += ind(2) + 'memcpy(newMethods, methods, sizeof(JNINativeMethod) * numMethods);' decl += ind(1) + '}' decl += ind(1) + 'auto &class_map = (*jni_method_map)[className];' @@ -284,6 +282,7 @@ with open('jni_hooks.hpp', 'w') as f: methods = [server_l, server_samsung_q] f.write(gen_jni_def(zygote, methods)) - f.write(gen_jni_hook()) + f.write('\n} // namespace\n') - f.write('\n\n} // namespace\n') + f.write(gen_jni_hook()) + f.write('\n') diff --git a/native/src/zygisk/hook.cpp b/native/src/zygisk/hook.cpp index d38dfa7ad..50302f6ec 100644 --- a/native/src/zygisk/hook.cpp +++ b/native/src/zygisk/hook.cpp @@ -25,7 +25,9 @@ using xstring = jni_hook::string; //#define ZLOGV(...) ZLOGD(__VA_ARGS__) #define ZLOGV(...) (void*)0 -static bool unhook_functions(); +static void hook_unloader(); +static void unhook_functions(); +static void hook_jni_env(); namespace { @@ -35,12 +37,22 @@ enum { APP_SPECIALIZE, SERVER_FORK_AND_SPECIALIZE, DO_REVERT_UNMOUNT, - CAN_UNLOAD_ZYGISK, SKIP_FD_SANITIZATION, FLAG_MAX }; +// Global variables +vector> *plt_hook_list; +map, StringCmp> *jni_hook_list; +hash_map>> *jni_method_map; +bool should_unmap_zygisk = false; + +// Current context +HookContext *g_ctx; +const JNINativeInterface *old_functions = nullptr; +JNINativeInterface *new_functions = nullptr; + #define DCL_PRE_POST(name) \ void name##_pre(); \ void name##_post(); @@ -80,21 +92,24 @@ struct HookContext { vector register_info; vector ignore_info; - HookContext() : - env(nullptr), args{nullptr}, process(nullptr), pid(-1), info_flags(0), - hook_info_lock(PTHREAD_MUTEX_INITIALIZER) {} + HookContext(JNIEnv *env, void *args) : + env(env), args{args}, process(nullptr), pid(-1), info_flags(0), + hook_info_lock(PTHREAD_MUTEX_INITIALIZER) { g_ctx = this; } + + ~HookContext(); void run_modules_pre(const vector &fds); void run_modules_post(); DCL_PRE_POST(fork) DCL_PRE_POST(app_specialize) + DCL_PRE_POST(server_specialize) DCL_PRE_POST(nativeForkAndSpecialize) DCL_PRE_POST(nativeSpecializeAppProcess) DCL_PRE_POST(nativeForkSystemServer) - void unload_zygisk(); void sanitize_fds(); bool exempt_fd(int fd); + bool is_child() const { return pid <= 0; } // Compatibility shim void plt_hook_register(const char *regex, const char *symbol, void *fn, void **backup); @@ -106,105 +121,15 @@ struct HookContext { #undef DCL_PRE_POST -// Global variables -vector> *plt_hook_list; -map, StringCmp> *jni_hook_list; -hash_map>> *jni_method_map; - -// Current context -HookContext *g_ctx; -const JNINativeInterface *old_functions = nullptr; -JNINativeInterface *new_functions = nullptr; - -} // namespace - -#define HOOK_JNI(method) \ -if (methods[i].name == #method##sv) { \ - int j = 0; \ - for (; j < method##_methods_num; ++j) { \ - if (strcmp(methods[i].signature, method##_methods[j].signature) == 0) { \ - jni_hook_list->try_emplace(className).first->second.push_back(methods[i]); \ - method##_orig = methods[i].fnPtr; \ - newMethods[i] = method##_methods[j]; \ - ZLOGI("replaced %s#" #method "\n", className); \ - --hook_cnt; \ - break; \ - } \ - } \ - if (j == method##_methods_num) { \ - ZLOGE("unknown signature of %s#" #method ": %s\n", className, methods[i].signature); \ - } \ - continue; \ -} - -// JNI method hook definitions, auto generated -#include "jni_hooks.hpp" - -#undef HOOK_JNI - -namespace { - -string get_class_name(JNIEnv *env, jclass clazz) { - static auto class_getName = env->GetMethodID( - env->FindClass("java/lang/Class"), "getName", "()Ljava/lang/String;"); - auto nameRef = (jstring) env->CallObjectMethod(clazz, class_getName); - const char *name = env->GetStringUTFChars(nameRef, nullptr); - string className(name); - env->ReleaseStringUTFChars(nameRef, name); - std::replace(className.begin(), className.end(), '.', '/'); - return className; -} +// ----------------------------------------------------------------- #define DCL_HOOK_FUNC(ret, func, ...) \ ret (*old_##func)(__VA_ARGS__); \ ret new_##func(__VA_ARGS__) -jint env_RegisterNatives( - JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint numMethods) { - auto className = get_class_name(env, clazz); - ZLOGV("JNIEnv->RegisterNatives [%s]\n", className.data()); - auto newMethods = hookAndSaveJNIMethods(className.data(), methods, numMethods); - return old_functions->RegisterNatives(env, clazz, newMethods.get() ?: methods, numMethods); -} - DCL_HOOK_FUNC(void, androidSetCreateThreadFunc, void *func) { ZLOGD("androidSetCreateThreadFunc\n"); - using method_sig = jint(*)(JavaVM **, jsize, jsize *); - do { - auto get_created_vms = reinterpret_cast( - dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs")); - if (!get_created_vms) { - for (auto &map: lsplt::MapInfo::Scan()) { - if (!map.path.ends_with("/libnativehelper.so")) continue; - void *h = dlopen(map.path.data(), RTLD_LAZY); - if (!h) { - LOGW("cannot dlopen libnativehelper.so: %s\n", dlerror()); - break; - } - get_created_vms = reinterpret_cast(dlsym(h, "JNI_GetCreatedJavaVMs")); - dlclose(h); - break; - } - if (!get_created_vms) { - LOGW("JNI_GetCreatedJavaVMs not found\n"); - break; - } - } - JavaVM *vm = nullptr; - jsize num = 0; - jint res = get_created_vms(&vm, 1, &num); - if (res != JNI_OK || vm == nullptr) break; - JNIEnv *env = nullptr; - res = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); - if (res != JNI_OK || env == nullptr) break; - default_new(new_functions); - memcpy(new_functions, env->functions, sizeof(*new_functions)); - new_functions->RegisterNatives = &env_RegisterNatives; - - // Replace the function table in JNIEnv to hook RegisterNatives - old_functions = env->functions; - env->functions = new_functions; - } while (false); + hook_jni_env(); old_androidSetCreateThreadFunc(func); } @@ -241,7 +166,7 @@ DCL_HOOK_FUNC(void, android_log_close) { close(logd_fd.exchange(-1)); } else if (!g_ctx->flags[SKIP_FD_SANITIZATION]) { close(logd_fd.exchange(-1)); - if (g_ctx->pid <= 0) { + if (g_ctx->is_child()) { // Switch to plain old android logging because we cannot talk // to magiskd to fetch our log pipe afterwards anyways. android_logging(); @@ -250,36 +175,28 @@ DCL_HOOK_FUNC(void, android_log_close) { old_android_log_close(); } -// Last point before process secontext changes -DCL_HOOK_FUNC(int, selinux_android_setcontext, - uid_t uid, int isSystemServer, const char *seinfo, const char *pkgname) { - if (g_ctx) { - g_ctx->flags[CAN_UNLOAD_ZYGISK] = unhook_functions(); - } - return old_selinux_android_setcontext(uid, isSystemServer, seinfo, pkgname); -} - -dev_t art_dev = 0; -ino_t art_inode = 0; -pthread_t main_thread = 0; -DCL_HOOK_FUNC(int, pthread_attr_destroy, void* target) { +// We cannot directly call `dlclose` to unload ourselves, otherwise when `dlclose` returns, +// it will return to our code which has been unmapped, causing segmentation fault. +// Instead, we hook `pthread_attr_destroy` which will be called when VM daemon threads start. +DCL_HOOK_FUNC(int, pthread_attr_destroy, void *target) { int res = old_pthread_attr_destroy((pthread_attr_t *)target); - if (main_thread != pthread_self()) { + // Only perform unloading on the main thread + if (gettid() != getpid()) return res; + + ZLOGV("pthread_attr_destroy\n"); + if (should_unmap_zygisk) { + unhook_functions(); + if (should_unmap_zygisk) { + // Because both `pthread_attr_destroy` and `dlclose` have the same function signature, + // we can use `musttail` to let the compiler reuse our stack frame and thus + // `dlclose` will directly return to the caller of `pthread_attr_destroy`. + [[clang::musttail]] return dlclose(self_handle); + } } - ZLOGD("pthread_attr_destroy(%p)\n", target); - - lsplt::RegisterHook(art_dev, art_inode, "pthread_attr_destroy", reinterpret_cast(*old_pthread_attr_destroy), nullptr); - lsplt::CommitHook(); - - // Directly call `dlclose` will crash because when `dlclose` returns, CPU will try to execute code at an - // unmapped address. Because both `pthread_attr_destroy` and `dlclose` have same - // parameter types (a pointer) and return type (an int), the way they treat arguments and results - // are the same. We can use `musttail` to let the compiler reuse our stack frame and thus - // dlclose will directly return to the caller of `pthread_attr_destroy` - [[clang::musttail]] return dlclose(self_handle); + return res; } #undef DCL_HOOK_FUNC @@ -317,8 +234,8 @@ void hookJniNativeMethods(JNIEnv *env, const char *clz, JNINativeMethod *methods if (hooks.empty()) return; - old_functions->RegisterNatives(env, env->FindClass(clz), hooks.data(), - static_cast(hooks.size())); + old_functions->RegisterNatives( + env, env->FindClass(clz), hooks.data(), static_cast(hooks.size())); } ZygiskModule::ZygiskModule(int id, void *handle, void *entry) @@ -424,7 +341,6 @@ bool HookContext::plt_hook_commit() { return lsplt::CommitHook(); } - bool ZygiskModule::valid() const { if (mod.api_version == nullptr) return false; @@ -485,7 +401,6 @@ int sigmask(int how, int signum) { } void HookContext::fork_pre() { - g_ctx = this; // Do our own fork before loading any 3rd party code // First block SIGCHLD, unblock after original fork is done sigmask(SIG_BLOCK, SIGCHLD); @@ -507,6 +422,11 @@ void HookContext::fork_pre() { allowed_fds[dirfd(dir.get())] = false; } +void HookContext::fork_post() { + // Unblock SIGCHLD in case the original method didn't + sigmask(SIG_UNBLOCK, SIGCHLD); +} + void HookContext::sanitize_fds() { if (flags[SKIP_FD_SANITIZATION]) return; @@ -550,9 +470,6 @@ void HookContext::sanitize_fds() { } } - if (pid != 0) - return; - // Close all forbidden fds to prevent crashing auto dir = xopen_dir("/proc/self/fd"); int dfd = dirfd(dir.get()); @@ -564,13 +481,6 @@ void HookContext::sanitize_fds() { } } -void HookContext::fork_post() { - // Unblock SIGCHLD in case the original method didn't - sigmask(SIG_UNBLOCK, SIGCHLD); - g_ctx = nullptr; - unload_zygisk(); -} - void HookContext::run_modules_pre(const vector &fds) { for (int i = 0; i < fds.size(); ++i) { struct stat s{}; @@ -587,7 +497,7 @@ void HookContext::run_modules_pre(const vector &fds) { modules.emplace_back(i, h, e); } } else if (g_ctx->flags[SERVER_FORK_AND_SPECIALIZE]) { - LOGW("Failed to dlopen zygisk module: %s\n", dlerror()); + ZLOGW("Failed to dlopen zygisk module: %s\n", dlerror()); } close(fds[i]); } @@ -643,7 +553,6 @@ void HookContext::app_specialize_pre() { close(fd); } - void HookContext::app_specialize_post() { run_modules_post(); if (info_flags & PROCESS_IS_MAGISK_APP) { @@ -652,77 +561,11 @@ void HookContext::app_specialize_post() { // Cleanups env->ReleaseStringUTFChars(args.app->nice_name, process); - g_ctx = nullptr; close(logd_fd.exchange(-1)); android_logging(); } -void HookContext::unload_zygisk() { - if (flags[CAN_UNLOAD_ZYGISK]) { - // Do NOT call the destructor - operator delete(jni_method_map); - // Directly unmap the whole memory block - jni_hook::memory_block::release(); - - // Strip out all API function pointers - for (auto &m : modules) { - m.clearApi(); - } - - // We cannot directly `dlclose` ourselves here, otherwise when `dlclose` returns, it will return - // to our code which have been unmapped, causing a segment fault. Instead, we hook - // `pthread_attr_destroy` which will be called when VM daemon threads start and - // do some magic. Check comment in our replacement of the function for more info. - for (auto &map : lsplt::MapInfo::Scan()) { - if (map.path.ends_with("/libart.so")) { - ZLOGD("hook pthread_attr_destroy\n"); - art_inode = map.inode; - art_dev = map.dev; - main_thread = pthread_self(); - lsplt::RegisterHook(art_dev, art_inode, "pthread_attr_destroy", - reinterpret_cast(new_pthread_attr_destroy), - reinterpret_cast(&old_pthread_attr_destroy)); - lsplt::CommitHook(); - break; - } - } - } -} - -bool HookContext::exempt_fd(int fd) { - if (flags[POST_SPECIALIZE] || flags[SKIP_FD_SANITIZATION]) - return true; - if (!flags[APP_FORK_AND_SPECIALIZE]) - return false; - exempted_fds.push_back(fd); - return true; -} - -// ----------------------------------------------------------------- - -void HookContext::nativeSpecializeAppProcess_pre() { - process = env->GetStringUTFChars(args.app->nice_name, nullptr); - ZLOGV("pre specialize [%s]\n", process); - g_ctx = this; - // App specialize does not check FD - flags[SKIP_FD_SANITIZATION] = true; - app_specialize_pre(); -} - -void HookContext::nativeSpecializeAppProcess_post() { - ZLOGV("post specialize [%s]\n", process); - app_specialize_post(); - unload_zygisk(); -} - -void HookContext::nativeForkSystemServer_pre() { - ZLOGV("pre forkSystemServer\n"); - flags[SERVER_FORK_AND_SPECIALIZE] = true; - - fork_pre(); - if (pid != 0) - return; - +void HookContext::server_specialize_pre() { vector module_fds; int fd = remote_get_info(1000, "system_server", &info_flags, module_fds); if (fd >= 0) { @@ -743,14 +586,90 @@ void HookContext::nativeForkSystemServer_pre() { } close(fd); } +} - sanitize_fds(); +void HookContext::server_specialize_post() { + run_modules_post(); +} + +HookContext::~HookContext() { + // This global pointer points to a variable on the stack. + // Set this to nullptr to prevent leaking local variable. + // This also disables most plt hooked functions. + g_ctx = nullptr; + + if (!is_child()) + return; + + should_unmap_zygisk = true; + + // Restore JNIEnv + env->functions = old_functions; + delete new_functions; + + // Unhook JNI methods + for (const auto &[clz, methods] : *jni_hook_list) { + if (!methods.empty() && env->RegisterNatives( + env->FindClass(clz.data()), methods.data(), + static_cast(methods.size())) != 0) { + ZLOGE("Failed to restore JNI hook of class [%s]\n", clz.data()); + should_unmap_zygisk = false; + } + } + delete jni_hook_list; + + // Do NOT call the destructor + operator delete(jni_method_map); + // Directly unmap the whole memory block + jni_hook::memory_block::release(); + + // Strip out all API function pointers + for (auto &m : modules) { + m.clearApi(); + } + + hook_unloader(); +} + +bool HookContext::exempt_fd(int fd) { + if (flags[POST_SPECIALIZE] || flags[SKIP_FD_SANITIZATION]) + return true; + if (!flags[APP_FORK_AND_SPECIALIZE]) + return false; + exempted_fds.push_back(fd); + return true; +} + +// ----------------------------------------------------------------- + +void HookContext::nativeSpecializeAppProcess_pre() { + process = env->GetStringUTFChars(args.app->nice_name, nullptr); + ZLOGV("pre specialize [%s]\n", process); + // App specialize does not check FD + flags[SKIP_FD_SANITIZATION] = true; + app_specialize_pre(); +} + +void HookContext::nativeSpecializeAppProcess_post() { + ZLOGV("post specialize [%s]\n", process); + app_specialize_post(); +} + +void HookContext::nativeForkSystemServer_pre() { + ZLOGV("pre forkSystemServer\n"); + flags[SERVER_FORK_AND_SPECIALIZE] = true; + + fork_pre(); + if (is_child()) { + server_specialize_pre(); + sanitize_fds(); + } } void HookContext::nativeForkSystemServer_post() { - if (pid == 0) { + if (is_child()) { ZLOGV("post forkSystemServer\n"); - run_modules_post(); + server_specialize_post(); } fork_post(); } @@ -769,14 +688,14 @@ void HookContext::nativeForkAndSpecialize_pre() { } fork_pre(); - if (pid == 0) { + if (is_child()) { app_specialize_pre(); + sanitize_fds(); } - sanitize_fds(); } void HookContext::nativeForkAndSpecialize_post() { - if (pid == 0) { + if (is_child()) { ZLOGV("post forkAndSpecialize [%s]\n", process); app_specialize_post(); } @@ -785,14 +704,7 @@ void HookContext::nativeForkAndSpecialize_post() { } // namespace -static bool hook_commit() { - if (lsplt::CommitHook()) { - return true; - } else { - ZLOGE("plt_hook failed\n"); - return false; - } -} +// ----------------------------------------------------------------- static void hook_register(dev_t dev, ino_t inode, const char *symbol, void *new_func, void **old_func) { if (!lsplt::RegisterHook(dev, inode, symbol, new_func, old_func)) { @@ -802,8 +714,14 @@ static void hook_register(dev_t dev, ino_t inode, const char *symbol, void *new_ plt_hook_list->emplace_back(dev, inode, symbol, old_func); } +static void hook_commit() { + if (!lsplt::CommitHook()) + ZLOGE("plt_hook failed\n"); +} + #define PLT_HOOK_REGISTER_SYM(DEV, INODE, SYM, NAME) \ - hook_register(DEV, INODE, SYM, (void*) new_##NAME, (void **) &old_##NAME) + hook_register(DEV, INODE, SYM, \ + reinterpret_cast(new_##NAME), reinterpret_cast(&old_##NAME)) #define PLT_HOOK_REGISTER(DEV, INODE, NAME) \ PLT_HOOK_REGISTER_SYM(DEV, INODE, #NAME, NAME) @@ -815,6 +733,7 @@ void hook_functions() { ino_t android_runtime_inode = 0; dev_t android_runtime_dev = 0; + for (auto &map : lsplt::MapInfo::Scan()) { if (map.path.ends_with("libandroid_runtime.so")) { android_runtime_inode = map.inode; @@ -825,10 +744,10 @@ void hook_functions() { PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, fork); PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, unshare); - PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, selinux_android_setcontext); PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, androidSetCreateThreadFunc); PLT_HOOK_REGISTER_SYM(android_runtime_dev, android_runtime_inode, "__android_log_close", android_log_close); hook_commit(); + // Remove unhooked methods plt_hook_list->erase( std::remove_if(plt_hook_list->begin(), plt_hook_list->end(), @@ -836,38 +755,123 @@ void hook_functions() { plt_hook_list->end()); } -static bool unhook_functions() { - bool success = true; +static void hook_unloader() { + ino_t art_inode = 0; + dev_t art_dev = 0; - // Restore JNIEnv - if (g_ctx->env->functions == new_functions) { - g_ctx->env->functions = old_functions; - delete new_functions; - } - - // Unhook JNI methods - for (const auto &[clz, methods] : *jni_hook_list) { - if (!methods.empty() && g_ctx->env->RegisterNatives( - g_ctx->env->FindClass(clz.data()), methods.data(), - static_cast(methods.size())) != 0) { - ZLOGE("Failed to restore JNI hook of class [%s]\n", clz.data()); - success = false; + for (auto &map : lsplt::MapInfo::Scan()) { + if (map.path.ends_with("/libart.so")) { + art_inode = map.inode; + art_dev = map.dev; + break; } } - delete jni_hook_list; + PLT_HOOK_REGISTER(art_dev, art_inode, pthread_attr_destroy); + hook_commit(); +} + +static void unhook_functions() { // Unhook plt_hook for (const auto &[dev, inode, sym, old_func] : *plt_hook_list) { if (!lsplt::RegisterHook(dev, inode, sym, *old_func, nullptr)) { ZLOGE("Failed to register plt_hook [%s]\n", sym); - success = false; + should_unmap_zygisk = false; } } delete plt_hook_list; - if (!hook_commit()) { + if (!lsplt::CommitHook()) { ZLOGE("Failed to restore plt_hook\n"); - success = false; + should_unmap_zygisk = false; + } +} + +// ----------------------------------------------------------------- + +static JNINativeMethod *hookAndSaveJNIMethods(const char *, const JNINativeMethod *, int); + +static string get_class_name(JNIEnv *env, jclass clazz) { + static auto class_getName = env->GetMethodID( + env->FindClass("java/lang/Class"), "getName", "()Ljava/lang/String;"); + auto nameRef = (jstring) env->CallObjectMethod(clazz, class_getName); + const char *name = env->GetStringUTFChars(nameRef, nullptr); + string className(name); + env->ReleaseStringUTFChars(nameRef, name); + std::replace(className.begin(), className.end(), '.', '/'); + return className; +} + +static jint env_RegisterNatives( + JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint numMethods) { + auto className = get_class_name(env, clazz); + ZLOGV("JNIEnv->RegisterNatives [%s]\n", className.data()); + auto newMethods = unique_ptr( + hookAndSaveJNIMethods(className.data(), methods, numMethods)); + return old_functions->RegisterNatives(env, clazz, newMethods.get() ?: methods, numMethods); +} + +static void hook_jni_env() { + using method_sig = jint(*)(JavaVM **, jsize, jsize *); + auto get_created_vms = reinterpret_cast( + dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs")); + if (!get_created_vms) { + for (auto &map: lsplt::MapInfo::Scan()) { + if (!map.path.ends_with("/libnativehelper.so")) continue; + void *h = dlopen(map.path.data(), RTLD_LAZY); + if (!h) { + ZLOGW("Cannot dlopen libnativehelper.so: %s\n", dlerror()); + break; + } + get_created_vms = reinterpret_cast(dlsym(h, "JNI_GetCreatedJavaVMs")); + dlclose(h); + break; + } + if (!get_created_vms) { + ZLOGW("JNI_GetCreatedJavaVMs not found\n"); + return; + } } - return success; + JavaVM *vm = nullptr; + jsize num = 0; + jint res = get_created_vms(&vm, 1, &num); + if (res != JNI_OK || vm == nullptr) { + ZLOGW("JavaVM not found\n"); + return; + } + JNIEnv *env = nullptr; + res = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); + if (res != JNI_OK || env == nullptr) { + ZLOGW("JNIEnv not found\n"); + return; + } + + // Replace the function table in JNIEnv to hook RegisterNatives + default_new(new_functions); + memcpy(new_functions, env->functions, sizeof(*new_functions)); + new_functions->RegisterNatives = &env_RegisterNatives; + old_functions = env->functions; + env->functions = new_functions; } + +#define HOOK_JNI(method) \ +if (methods[i].name == #method##sv) { \ + int j = 0; \ + for (; j < method##_methods_num; ++j) { \ + if (strcmp(methods[i].signature, method##_methods[j].signature) == 0) { \ + jni_hook_list->try_emplace(className).first->second.push_back(methods[i]); \ + method##_orig = methods[i].fnPtr; \ + newMethods[i] = method##_methods[j]; \ + ZLOGI("replaced %s#" #method "\n", className); \ + --hook_cnt; \ + break; \ + } \ + } \ + if (j == method##_methods_num) { \ + ZLOGE("unknown signature of %s#" #method ": %s\n", className, methods[i].signature); \ + } \ + continue; \ +} + +// JNI method hook definitions, auto generated +#include "jni_hooks.hpp" diff --git a/native/src/zygisk/jni_hooks.hpp b/native/src/zygisk/jni_hooks.hpp index 4445ad6a5..9b6208398 100644 --- a/native/src/zygisk/jni_hooks.hpp +++ b/native/src/zygisk/jni_hooks.hpp @@ -5,9 +5,7 @@ namespace { void *nativeForkAndSpecialize_orig = nullptr; [[clang::no_stack_protector]] jint nativeForkAndSpecialize_l(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, instruction_set, app_data_dir @@ -18,9 +16,7 @@ void *nativeForkAndSpecialize_orig = nullptr; [[clang::no_stack_protector]] jint nativeForkAndSpecialize_o(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir @@ -32,9 +28,7 @@ void *nativeForkAndSpecialize_orig = nullptr; AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir @@ -47,9 +41,7 @@ void *nativeForkAndSpecialize_orig = nullptr; args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app @@ -66,9 +58,7 @@ void *nativeForkAndSpecialize_orig = nullptr; args.whitelisted_data_info_list = &whitelisted_data_info_list; args.mount_data_dirs = &mount_data_dirs; args.mount_storage_dirs = &mount_storage_dirs; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs @@ -78,9 +68,7 @@ void *nativeForkAndSpecialize_orig = nullptr; } [[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_m(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _0, jint _1, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _0, _1, nice_name, fds_to_close, instruction_set, app_data_dir @@ -90,9 +78,7 @@ void *nativeForkAndSpecialize_orig = nullptr; } [[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_n(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _2, jint _3, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir, jint _4) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _2, _3, nice_name, fds_to_close, instruction_set, app_data_dir, _4 @@ -103,9 +89,7 @@ void *nativeForkAndSpecialize_orig = nullptr; [[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_o(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _5, jint _6, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _5, _6, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir @@ -117,9 +101,7 @@ void *nativeForkAndSpecialize_orig = nullptr; AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast(nativeForkAndSpecialize_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _7, _8, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir @@ -180,9 +162,7 @@ void *nativeSpecializeAppProcess_orig = nullptr; [[clang::no_stack_protector]] void nativeSpecializeAppProcess_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast(nativeSpecializeAppProcess_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir @@ -193,9 +173,7 @@ void *nativeSpecializeAppProcess_orig = nullptr; AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast(nativeSpecializeAppProcess_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app @@ -210,9 +188,7 @@ void *nativeSpecializeAppProcess_orig = nullptr; args.whitelisted_data_info_list = &whitelisted_data_info_list; args.mount_data_dirs = &mount_data_dirs; args.mount_storage_dirs = &mount_storage_dirs; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast(nativeSpecializeAppProcess_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs @@ -222,9 +198,7 @@ void *nativeSpecializeAppProcess_orig = nullptr; [[clang::no_stack_protector]] void nativeSpecializeAppProcess_samsung_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _9, jint _10, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) { AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast(nativeSpecializeAppProcess_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _9, _10, nice_name, is_child_zygote, instruction_set, app_data_dir @@ -258,9 +232,7 @@ constexpr int nativeSpecializeAppProcess_methods_num = std::size(nativeSpecializ void *nativeForkSystemServer_orig = nullptr; [[clang::no_stack_protector]] jint nativeForkSystemServer_l(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities) { ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities); - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkSystemServer_pre(); reinterpret_cast(nativeForkSystemServer_orig)( env, clazz, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities @@ -270,9 +242,7 @@ void *nativeForkSystemServer_orig = nullptr; } [[clang::no_stack_protector]] jint nativeForkSystemServer_samsung_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jint _11, jint _12, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities) { ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities); - HookContext ctx; - ctx.env = env; - ctx.args = { &args }; + HookContext ctx(env, &args); ctx.nativeForkSystemServer_pre(); reinterpret_cast(nativeForkSystemServer_orig)( env, clazz, uid, gid, gids, runtime_flags, _11, _12, rlimits, permitted_capabilities, effective_capabilities @@ -294,8 +264,10 @@ const JNINativeMethod nativeForkSystemServer_methods[] = { }; constexpr int nativeForkSystemServer_methods_num = std::size(nativeForkSystemServer_methods); -unique_ptr hookAndSaveJNIMethods(const char *className, const JNINativeMethod *methods, int numMethods) { - unique_ptr newMethods; +} // namespace + +static JNINativeMethod *hookAndSaveJNIMethods(const char *className, const JNINativeMethod *methods, int numMethods) { + JNINativeMethod *newMethods = nullptr; int clz_id = -1; int hook_cnt = 0; do { @@ -306,8 +278,8 @@ unique_ptr hookAndSaveJNIMethods(const char *className, const } } while (false); if (hook_cnt) { - newMethods = make_unique(numMethods); - memcpy(newMethods.get(), methods, sizeof(JNINativeMethod) * numMethods); + newMethods = new JNINativeMethod[numMethods]; + memcpy(newMethods, methods, sizeof(JNINativeMethod) * numMethods); } auto &class_map = (*jni_method_map)[className]; for (int i = 0; i < numMethods; ++i) { @@ -320,5 +292,3 @@ unique_ptr hookAndSaveJNIMethods(const char *className, const } return newMethods; } - -} // namespace diff --git a/native/src/zygisk/zygisk.hpp b/native/src/zygisk/zygisk.hpp index 418fc8c6c..78f8de3d0 100644 --- a/native/src/zygisk/zygisk.hpp +++ b/native/src/zygisk/zygisk.hpp @@ -26,11 +26,13 @@ enum : int { #define ZLOGD(...) LOGD("zygisk64: " __VA_ARGS__) #define ZLOGE(...) LOGE("zygisk64: " __VA_ARGS__) #define ZLOGI(...) LOGI("zygisk64: " __VA_ARGS__) +#define ZLOGW(...) LOGW("zygisk64: " __VA_ARGS__) #define HIJACK_BIN HIJACK_BIN64 #else #define ZLOGD(...) LOGD("zygisk32: " __VA_ARGS__) #define ZLOGE(...) LOGE("zygisk32: " __VA_ARGS__) #define ZLOGI(...) LOGI("zygisk32: " __VA_ARGS__) +#define ZLOGW(...) LOGW("zygisk32: " __VA_ARGS__) #define HIJACK_BIN HIJACK_BIN32 #endif