Consolidate zygisk cleanup routines

This commit is contained in:
topjohnwu
2023-04-01 03:37:17 -07:00
committed by John Wu
parent 3a4fe53f27
commit 23b1b69110
5 changed files with 278 additions and 312 deletions
+247 -243
View File
@@ -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<tuple<dev_t, ino_t, const char *, void **>> *plt_hook_list;
map<string, vector<JNINativeMethod>, StringCmp> *jni_hook_list;
hash_map<xstring, tree_map<xstring, tree_map<xstring, void *>>> *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<RegisterInfo> register_info;
vector<IgnoreInfo> 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<int> &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<tuple<dev_t, ino_t, const char *, void **>> *plt_hook_list;
map<string, vector<JNINativeMethod>, StringCmp> *jni_hook_list;
hash_map<xstring, tree_map<xstring, tree_map<xstring, void *>>> *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<method_sig>(
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<method_sig>(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<void **>(&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<void*>(*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<int>(hooks.size()));
old_functions->RegisterNatives(
env, env->FindClass(clz), hooks.data(), static_cast<int>(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<int> &fds) {
for (int i = 0; i < fds.size(); ++i) {
struct stat s{};
@@ -587,7 +497,7 @@ void HookContext::run_modules_pre(const vector<int> &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<void *>(new_pthread_attr_destroy),
reinterpret_cast<void **>(&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<int> 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<int>(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<void *>(new_##NAME), reinterpret_cast<void **>(&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<int>(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<JNINativeMethod[]>(
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<method_sig>(
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<method_sig>(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<void **>(&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"