Dataset Viewer
Auto-converted to Parquet
id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
0
package.cpp
topjohnwu_Magisk/native/src/core/package.cpp
#include <base.hpp> #include <consts.hpp> #include <core.hpp> #include <db.hpp> #include <flags.h> using namespace std; using rust::Vec; #define ENFORCE_SIGNATURE (!MAGISK_DEBUG) // These functions will be called on every single zygote process specialization and su request, // so performance is absolutely critical. Most operations should either have its result cached // or simply skipped unless necessary. static pthread_mutex_t pkg_lock = PTHREAD_MUTEX_INITIALIZER; // pkg_lock protects all following variables static int stub_apk_fd = -1; static int repackaged_app_id = -1; // Only used by dyn static string repackaged_pkg; static Vec<uint8_t> repackaged_cert; static Vec<uint8_t> trusted_cert; static map<int, pair<string, time_t>> user_to_check; enum status { INSTALLED, NO_INSTALLED, CERT_MISMATCH, }; static bool operator==(const Vec<uint8_t> &a, const Vec<uint8_t> &b) { return a.size() == b.size() && memcmp(a.data(), b.data(), a.size()) == 0; } // app_id = app_no + AID_APP_START // app_no range: [0, 9999] vector<bool> get_app_no_list() { vector<bool> list; auto data_dir = xopen_dir(APP_DATA_DIR); if (!data_dir) return list; dirent *entry; while ((entry = xreaddir(data_dir.get()))) { // For each user int dfd = xopenat(dirfd(data_dir.get()), entry->d_name, O_RDONLY); if (auto dir = xopen_dir(dfd)) { while ((entry = xreaddir(dir.get()))) { // For each package struct stat st{}; xfstatat(dfd, entry->d_name, &st, 0); int app_id = to_app_id(st.st_uid); if (app_id >= AID_APP_START && app_id <= AID_APP_END) { int app_no = app_id - AID_APP_START; if (list.size() <= app_no) { list.resize(app_no + 1); } list[app_no] = true; } } } else { close(dfd); } } return list; } void preserve_stub_apk() { mutex_guard g(pkg_lock); string stub_path = get_magisk_tmp() + "/stub.apk"s; stub_apk_fd = xopen(stub_path.data(), O_RDONLY | O_CLOEXEC); unlink(stub_path.data()); trusted_cert = read_certificate(stub_apk_fd, MAGISK_VER_CODE); lseek(stub_apk_fd, 0, SEEK_SET); } static void install_stub() { if (stub_apk_fd < 0) return; struct stat st{}; fstat(stub_apk_fd, &st); char apk[] = "/data/stub.apk"; int dfd = xopen(apk, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); xsendfile(dfd, stub_apk_fd, nullptr, st.st_size); lseek(stub_apk_fd, 0, SEEK_SET); close(dfd); install_apk(apk); } static status check_dyn(int user, string &pkg) { struct stat st{}; char apk[PATH_MAX]; ssprintf(apk, sizeof(apk), "%s/%d/%s/dyn/current.apk", APP_DATA_DIR, user, pkg.data()); int dyn = open(apk, O_RDONLY | O_CLOEXEC); if (dyn < 0) { LOGW("pkg: no dyn APK, ignore\n"); return NO_INSTALLED; } auto cert = read_certificate(dyn, MAGISK_VER_CODE); fstat(dyn, &st); close(dyn); if (cert.empty() || cert != trusted_cert) { LOGE("pkg: dyn APK signature mismatch: %s\n", apk); #if ENFORCE_SIGNATURE clear_pkg(pkg.data(), user); return CERT_MISMATCH; #endif } repackaged_app_id = to_app_id(st.st_uid); user_to_check[user] = make_pair(apk, st.st_ctim.tv_sec); return INSTALLED; } static status check_stub(int user, string &pkg) { struct stat st{}; byte_array<PATH_MAX> buf; find_apk_path(pkg, buf); string apk((const char *) buf.buf(), buf.sz()); int fd = xopen(apk.data(), O_RDONLY | O_CLOEXEC); if (fd < 0) return NO_INSTALLED; auto cert = read_certificate(fd, -1); fstat(fd, &st); close(fd); if (cert.empty() || (pkg == repackaged_pkg && cert != repackaged_cert)) { LOGE("pkg: repackaged APK signature invalid: %s\n", apk.data()); uninstall_pkg(pkg.data()); return CERT_MISMATCH; } repackaged_pkg.swap(pkg); repackaged_cert.swap(cert); user_to_check[user] = make_pair(apk, st.st_ctim.tv_sec); return INSTALLED; } static status check_orig(int user) { struct stat st{}; byte_array<PATH_MAX> buf; find_apk_path(JAVA_PACKAGE_NAME, buf); string apk((const char *) buf.buf(), buf.sz()); int fd = xopen(apk.data(), O_RDONLY | O_CLOEXEC); if (fd < 0) return NO_INSTALLED; auto cert = read_certificate(fd, MAGISK_VER_CODE); fstat(fd, &st); close(fd); if (cert.empty() || cert != trusted_cert) { LOGE("pkg: APK signature mismatch: %s\n", apk.data()); #if ENFORCE_SIGNATURE uninstall_pkg(JAVA_PACKAGE_NAME); return CERT_MISMATCH; #endif } user_to_check[user] = make_pair(apk, st.st_ctim.tv_sec); return INSTALLED; } static int get_pkg_uid(int user, const char *pkg) { char path[PATH_MAX]; struct stat st{}; ssprintf(path, sizeof(path), "%s/%d/%s", APP_DATA_DIR, user, pkg); if (stat(path, &st) == 0) { return st.st_uid; } return -1; } int get_manager(int user, string *pkg, bool install) { mutex_guard g(pkg_lock); struct stat st{}; const auto &[path, time] = user_to_check[user]; if (stat(path.data(), &st) == 0 && st.st_ctim.tv_sec == time) { // no APK if (path == "/data/system/packages.xml") { if (install) install_stub(); if (pkg) pkg->clear(); return -1; } // dyn APK is still the same if (path.starts_with(APP_DATA_DIR)) { if (pkg) *pkg = repackaged_pkg; return user * AID_USER_OFFSET + repackaged_app_id; } // stub APK is still the same if (!repackaged_pkg.empty()) { if (check_dyn(user, repackaged_pkg) == INSTALLED) { if (pkg) *pkg = repackaged_pkg; return user * AID_USER_OFFSET + repackaged_app_id; } else { if (pkg) pkg->clear(); return -1; } } // orig APK is still the same int uid = get_pkg_uid(user, JAVA_PACKAGE_NAME); if (uid < 0) { if (pkg) pkg->clear(); return -1; } else { if (pkg) *pkg = JAVA_PACKAGE_NAME; return uid; } } db_strings str; get_db_strings(str, SU_MANAGER); if (!str[SU_MANAGER].empty()) { switch (check_stub(user, str[SU_MANAGER])) { case INSTALLED: if (check_dyn(user, repackaged_pkg) == INSTALLED) { if (pkg) *pkg = repackaged_pkg; return user * AID_USER_OFFSET + repackaged_app_id; } else { if (pkg) pkg->clear(); return -1; } case CERT_MISMATCH: install = true; case NO_INSTALLED: break; } } repackaged_pkg.clear(); repackaged_cert.clear(); switch (check_orig(user)) { case INSTALLED: { int uid = get_pkg_uid(user, JAVA_PACKAGE_NAME); if (uid < 0) { if (pkg) pkg->clear(); return -1; } else { if (pkg) *pkg = JAVA_PACKAGE_NAME; return uid; } } case CERT_MISMATCH: install = true; case NO_INSTALLED: break; } auto xml = "/data/system/packages.xml"; stat(xml, &st); user_to_check[user] = make_pair(xml, st.st_ctim.tv_sec); if (install) install_stub(); if (pkg) pkg->clear(); return -1; }
7,711
C++
.cpp
232
25.706897
95
0.561385
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1
selinux.cpp
topjohnwu_Magisk/native/src/core/selinux.cpp
#include <unistd.h> #include <sys/syscall.h> #include <sys/xattr.h> #include <consts.hpp> #include <base.hpp> #include <selinux.hpp> #include <core.hpp> #include <flags.h> using namespace std; int setcon(const char *con) { int fd = open("/proc/self/attr/current", O_WRONLY | O_CLOEXEC); if (fd < 0) return fd; size_t len = strlen(con) + 1; int rc = write(fd, con, len); close(fd); return rc != len; } int getfilecon(const char *path, byte_data con) { return syscall(__NR_getxattr, path, XATTR_NAME_SELINUX, con.buf(), con.sz()); } int lgetfilecon(const char *path, byte_data con) { return syscall(__NR_lgetxattr, path, XATTR_NAME_SELINUX, con.buf(), con.sz()); } int fgetfilecon(int fd, byte_data con) { return syscall(__NR_fgetxattr, fd, XATTR_NAME_SELINUX, con.buf(), con.sz()); } int setfilecon(const char *path, const char *con) { return syscall(__NR_setxattr, path, XATTR_NAME_SELINUX, con, strlen(con) + 1, 0); } int lsetfilecon(const char *path, const char *con) { return syscall(__NR_lsetxattr, path, XATTR_NAME_SELINUX, con, strlen(con) + 1, 0); } int fsetfilecon(int fd, const char *con) { return syscall(__NR_fsetxattr, fd, XATTR_NAME_SELINUX, con, strlen(con) + 1, 0); } int getfilecon_at(int dirfd, const char *name, byte_data con) { char path[4096]; fd_pathat(dirfd, name, path, sizeof(path)); return lgetfilecon(path, con); } void setfilecon_at(int dirfd, const char *name, const char *con) { char path[4096]; fd_pathat(dirfd, name, path, sizeof(path)); lsetfilecon(path, con); } #define UNLABEL_CON "u:object_r:unlabeled:s0" #define SYSTEM_CON "u:object_r:system_file:s0" #define ADB_CON "u:object_r:adb_data_file:s0" #define ROOT_CON "u:object_r:rootfs:s0" static void restore_syscon_from_null(int dirfd) { struct dirent *entry; char con[1024]; if (fgetfilecon(dirfd, { con, sizeof(con) }) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0) fsetfilecon(dirfd, SYSTEM_CON); } auto dir = xopen_dir(dirfd); while ((entry = xreaddir(dir.get()))) { int fd = openat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (entry->d_type == DT_DIR) { restore_syscon_from_null(fd); continue; } else if (entry->d_type == DT_REG) { if (fgetfilecon(fd, { con, sizeof(con) }) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0) fsetfilecon(fd, SYSTEM_CON); } } else if (entry->d_type == DT_LNK) { if (getfilecon_at(dirfd, entry->d_name, { con, sizeof(con) }) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0) setfilecon_at(dirfd, entry->d_name, SYSTEM_CON); } } close(fd); } } static void restore_syscon(int dirfd) { struct dirent *entry; fsetfilecon(dirfd, SYSTEM_CON); fchown(dirfd, 0, 0); auto dir = xopen_dir(dirfd); while ((entry = xreaddir(dir.get()))) { int fd = xopenat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (entry->d_type == DT_DIR) { restore_syscon(fd); continue; } else if (entry->d_type) { fsetfilecon(fd, SYSTEM_CON); fchown(fd, 0, 0); } close(fd); } } void restorecon() { int fd = xopen("/sys/fs/selinux/context", O_WRONLY | O_CLOEXEC); if (write(fd, ADB_CON, sizeof(ADB_CON)) >= 0) lsetfilecon(SECURE_DIR, ADB_CON); close(fd); lsetfilecon(MODULEROOT, SYSTEM_CON); restore_syscon_from_null(xopen(MODULEROOT, O_RDONLY | O_CLOEXEC)); restore_syscon(xopen(DATABIN, O_RDONLY | O_CLOEXEC)); } void restore_tmpcon() { const char *tmp = get_magisk_tmp(); if (tmp == "/sbin"sv) setfilecon(tmp, ROOT_CON); else chmod(tmp, 0711); auto dir = xopen_dir(tmp); int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) setfilecon_at(dfd, entry->d_name, SYSTEM_CON); string logd = tmp + "/"s LOG_PIPE; setfilecon(logd.data(), MAGISK_LOG_CON); }
4,154
C++
.cpp
116
30.12931
86
0.606227
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2
applets.cpp
topjohnwu_Magisk/native/src/core/applets.cpp
#include <libgen.h> #include <sys/types.h> #include <sys/stat.h> #include <consts.hpp> #include <selinux.hpp> #include <base.hpp> using namespace std; struct Applet { string_view name; int (*fn)(int, char *[]); }; constexpr Applet applets[] = { { "su", su_client_main }, { "resetprop", resetprop_main }, }; constexpr Applet private_applets[] = { { "zygisk", zygisk_main }, }; int main(int argc, char *argv[]) { if (argc < 1) return 1; cmdline_logging(); init_argv0(argc, argv); string_view argv0 = basename(argv[0]); umask(0); if (argv[0][0] == '\0') { // When argv[0] is an empty string, we're calling private applets if (argc < 2) return 1; --argc; ++argv; for (const auto &app : private_applets) { if (argv[0] == app.name) { return app.fn(argc, argv); } } fprintf(stderr, "%s: applet not found\n", argv[0]); return 1; } if (argv0 == "magisk" || argv0 == "magisk32" || argv0 == "magisk64") { if (argc > 1 && argv[1][0] != '-') { // Calling applet with "magisk [applet] args..." --argc; ++argv; argv0 = argv[0]; } else { return magisk_main(argc, argv); } } for (const auto &app : applets) { if (argv0 == app.name) { return app.fn(argc, argv); } } fprintf(stderr, "%s: applet not found\n", argv0.data()); return 1; }
1,537
C++
.cpp
57
20.350877
74
0.521117
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3
daemon.cpp
topjohnwu_Magisk/native/src/core/daemon.cpp
#include <csignal> #include <libgen.h> #include <sys/un.h> #include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include <core.hpp> #include <selinux.hpp> #include <db.hpp> #include <flags.h> using namespace std; int SDK_INT = -1; static struct stat self_st; static map<int, poll_callback> *poll_map; static vector<pollfd> *poll_fds; static int poll_ctrl; enum { POLL_CTRL_NEW, POLL_CTRL_RM, }; void register_poll(const pollfd *pfd, poll_callback callback) { if (gettid() == getpid()) { // On main thread, directly modify poll_map->try_emplace(pfd->fd, callback); poll_fds->emplace_back(*pfd); } else { // Send it to poll_ctrl write_int(poll_ctrl, POLL_CTRL_NEW); xwrite(poll_ctrl, pfd, sizeof(*pfd)); xwrite(poll_ctrl, &callback, sizeof(callback)); } } void unregister_poll(int fd, bool auto_close) { if (fd < 0) return; if (gettid() == getpid()) { // On main thread, directly modify poll_map->erase(fd); for (auto &poll_fd : *poll_fds) { if (poll_fd.fd == fd) { if (auto_close) { close(poll_fd.fd); } // Cannot modify while iterating, invalidate it instead // It will be removed in the next poll loop poll_fd.fd = -1; break; } } } else { // Send it to poll_ctrl write_int(poll_ctrl, POLL_CTRL_RM); write_int(poll_ctrl, fd); write_int(poll_ctrl, auto_close); } } void clear_poll() { if (poll_fds) { for (auto &poll_fd : *poll_fds) { close(poll_fd.fd); } } delete poll_fds; delete poll_map; poll_fds = nullptr; poll_map = nullptr; } static void poll_ctrl_handler(pollfd *pfd) { int code = read_int(pfd->fd); switch (code) { case POLL_CTRL_NEW: { pollfd new_fd{}; poll_callback cb; xxread(pfd->fd, &new_fd, sizeof(new_fd)); xxread(pfd->fd, &cb, sizeof(cb)); register_poll(&new_fd, cb); break; } case POLL_CTRL_RM: { int fd = read_int(pfd->fd); bool auto_close = read_int(pfd->fd); unregister_poll(fd, auto_close); break; } default: __builtin_unreachable(); } } [[noreturn]] static void poll_loop() { // Register poll_ctrl auto pipefd = array<int, 2>{-1, -1}; xpipe2(pipefd, O_CLOEXEC); poll_ctrl = pipefd[1]; pollfd poll_ctrl_pfd = { pipefd[0], POLLIN, 0 }; register_poll(&poll_ctrl_pfd, poll_ctrl_handler); for (;;) { if (poll(poll_fds->data(), poll_fds->size(), -1) <= 0) continue; // MUST iterate with index because any poll_callback could add new elements to poll_fds for (int i = 0; i < poll_fds->size();) { auto &pfd = (*poll_fds)[i]; if (pfd.revents) { if (pfd.revents & POLLERR || pfd.revents & POLLNVAL) { poll_map->erase(pfd.fd); poll_fds->erase(poll_fds->begin() + i); continue; } if (auto it = poll_map->find(pfd.fd); it != poll_map->end()) { it->second(&pfd); } } ++i; } } } const MagiskD &MagiskD::get() { return *reinterpret_cast<const MagiskD*>(&rust::get_magiskd()); } const rust::MagiskD *MagiskD::operator->() const { return reinterpret_cast<const rust::MagiskD*>(this); } const rust::MagiskD &MagiskD::as_rust() const { return *operator->(); } void MagiskD::reboot() const { if (as_rust().is_recovery()) exec_command_sync("/system/bin/reboot", "recovery"); else exec_command_sync("/system/bin/reboot"); } static void handle_request_async(int client, int code, const sock_cred &cred) { switch (code) { case +RequestCode::DENYLIST: denylist_handler(client, &cred); break; case +RequestCode::SUPERUSER: su_daemon_handler(client, &cred); break; case +RequestCode::ZYGOTE_RESTART: LOGI("** zygote restarted\n"); prune_su_access(); scan_deny_apps(); reset_zygisk(false); close(client); break; case +RequestCode::SQLITE_CMD: exec_sql(client); break; case +RequestCode::REMOVE_MODULES: { int do_reboot = read_int(client); remove_modules(); write_int(client, 0); close(client); if (do_reboot) { MagiskD::get().reboot(); } break; } case +RequestCode::ZYGISK: zygisk_handler(client, &cred); break; default: __builtin_unreachable(); } } static void handle_request_sync(int client, int code) { switch (code) { case +RequestCode::CHECK_VERSION: #if MAGISK_DEBUG write_string(client, MAGISK_VERSION ":MAGISK:D"); #else write_string(client, MAGISK_VERSION ":MAGISK:R"); #endif break; case +RequestCode::CHECK_VERSION_CODE: write_int(client, MAGISK_VER_CODE); break; case +RequestCode::START_DAEMON: MagiskD::get()->setup_logfile(); break; case +RequestCode::STOP_DAEMON: { // Unmount all overlays denylist_handler(-1, nullptr); // Restore native bridge property auto nb = get_prop(NBPROP); auto len = sizeof(ZYGISKLDR) - 1; if (nb == ZYGISKLDR) { set_prop(NBPROP, "0"); } else if (nb.size() > len) { set_prop(NBPROP, nb.data() + len); } write_int(client, 0); // Terminate the daemon! exit(0); } default: __builtin_unreachable(); } } static bool is_client(pid_t pid) { // Verify caller is the same as server char path[32]; sprintf(path, "/proc/%d/exe", pid); struct stat st{}; return !(stat(path, &st) || st.st_dev != self_st.st_dev || st.st_ino != self_st.st_ino); } static void handle_request(pollfd *pfd) { owned_fd client = xaccept4(pfd->fd, nullptr, nullptr, SOCK_CLOEXEC); // Verify client credentials sock_cred cred; bool is_root; bool is_zygote; int code; if (!get_client_cred(client, &cred)) { // Client died return; } is_root = cred.uid == AID_ROOT; is_zygote = cred.context == "u:r:zygote:s0"; if (!is_root && !is_zygote && !is_client(cred.pid)) { // Unsupported client state write_int(client, +RespondCode::ACCESS_DENIED); return; } code = read_int(client); if (code < 0 || code >= +RequestCode::END || code == +RequestCode::_SYNC_BARRIER_ || code == +RequestCode::_STAGE_BARRIER_) { // Unknown request code return; } // Check client permissions switch (code) { case +RequestCode::POST_FS_DATA: case +RequestCode::LATE_START: case +RequestCode::BOOT_COMPLETE: case +RequestCode::ZYGOTE_RESTART: case +RequestCode::SQLITE_CMD: case +RequestCode::DENYLIST: case +RequestCode::STOP_DAEMON: if (!is_root) { write_int(client, +RespondCode::ROOT_REQUIRED); return; } break; case +RequestCode::REMOVE_MODULES: if (!is_root && cred.uid != AID_SHELL) { write_int(client, +RespondCode::ACCESS_DENIED); return; } break; case +RequestCode::ZYGISK: if (!is_zygote) { // Invalid client context write_int(client, +RespondCode::ACCESS_DENIED); return; } break; default: break; } write_int(client, +RespondCode::OK); if (code < +RequestCode::_SYNC_BARRIER_) { handle_request_sync(client, code); } else if (code < +RequestCode::_STAGE_BARRIER_) { exec_task([=, fd = client.release()] { handle_request_async(fd, code, cred); }); } else { exec_task([=, fd = client.release()] { MagiskD::get()->boot_stage_handler(fd, code); }); } } static void switch_cgroup(const char *cgroup, int pid) { char buf[32]; ssprintf(buf, sizeof(buf), "%s/cgroup.procs", cgroup); if (access(buf, F_OK) != 0) return; int fd = xopen(buf, O_WRONLY | O_APPEND | O_CLOEXEC); if (fd == -1) return; ssprintf(buf, sizeof(buf), "%d\n", pid); xwrite(fd, buf, strlen(buf)); close(fd); } static void daemon_entry() { android_logging(); // Block all signals sigset_t block_set; sigfillset(&block_set); pthread_sigmask(SIG_SETMASK, &block_set, nullptr); // Change process name set_nice_name("magiskd"); int fd = xopen("/dev/null", O_WRONLY); xdup2(fd, STDOUT_FILENO); xdup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); fd = xopen("/dev/zero", O_RDONLY); xdup2(fd, STDIN_FILENO); if (fd > STDERR_FILENO) close(fd); setsid(); setcon(MAGISK_PROC_CON); rust::daemon_entry(); LOGI(NAME_WITH_VER(Magisk) " daemon started\n"); // Escape from cgroup int pid = getpid(); switch_cgroup("/acct", pid); switch_cgroup("/dev/cg2_bpf", pid); switch_cgroup("/sys/fs/cgroup", pid); if (get_prop("ro.config.per_app_memcg") != "false") { switch_cgroup("/dev/memcg/apps", pid); } // Get self stat xstat("/proc/self/exe", &self_st); // Get API level parse_prop_file("/system/build.prop", [](auto key, auto val) -> bool { if (key == "ro.build.version.sdk") { SDK_INT = parse_int(val); return false; } return true; }); if (SDK_INT < 0) { // In case some devices do not store this info in build.prop, fallback to getprop auto sdk = get_prop("ro.build.version.sdk"); if (!sdk.empty()) { SDK_INT = parse_int(sdk); } } LOGI("* Device API level: %d\n", SDK_INT); // Samsung workaround #7887 if (access("/system_ext/app/mediatek-res/mediatek-res.apk", F_OK) == 0) { set_prop("ro.vendor.mtk_model", "0"); } restore_tmpcon(); // Cleanups const char *tmp = get_magisk_tmp(); char path[64]; ssprintf(path, sizeof(path), "%s/" ROOTMNT, tmp); if (access(path, F_OK) == 0) { file_readline(true, path, [](string_view line) -> bool { umount2(line.data(), MNT_DETACH); return true; }); } if (getenv("REMOUNT_ROOT")) { xmount(nullptr, "/", nullptr, MS_REMOUNT | MS_RDONLY, nullptr); unsetenv("REMOUNT_ROOT"); } ssprintf(path, sizeof(path), "%s/" ROOTOVL, tmp); rm_rf(path); fd = xsocket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); sockaddr_un addr = {.sun_family = AF_LOCAL}; ssprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" MAIN_SOCKET, tmp); unlink(addr.sun_path); if (xbind(fd, (sockaddr *) &addr, sizeof(addr))) exit(1); chmod(addr.sun_path, 0666); setfilecon(addr.sun_path, MAGISK_FILE_CON); xlisten(fd, 10); default_new(poll_map); default_new(poll_fds); default_new(module_list); // Register handler for main socket pollfd main_socket_pfd = { fd, POLLIN, 0 }; register_poll(&main_socket_pfd, handle_request); // Loop forever to listen for requests init_thread_pool(); poll_loop(); } const char *get_magisk_tmp() { static const char *path = nullptr; if (path == nullptr) { if (access("/debug_ramdisk/" INTLROOT, F_OK) == 0) { path = "/debug_ramdisk"; } else if (access("/sbin/" INTLROOT, F_OK) == 0) { path = "/sbin"; } else { path = ""; } } return path; } int connect_daemon(int req, bool create) { int fd = xsocket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); sockaddr_un addr = {.sun_family = AF_LOCAL}; const char *tmp = get_magisk_tmp(); ssprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" MAIN_SOCKET, tmp); if (connect(fd, (sockaddr *) &addr, sizeof(addr))) { if (!create || getuid() != AID_ROOT) { LOGE("No daemon is currently running!\n"); close(fd); return -1; } char buf[64]; xreadlink("/proc/self/exe", buf, sizeof(buf)); if (tmp[0] == '\0' || !str_starts(buf, tmp)) { LOGE("Start daemon on magisk tmpfs\n"); close(fd); return -1; } if (fork_dont_care() == 0) { close(fd); daemon_entry(); } while (connect(fd, (sockaddr *) &addr, sizeof(addr))) usleep(10000); } write_int(fd, req); int res = read_int(fd); if (res < +RespondCode::ERROR || res >= +RespondCode::END) res = +RespondCode::ERROR; switch (res) { case +RespondCode::OK: break; case +RespondCode::ERROR: LOGE("Daemon error\n"); close(fd); return -1; case +RespondCode::ROOT_REQUIRED: LOGE("Root is required for this operation\n"); close(fd); return -1; case +RespondCode::ACCESS_DENIED: LOGE("Access denied\n"); close(fd); return -1; default: __builtin_unreachable(); } return fd; }
13,327
C++
.cpp
433
23.711316
95
0.565329
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4
scripting.cpp
topjohnwu_Magisk/native/src/core/scripting.cpp
#include <string> #include <vector> #include <sys/wait.h> #include <consts.hpp> #include <base.hpp> #include <selinux.hpp> #include <core.hpp> using namespace std; #define BBEXEC_CMD bbpath(), "sh" static const char *bbpath() { static string path; path = get_magisk_tmp(); path += "/" BBPATH "/busybox"; if (access(path.data(), X_OK) != 0) { path = DATABIN "/busybox"; } return path.data(); } static void set_script_env() { setenv("ASH_STANDALONE", "1", 1); char new_path[4096]; ssprintf(new_path, sizeof(new_path), "%s:%s", getenv("PATH"), get_magisk_tmp()); setenv("PATH", new_path, 1); if (zygisk_enabled) setenv("ZYGISK_ENABLED", "1", 1); }; void exec_script(const char *script) { exec_t exec { .pre_exec = set_script_env, .fork = fork_no_orphan }; exec_command_sync(exec, BBEXEC_CMD, script); } static timespec pfs_timeout; #define PFS_SETUP() \ if (pfs) { \ if (int pid = xfork()) { \ if (pid < 0) \ return; \ /* In parent process, simply wait for child to finish */ \ waitpid(pid, nullptr, 0); \ return; \ } \ timer_pid = xfork(); \ if (timer_pid == 0) { \ /* In timer process, count down */ \ clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &pfs_timeout, nullptr); \ exit(0); \ } \ } #define PFS_WAIT() \ if (pfs) { \ /* If we ran out of time, don't block */ \ if (timer_pid < 0) \ continue; \ if (int pid = waitpid(-1, nullptr, 0); pid == timer_pid) { \ LOGW("* post-fs-data scripts blocking phase timeout\n"); \ timer_pid = -1; \ } \ } #define PFS_DONE() \ if (pfs) { \ if (timer_pid > 0) \ kill(timer_pid, SIGKILL); \ exit(0); \ } void exec_common_scripts(const char *stage) { LOGI("* Running %s.d scripts\n", stage); char path[4096]; char *name = path + sprintf(path, SECURE_DIR "/%s.d", stage); auto dir = xopen_dir(path); if (!dir) return; bool pfs = stage == "post-fs-data"sv; int timer_pid = -1; if (pfs) { // Setup timer clock_gettime(CLOCK_MONOTONIC, &pfs_timeout); pfs_timeout.tv_sec += POST_FS_DATA_SCRIPT_MAX_TIME; } PFS_SETUP() *(name++) = '/'; int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_type == DT_REG) { if (faccessat(dfd, entry->d_name, X_OK, 0) != 0) continue; LOGI("%s.d: exec [%s]\n", stage, entry->d_name); strcpy(name, entry->d_name); exec_t exec { .pre_exec = set_script_env, .fork = pfs ? xfork : fork_dont_care }; exec_command(exec, BBEXEC_CMD, path); PFS_WAIT() } } PFS_DONE() } static bool operator>(const timespec &a, const timespec &b) { if (a.tv_sec != b.tv_sec) return a.tv_sec > b.tv_sec; return a.tv_nsec > b.tv_nsec; } void exec_module_scripts(const char *stage, const vector<string_view> &modules) { LOGI("* Running module %s scripts\n", stage); if (modules.empty()) return; bool pfs = stage == "post-fs-data"sv; if (pfs) { timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); // If we had already timed out, treat it as service mode if (now > pfs_timeout) pfs = false; } int timer_pid = -1; PFS_SETUP() char path[4096]; for (auto &m : modules) { const char *module = m.data(); sprintf(path, MODULEROOT "/%s/%s.sh", module, stage); if (access(path, F_OK) == -1) continue; LOGI("%s: exec [%s.sh]\n", module, stage); exec_t exec { .pre_exec = set_script_env, .fork = pfs ? xfork : fork_dont_care }; exec_command(exec, BBEXEC_CMD, path); PFS_WAIT() } PFS_DONE() } constexpr char install_script[] = R"EOF( APK=%s log -t Magisk "pm_install: $APK" log -t Magisk "pm_install: $(pm install -g -r $APK 2>&1)" appops set %s REQUEST_INSTALL_PACKAGES allow rm -f $APK )EOF"; void install_apk(const char *apk) { setfilecon(apk, MAGISK_FILE_CON); char cmds[sizeof(install_script) + 4096]; ssprintf(cmds, sizeof(cmds), install_script, apk, JAVA_PACKAGE_NAME); exec_command_async("/system/bin/sh", "-c", cmds); } constexpr char uninstall_script[] = R"EOF( PKG=%s log -t Magisk "pm_uninstall: $PKG" log -t Magisk "pm_uninstall: $(pm uninstall $PKG 2>&1)" )EOF"; void uninstall_pkg(const char *pkg) { char cmds[sizeof(uninstall_script) + 256]; ssprintf(cmds, sizeof(cmds), uninstall_script, pkg); exec_command_async("/system/bin/sh", "-c", cmds); } constexpr char clear_script[] = R"EOF( PKG=%s USER=%d log -t Magisk "pm_clear: $PKG (user=$USER)" log -t Magisk "pm_clear: $(pm clear --user $USER $PKG 2>&1)" )EOF"; void clear_pkg(const char *pkg, int user_id) { char cmds[sizeof(clear_script) + 288]; ssprintf(cmds, sizeof(cmds), clear_script, pkg, user_id); exec_command_async("/system/bin/sh", "-c", cmds); } [[noreturn]] __printflike(2, 3) static void abort(FILE *fp, const char *fmt, ...) { va_list valist; va_start(valist, fmt); vfprintf(fp, fmt, valist); fprintf(fp, "\n\n"); va_end(valist); exit(1); } constexpr char install_module_script[] = R"EOF( exec %s sh -c ' . /data/adb/magisk/util_functions.sh install_module exit 0' )EOF"; void install_module(const char *file) { if (getuid() != 0) abort(stderr, "Run this command with root"); if (access(DATABIN, F_OK) || access(bbpath(), X_OK) || access(DATABIN "/util_functions.sh", F_OK)) abort(stderr, "Incomplete Magisk install"); if (access(file, F_OK)) abort(stderr, "'%s' does not exist", file); char *zip = realpath(file, nullptr); setenv("OUTFD", "1", 1); setenv("ZIPFILE", zip, 1); setenv("ASH_STANDALONE", "1", 1); setenv("MAGISKTMP", get_magisk_tmp(), 0); free(zip); int fd = xopen("/dev/null", O_RDONLY); xdup2(fd, STDERR_FILENO); close(fd); char cmds[256]; ssprintf(cmds, sizeof(cmds), install_module_script, bbpath()); const char *argv[] = { "/system/bin/sh", "-c", cmds, nullptr }; execve(argv[0], (char **) argv, environ); abort(stdout, "Failed to execute BusyBox shell"); }
6,402
C++
.cpp
206
25.805825
84
0.587768
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
5
bootstages.cpp
topjohnwu_Magisk/native/src/core/bootstages.cpp
#include <sys/mount.h> #include <sys/wait.h> #include <sys/sysmacros.h> #include <linux/input.h> #include <libgen.h> #include <set> #include <string> #include <consts.hpp> #include <db.hpp> #include <base.hpp> #include <core.hpp> #include <selinux.hpp> using namespace std; bool zygisk_enabled = false; /********* * Setup * *********/ static bool magisk_env() { char buf[4096]; LOGI("* Initializing Magisk environment\n"); ssprintf(buf, sizeof(buf), "%s/0/%s/install", APP_DATA_DIR, JAVA_PACKAGE_NAME); // Alternative binaries paths const char *alt_bin[] = { "/cache/data_adb/magisk", "/data/magisk", buf }; for (auto alt : alt_bin) { if (access(alt, F_OK) == 0) { rm_rf(DATABIN); cp_afc(alt, DATABIN); rm_rf(alt); } } rm_rf("/cache/data_adb"); // Directories in /data/adb chmod(SECURE_DIR, 0700); xmkdir(DATABIN, 0755); xmkdir(MODULEROOT, 0755); xmkdir(SECURE_DIR "/post-fs-data.d", 0755); xmkdir(SECURE_DIR "/service.d", 0755); restorecon(); if (access(DATABIN "/busybox", X_OK)) return false; ssprintf(buf, sizeof(buf), "%s/" BBPATH "/busybox", get_magisk_tmp()); mkdir(dirname(buf), 0755); cp_afc(DATABIN "/busybox", buf); exec_command_async(buf, "--install", "-s", dirname(buf)); // magisk32 and magiskpolicy are not installed into ramdisk and has to be copied // from data to magisk tmp if (access(DATABIN "/magisk32", X_OK) == 0) { ssprintf(buf, sizeof(buf), "%s/magisk32", get_magisk_tmp()); cp_afc(DATABIN "/magisk32", buf); } if (access(DATABIN "/magiskpolicy", X_OK) == 0) { ssprintf(buf, sizeof(buf), "%s/magiskpolicy", get_magisk_tmp()); cp_afc(DATABIN "/magiskpolicy", buf); } return true; } void unlock_blocks() { int fd, dev, OFF = 0; auto dir = xopen_dir("/dev/block"); if (!dir) return; dev = dirfd(dir.get()); for (dirent *entry; (entry = readdir(dir.get()));) { if (entry->d_type == DT_BLK) { if ((fd = openat(dev, entry->d_name, O_RDONLY | O_CLOEXEC)) < 0) continue; if (ioctl(fd, BLKROSET, &OFF) < 0) PLOGE("unlock %s", entry->d_name); close(fd); } } } #define test_bit(bit, array) (array[bit / 8] & (1 << (bit % 8))) static bool check_key_combo() { uint8_t bitmask[(KEY_MAX + 1) / 8]; vector<int> events; constexpr char name[] = "/dev/.ev"; // First collect candidate events that accepts volume down for (int minor = 64; minor < 96; ++minor) { if (xmknod(name, S_IFCHR | 0444, makedev(13, minor))) continue; int fd = open(name, O_RDONLY | O_CLOEXEC); unlink(name); if (fd < 0) continue; memset(bitmask, 0, sizeof(bitmask)); ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(bitmask)), bitmask); if (test_bit(KEY_VOLUMEDOWN, bitmask)) events.push_back(fd); else close(fd); } if (events.empty()) return false; run_finally fin([&]{ std::for_each(events.begin(), events.end(), close); }); // Check if volume down key is held continuously for more than 3 seconds for (int i = 0; i < 300; ++i) { bool pressed = false; for (const int &fd : events) { memset(bitmask, 0, sizeof(bitmask)); ioctl(fd, EVIOCGKEY(sizeof(bitmask)), bitmask); if (test_bit(KEY_VOLUMEDOWN, bitmask)) { pressed = true; break; } } if (!pressed) return false; // Check every 10ms usleep(10000); } LOGD("KEY_VOLUMEDOWN detected: enter safe mode\n"); return true; } static bool check_safe_mode() { int bootloop_cnt; db_settings dbs; get_db_settings(dbs, BOOTLOOP_COUNT); bootloop_cnt = dbs[BOOTLOOP_COUNT]; // Increment the bootloop counter set_db_settings(BOOTLOOP_COUNT, bootloop_cnt + 1); return bootloop_cnt >= 2 || get_prop("persist.sys.safemode", true) == "1" || get_prop("ro.sys.safemode") == "1" || check_key_combo(); } /*********************** * Boot Stage Handlers * ***********************/ bool MagiskD::post_fs_data() const { as_rust().setup_logfile(); LOGI("** post-fs-data mode running\n"); preserve_stub_apk(); prune_su_access(); bool safe_mode = false; if (access(SECURE_DIR, F_OK) != 0) { if (SDK_INT < 24) { xmkdir(SECURE_DIR, 0700); } else { LOGE(SECURE_DIR " is not present, abort\n"); safe_mode = true; return safe_mode; } } if (!magisk_env()) { LOGE("* Magisk environment incomplete, abort\n"); safe_mode = true; return safe_mode; } if (check_safe_mode()) { LOGI("* Safe mode triggered\n"); safe_mode = true; // Disable all modules and zygisk so next boot will be clean disable_modules(); set_db_settings(ZYGISK_CONFIG, false); return safe_mode; } exec_common_scripts("post-fs-data"); db_settings dbs; get_db_settings(dbs, ZYGISK_CONFIG); zygisk_enabled = dbs[ZYGISK_CONFIG]; initialize_denylist(); setup_mounts(); handle_modules(); load_modules(); return safe_mode; } void MagiskD::late_start() const { as_rust().setup_logfile(); LOGI("** late_start service mode running\n"); exec_common_scripts("service"); exec_module_scripts("service"); } void MagiskD::boot_complete() const { as_rust().setup_logfile(); LOGI("** boot-complete triggered\n"); // Reset the bootloop counter once we have boot-complete set_db_settings(BOOTLOOP_COUNT, 0); // At this point it's safe to create the folder if (access(SECURE_DIR, F_OK) != 0) xmkdir(SECURE_DIR, 0700); // Ensure manager exists get_manager(0, nullptr, true); reset_zygisk(true); }
6,013
C++
.cpp
183
26.42623
84
0.582974
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6
socket.cpp
topjohnwu_Magisk/native/src/core/socket.cpp
#include <fcntl.h> #include <endian.h> #include <socket.hpp> #include <base.hpp> using namespace std; bool get_client_cred(int fd, sock_cred *cred) { socklen_t len = sizeof(ucred); if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, cred, &len) != 0) return false; char buf[4096]; len = sizeof(buf); if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &len) != 0) len = 0; buf[len] = '\0'; cred->context = buf; return true; } static int send_fds(int sockfd, void *cmsgbuf, size_t bufsz, const int *fds, int cnt) { iovec iov = { .iov_base = &cnt, .iov_len = sizeof(cnt), }; msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, }; if (cnt) { msg.msg_control = cmsgbuf; msg.msg_controllen = bufsz; cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_len = CMSG_LEN(sizeof(int) * cnt); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; memcpy(CMSG_DATA(cmsg), fds, sizeof(int) * cnt); } return xsendmsg(sockfd, &msg, 0); } int send_fds(int sockfd, const int *fds, int cnt) { if (cnt == 0) { return send_fds(sockfd, nullptr, 0, nullptr, 0); } vector<char> cmsgbuf; cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); return send_fds(sockfd, cmsgbuf.data(), cmsgbuf.size(), fds, cnt); } int send_fd(int sockfd, int fd) { if (fd < 0) { return send_fds(sockfd, nullptr, 0, nullptr, 0); } char cmsgbuf[CMSG_SPACE(sizeof(int))]; return send_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), &fd, 1); } static void *recv_fds(int sockfd, char *cmsgbuf, size_t bufsz, int cnt) { iovec iov = { .iov_base = &cnt, .iov_len = sizeof(cnt), }; msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cmsgbuf, .msg_controllen = bufsz }; xrecvmsg(sockfd, &msg, MSG_WAITALL); if (msg.msg_controllen != bufsz) { LOGE("recv_fd: msg_flags = %d, msg_controllen(%zu) != %zu\n", msg.msg_flags, msg.msg_controllen, bufsz); return nullptr; } cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) { LOGE("recv_fd: cmsg == nullptr\n"); return nullptr; } if (cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt)) { LOGE("recv_fd: cmsg_len(%zu) != %zu\n", cmsg->cmsg_len, CMSG_LEN(sizeof(int) * cnt)); return nullptr; } if (cmsg->cmsg_level != SOL_SOCKET) { LOGE("recv_fd: cmsg_level != SOL_SOCKET\n"); return nullptr; } if (cmsg->cmsg_type != SCM_RIGHTS) { LOGE("recv_fd: cmsg_type != SCM_RIGHTS\n"); return nullptr; } return CMSG_DATA(cmsg); } vector<int> recv_fds(int sockfd) { vector<int> results; // Peek fd count to allocate proper buffer int cnt; recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); if (cnt == 0) { // Consume data recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL); return results; } vector<char> cmsgbuf; cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); void *data = recv_fds(sockfd, cmsgbuf.data(), cmsgbuf.size(), cnt); if (data == nullptr) return results; results.resize(cnt); memcpy(results.data(), data, sizeof(int) * cnt); return results; } int recv_fd(int sockfd) { // Peek fd count int cnt; recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); if (cnt == 0) { // Consume data recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL); return -1; } char cmsgbuf[CMSG_SPACE(sizeof(int))]; void *data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1); if (data == nullptr) return -1; int result; memcpy(&result, data, sizeof(int)); return result; } int read_int(int fd) { int val; if (xxread(fd, &val, sizeof(val)) != sizeof(val)) return -1; return val; } int read_int_be(int fd) { return ntohl(read_int(fd)); } void write_int(int fd, int val) { if (fd < 0) return; xwrite(fd, &val, sizeof(val)); } void write_int_be(int fd, int val) { write_int(fd, htonl(val)); } bool read_string(int fd, std::string &str) { int len = read_int(fd); str.clear(); if (len < 0) return false; str.resize(len); return xxread(fd, str.data(), len) == len; } string read_string(int fd) { string str; read_string(fd, str); return str; } void write_string(int fd, string_view str) { if (fd < 0) return; write_int(fd, str.size()); xwrite(fd, str.data(), str.size()); }
4,615
C++
.cpp
158
23.759494
93
0.581884
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
7
magisk.cpp
topjohnwu_Magisk/native/src/core/magisk.cpp
#include <sys/mount.h> #include <libgen.h> #include <base.hpp> #include <consts.hpp> #include <core.hpp> #include <selinux.hpp> #include <flags.h> using namespace std; [[noreturn]] static void usage() { fprintf(stderr, R"EOF(Magisk - Multi-purpose Utility Usage: magisk [applet [arguments]...] or: magisk [options]... Options: -c print current binary version -v print running daemon version -V print running daemon version code --list list all available applets --remove-modules [-n] remove all modules, reboot if -n is not provided --install-module ZIP install a module zip file Advanced Options (Internal APIs): --daemon manually start magisk daemon --stop remove all magisk changes and stop daemon --[init trigger] callback on init triggers. Valid triggers: post-fs-data, service, boot-complete, zygote-restart --unlock-blocks set BLKROSET flag to OFF for all block devices --restorecon restore selinux context on Magisk files --clone-attr SRC DEST clone permission, owner, and selinux context --clone SRC DEST clone SRC to DEST --sqlite SQL exec SQL commands to Magisk database --path print Magisk tmpfs mount path --denylist ARGS denylist config CLI --preinit-device resolve a device to store preinit files Available applets: )EOF"); for (int i = 0; applet_names[i]; ++i) fprintf(stderr, i ? ", %s" : " %s", applet_names[i]); fprintf(stderr, "\n\n"); exit(1); } int magisk_main(int argc, char *argv[]) { if (argc < 2) usage(); if (argv[1] == "-c"sv) { #if MAGISK_DEBUG printf(MAGISK_VERSION ":MAGISK:D (" str(MAGISK_VER_CODE) ")\n"); #else printf(MAGISK_VERSION ":MAGISK:R (" str(MAGISK_VER_CODE) ")\n"); #endif return 0; } else if (argv[1] == "-v"sv) { int fd = connect_daemon(+RequestCode::CHECK_VERSION); string v = read_string(fd); printf("%s\n", v.data()); return 0; } else if (argv[1] == "-V"sv) { int fd = connect_daemon(+RequestCode::CHECK_VERSION_CODE); printf("%d\n", read_int(fd)); return 0; } else if (argv[1] == "--list"sv) { for (int i = 0; applet_names[i]; ++i) printf("%s\n", applet_names[i]); return 0; } else if (argv[1] == "--unlock-blocks"sv) { unlock_blocks(); return 0; } else if (argv[1] == "--restorecon"sv) { restorecon(); return 0; } else if (argc >= 4 && argv[1] == "--clone-attr"sv) { clone_attr(argv[2], argv[3]); return 0; } else if (argc >= 4 && argv[1] == "--clone"sv) { cp_afc(argv[2], argv[3]); return 0; } else if (argv[1] == "--daemon"sv) { close(connect_daemon(+RequestCode::START_DAEMON, true)); return 0; } else if (argv[1] == "--stop"sv) { int fd = connect_daemon(+RequestCode::STOP_DAEMON); return read_int(fd); } else if (argv[1] == "--post-fs-data"sv) { int fd = connect_daemon(+RequestCode::POST_FS_DATA, true); struct pollfd pfd = { fd, POLLIN, 0 }; poll(&pfd, 1, 1000 * POST_FS_DATA_WAIT_TIME); return 0; } else if (argv[1] == "--service"sv) { close(connect_daemon(+RequestCode::LATE_START, true)); return 0; } else if (argv[1] == "--boot-complete"sv) { close(connect_daemon(+RequestCode::BOOT_COMPLETE)); return 0; } else if (argv[1] == "--zygote-restart"sv) { close(connect_daemon(+RequestCode::ZYGOTE_RESTART)); return 0; } else if (argv[1] == "--denylist"sv) { return denylist_cli(argc - 1, argv + 1); } else if (argc >= 3 && argv[1] == "--sqlite"sv) { int fd = connect_daemon(+RequestCode::SQLITE_CMD); write_string(fd, argv[2]); string res; for (;;) { read_string(fd, res); if (res.empty()) return 0; printf("%s\n", res.data()); } } else if (argv[1] == "--remove-modules"sv) { int do_reboot; if (argc == 3 && argv[2] == "-n"sv) { do_reboot = 0; } else if (argc == 2) { do_reboot = 1; } else { usage(); } int fd = connect_daemon(+RequestCode::REMOVE_MODULES); write_int(fd, do_reboot); return read_int(fd); } else if (argv[1] == "--path"sv) { const char *path = get_magisk_tmp(); if (path[0] != '\0') { printf("%s\n", path); return 0; } return 1; } else if (argc >= 3 && argv[1] == "--install-module"sv) { install_module(argv[2]); } else if (argv[1] == "--preinit-device"sv) { auto name = find_preinit_device(); if (!name.empty()) { printf("%s\n", name.c_str()); return 0; } return 1; } #if 0 /* Entry point for testing stuffs */ else if (argv[1] == "--test"sv) { rust_test_entry(); return 0; } #endif usage(); }
5,251
C++
.cpp
145
29.365517
81
0.537767
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8
thread.cpp
topjohnwu_Magisk/native/src/core/thread.cpp
// Cached thread pool implementation #include <base.hpp> #include <core.hpp> using namespace std; #define THREAD_IDLE_MAX_SEC 60 #define CORE_POOL_SIZE 3 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t send_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; static pthread_cond_t recv_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; // The following variables should be guarded by lock static int idle_threads = 0; static int total_threads = 0; static function<void()> pending_task; static void operator+=(timespec &a, const timespec &b) { a.tv_sec += b.tv_sec; a.tv_nsec += b.tv_nsec; if (a.tv_nsec >= 1000000000L) { a.tv_sec++; a.tv_nsec -= 1000000000L; } } static void reset_pool() { clear_poll(); pthread_mutex_unlock(&lock); pthread_mutex_destroy(&lock); pthread_mutex_init(&lock, nullptr); pthread_cond_destroy(&send_task); send_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; pthread_cond_destroy(&recv_task); recv_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; idle_threads = 0; total_threads = 0; pending_task = nullptr; } static void *thread_pool_loop(void * const is_core_pool) { // Block all signals sigset_t mask; sigfillset(&mask); for (;;) { // Restore sigmask pthread_sigmask(SIG_SETMASK, &mask, nullptr); function<void()> local_task; { mutex_guard g(lock); ++idle_threads; if (!pending_task) { if (is_core_pool) { pthread_cond_wait(&send_task, &lock); } else { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); ts += { THREAD_IDLE_MAX_SEC, 0 }; if (pthread_cond_timedwait(&send_task, &lock, &ts) == ETIMEDOUT) { // Terminate thread after max idle time --idle_threads; --total_threads; return nullptr; } } } if (pending_task) { local_task.swap(pending_task); pthread_cond_signal(&recv_task); } --idle_threads; } if (local_task) local_task(); if (getpid() == gettid()) exit(0); } } void init_thread_pool() { pthread_atfork(nullptr, nullptr, &reset_pool); } void exec_task(function<void()> &&task) { mutex_guard g(lock); pending_task.swap(task); if (idle_threads == 0) { ++total_threads; long is_core_pool = total_threads <= CORE_POOL_SIZE; new_daemon_thread(thread_pool_loop, (void *) is_core_pool); } else { pthread_cond_signal(&send_task); } pthread_cond_wait(&recv_task, &lock); }
2,848
C++
.cpp
87
24.517241
86
0.575482
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
9
applet_stub.cpp
topjohnwu_Magisk/native/src/core/applet_stub.cpp
#include <sys/stat.h> #include <consts.hpp> #include <selinux.hpp> #include <base.hpp> int main(int argc, char *argv[]) { if (argc < 1) return 1; cmdline_logging(); init_argv0(argc, argv); umask(0); return APPLET_STUB_MAIN(argc, argv); }
268
C++
.cpp
12
18.833333
40
0.641732
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10
module.cpp
topjohnwu_Magisk/native/src/core/module.cpp
#include <sys/mman.h> #include <sys/syscall.h> #include <sys/mount.h> #include <map> #include <utility> #include <base.hpp> #include <consts.hpp> #include <core.hpp> #include <selinux.hpp> #include "node.hpp" using namespace std; #define VLOGD(tag, from, to) LOGD("%-8s: %s <- %s\n", tag, to, from) static int bind_mount(const char *reason, const char *from, const char *to) { int ret = xmount(from, to, nullptr, MS_BIND | MS_REC, nullptr); if (ret == 0) VLOGD(reason, from, to); return ret; } /************************* * Node Tree Construction *************************/ tmpfs_node::tmpfs_node(node_entry *node) : dir_node(node, this) { if (!replace()) { if (auto dir = open_dir(node_path().data())) { set_exist(true); for (dirent *entry; (entry = xreaddir(dir.get()));) { // create a dummy inter_node to upgrade later emplace<inter_node>(entry->d_name, entry); } } } for (auto it = children.begin(); it != children.end(); ++it) { // Upgrade resting inter_node children to tmpfs_node if (isa<inter_node>(it->second)) it = upgrade<tmpfs_node>(it); } } bool dir_node::prepare() { // If direct replace or not exist, mount ourselves as tmpfs bool upgrade_to_tmpfs = replace() || !exist(); for (auto it = children.begin(); it != children.end();) { // We also need to upgrade to tmpfs node if any child: // - Target does not exist // - Source or target is a symlink (since we cannot bind mount symlink) bool cannot_mnt; if (struct stat st{}; lstat(it->second->node_path().data(), &st) != 0) { cannot_mnt = true; } else { it->second->set_exist(true); cannot_mnt = it->second->is_lnk() || S_ISLNK(st.st_mode); } if (cannot_mnt) { if (_node_type > type_id<tmpfs_node>()) { // Upgrade will fail, remove the unsupported child node LOGW("Unable to add: %s, skipped\n", it->second->node_path().data()); delete it->second; it = children.erase(it); continue; } upgrade_to_tmpfs = true; } if (auto dn = dyn_cast<dir_node>(it->second)) { if (replace()) { // Propagate skip mirror state to all children dn->set_replace(true); } if (dn->prepare()) { // Upgrade child to tmpfs it = upgrade<tmpfs_node>(it); } } ++it; } return upgrade_to_tmpfs; } void dir_node::collect_module_files(const char *module, int dfd) { auto dir = xopen_dir(xopenat(dfd, name().data(), O_RDONLY | O_CLOEXEC)); if (!dir) return; for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_name == ".replace"sv) { set_replace(true); continue; } if (entry->d_type == DT_DIR) { inter_node *node; if (auto it = children.find(entry->d_name); it == children.end()) { node = emplace<inter_node>(entry->d_name, entry->d_name); } else { node = dyn_cast<inter_node>(it->second); } if (node) { node->collect_module_files(module, dirfd(dir.get())); } } else { emplace<module_node>(entry->d_name, module, entry); } } } /************************ * Mount Implementations ************************/ void node_entry::create_and_mount(const char *reason, const string &src, bool ro) { const string dest = isa<tmpfs_node>(parent()) ? worker_path() : node_path(); if (is_lnk()) { VLOGD("cp_link", src.data(), dest.data()); cp_afc(src.data(), dest.data()); } else { if (is_dir()) xmkdir(dest.data(), 0); else if (is_reg()) close(xopen(dest.data(), O_RDONLY | O_CREAT | O_CLOEXEC, 0)); else return; bind_mount(reason, src.data(), dest.data()); if (ro) { xmount(nullptr, dest.data(), nullptr, MS_REMOUNT | MS_BIND | MS_RDONLY, nullptr); } } } void module_node::mount() { std::string path = module + (parent()->root()->prefix + node_path()); string mnt_src = module_mnt + path; { string src = MODULEROOT "/" + path; if (exist()) clone_attr(node_path().data(), src.data()); } if (isa<tmpfs_node>(parent())) { create_and_mount("module", mnt_src); } else { bind_mount("module", mnt_src.data(), node_path().data()); } } void tmpfs_node::mount() { if (!is_dir()) { create_and_mount("mirror", node_path()); return; } if (!isa<tmpfs_node>(parent())) { auto worker_dir = worker_path(); mkdirs(worker_dir.data(), 0); clone_attr(exist() ? node_path().data() : parent()->node_path().data(), worker_dir.data()); dir_node::mount(); bind_mount(replace() ? "replace" : "move", worker_dir.data(), node_path().data()); xmount(nullptr, node_path().data(), nullptr, MS_REMOUNT | MS_BIND | MS_RDONLY, nullptr); } else { const string dest = worker_path(); // We don't need another layer of tmpfs if parent is tmpfs mkdir(dest.data(), 0); clone_attr(exist() ? node_path().data() : parent()->worker_path().data(), dest.data()); dir_node::mount(); } } /**************** * Magisk Stuffs ****************/ class magisk_node : public node_entry { public: explicit magisk_node(const char *name) : node_entry(name, DT_REG, this) {} void mount() override { const string src = get_magisk_tmp() + "/"s + name(); if (access(src.data(), F_OK)) return; const string dir_name = isa<tmpfs_node>(parent()) ? parent()->worker_path() : parent()->node_path(); if (name() == "magisk") { for (int i = 0; applet_names[i]; ++i) { string dest = dir_name + "/" + applet_names[i]; VLOGD("create", "./magisk", dest.data()); xsymlink("./magisk", dest.data()); } } else { string dest = dir_name + "/supolicy"; VLOGD("create", "./magiskpolicy", dest.data()); xsymlink("./magiskpolicy", dest.data()); } create_and_mount("magisk", src, true); } }; class zygisk_node : public node_entry { public: explicit zygisk_node(const char *name, bool is64bit) : node_entry(name, DT_REG, this), is64bit(is64bit) {} void mount() override { #if defined(__LP64__) const string src = get_magisk_tmp() + "/magisk"s + (is64bit ? "" : "32"); #else const string src = get_magisk_tmp() + "/magisk"s; (void) is64bit; #endif if (access(src.data(), F_OK)) return; create_and_mount("zygisk", src, true); } private: bool is64bit; }; static void inject_magisk_bins(root_node *system) { auto bin = system->get_child<inter_node>("bin"); if (!bin) { bin = new inter_node("bin"); system->insert(bin); } // Insert binaries bin->insert(new magisk_node("magisk")); bin->insert(new magisk_node("magiskpolicy")); // Also delete all applets to make sure no modules can override it for (int i = 0; applet_names[i]; ++i) delete bin->extract(applet_names[i]); delete bin->extract("supolicy"); } static void inject_zygisk_libs(root_node *system) { if (access("/system/bin/linker", F_OK) == 0) { auto lib = system->get_child<inter_node>("lib"); if (!lib) { lib = new inter_node("lib"); system->insert(lib); } lib->insert(new zygisk_node(native_bridge.data(), false)); } if (access("/system/bin/linker64", F_OK) == 0) { auto lib64 = system->get_child<inter_node>("lib64"); if (!lib64) { lib64 = new inter_node("lib64"); system->insert(lib64); } lib64->insert(new zygisk_node(native_bridge.data(), true)); } } vector<module_info> *module_list; void load_modules() { node_entry::module_mnt = get_magisk_tmp() + "/"s MODULEMNT "/"; auto root = make_unique<root_node>(""); auto system = new root_node("system"); root->insert(system); char buf[4096]; LOGI("* Loading modules\n"); for (const auto &m : *module_list) { const char *module = m.name.data(); char *b = buf + ssprintf(buf, sizeof(buf), "%s/" MODULEMNT "/%s/", get_magisk_tmp(), module); // Read props strcpy(b, "system.prop"); if (access(buf, F_OK) == 0) { LOGI("%s: loading [system.prop]\n", module); // Do NOT go through property service as it could cause boot lock load_prop_file(buf, true); } // Check whether skip mounting strcpy(b, "skip_mount"); if (access(buf, F_OK) == 0) continue; // Double check whether the system folder exists strcpy(b, "system"); if (access(buf, F_OK) != 0) continue; LOGI("%s: loading mount files\n", module); b[-1] = '\0'; int fd = xopen(buf, O_RDONLY | O_CLOEXEC); system->collect_module_files(module, fd); close(fd); } if (get_magisk_tmp() != "/sbin"sv || !str_contains(getenv("PATH") ?: "", "/sbin")) { // Need to inject our binaries into /system/bin inject_magisk_bins(system); } if (zygisk_enabled) { string native_bridge_orig = get_prop(NBPROP); if (native_bridge_orig.empty()) { native_bridge_orig = "0"; } native_bridge = native_bridge_orig != "0" ? ZYGISKLDR + native_bridge_orig : ZYGISKLDR; set_prop(NBPROP, native_bridge.data()); // Weather Huawei's Maple compiler is enabled. // If so, system server will be created by a special Zygote which ignores the native bridge // and make system server out of our control. Avoid it by disabling. if (get_prop("ro.maple.enable") == "1") { set_prop("ro.maple.enable", "0"); } inject_zygisk_libs(system); } if (!system->is_empty()) { // Handle special read-only partitions for (const char *part : { "/vendor", "/product", "/system_ext" }) { struct stat st{}; if (lstat(part, &st) == 0 && S_ISDIR(st.st_mode)) { if (auto old = system->extract(part + 1)) { auto new_node = new root_node(old); root->insert(new_node); } } } root->prepare(); root->mount(); } // cleanup mounts clean_mounts(); } /************************ * Filesystem operations ************************/ static void prepare_modules() { // Upgrade modules if (auto dir = open_dir(MODULEUPGRADE); dir) { int ufd = dirfd(dir.get()); int mfd = xopen(MODULEROOT, O_RDONLY | O_CLOEXEC); for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_type == DT_DIR) { // Cleanup old module if exists if (faccessat(mfd, entry->d_name, F_OK, 0) == 0) { int modfd = xopenat(mfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (faccessat(modfd, "disable", F_OK, 0) == 0) { auto disable = entry->d_name + "/disable"s; close(xopenat(ufd, disable.data(), O_RDONLY | O_CREAT | O_CLOEXEC, 0)); } frm_rf(modfd); unlinkat(mfd, entry->d_name, AT_REMOVEDIR); } LOGI("Upgrade / New module: %s\n", entry->d_name); renameat(ufd, entry->d_name, mfd, entry->d_name); } } close(mfd); rm_rf(MODULEUPGRADE); } } template<typename Func> static void foreach_module(Func fn) { auto dir = open_dir(MODULEROOT); if (!dir) return; int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_type == DT_DIR && entry->d_name != ".core"sv) { int modfd = xopenat(dfd, entry->d_name, O_RDONLY | O_CLOEXEC); fn(dfd, entry, modfd); close(modfd); } } } static void collect_modules(bool open_zygisk) { foreach_module([=](int dfd, dirent *entry, int modfd) { if (faccessat(modfd, "remove", F_OK, 0) == 0) { LOGI("%s: remove\n", entry->d_name); auto uninstaller = MODULEROOT + "/"s + entry->d_name + "/uninstall.sh"; if (access(uninstaller.data(), F_OK) == 0) exec_script(uninstaller.data()); frm_rf(xdup(modfd)); unlinkat(dfd, entry->d_name, AT_REMOVEDIR); return; } unlinkat(modfd, "update", 0); if (faccessat(modfd, "disable", F_OK, 0) == 0) return; module_info info; if (zygisk_enabled) { // Riru and its modules are not compatible with zygisk if (entry->d_name == "riru-core"sv || faccessat(modfd, "riru", F_OK, 0) == 0) { LOGI("%s: ignore\n", entry->d_name); return; } if (open_zygisk) { #if defined(__arm__) info.z32 = openat(modfd, "zygisk/armeabi-v7a.so", O_RDONLY | O_CLOEXEC); #elif defined(__aarch64__) info.z32 = openat(modfd, "zygisk/armeabi-v7a.so", O_RDONLY | O_CLOEXEC); info.z64 = openat(modfd, "zygisk/arm64-v8a.so", O_RDONLY | O_CLOEXEC); #elif defined(__i386__) info.z32 = openat(modfd, "zygisk/x86.so", O_RDONLY | O_CLOEXEC); #elif defined(__x86_64__) info.z32 = openat(modfd, "zygisk/x86.so", O_RDONLY | O_CLOEXEC); info.z64 = openat(modfd, "zygisk/x86_64.so", O_RDONLY | O_CLOEXEC); #elif defined(__riscv) info.z32 = -1; info.z64 = openat(modfd, "zygisk/riscv64.so", O_RDONLY | O_CLOEXEC); #else #error Unsupported ABI #endif unlinkat(modfd, "zygisk/unloaded", 0); } } else { // Ignore zygisk modules when zygisk is not enabled if (faccessat(modfd, "zygisk", F_OK, 0) == 0) { LOGI("%s: ignore\n", entry->d_name); return; } } info.name = entry->d_name; module_list->push_back(info); }); if (zygisk_enabled) { bool use_memfd = true; auto convert_to_memfd = [&](int fd) -> int { if (fd < 0) return -1; if (use_memfd) { int memfd = syscall(__NR_memfd_create, "jit-cache", MFD_CLOEXEC); if (memfd >= 0) { xsendfile(memfd, fd, nullptr, INT_MAX); close(fd); return memfd; } else { // memfd_create failed, just use what we had use_memfd = false; } } return fd; }; std::for_each(module_list->begin(), module_list->end(), [&](module_info &info) { info.z32 = convert_to_memfd(info.z32); #if defined(__LP64__) info.z64 = convert_to_memfd(info.z64); #endif }); } } void handle_modules() { prepare_modules(); collect_modules(false); exec_module_scripts("post-fs-data"); // Recollect modules (module scripts could remove itself) module_list->clear(); collect_modules(true); } static int check_rules_dir(char *buf, size_t sz) { int off = ssprintf(buf, sz, "%s/" PREINITMIRR, get_magisk_tmp()); struct stat st1{}; struct stat st2{}; if (xstat(buf, &st1) < 0 || xstat(MODULEROOT, &st2) < 0) return 0; if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) return 0; return off; } void disable_modules() { char buf[4096]; int off = check_rules_dir(buf, sizeof(buf)); foreach_module([&](int, dirent *entry, int modfd) { close(xopenat(modfd, "disable", O_RDONLY | O_CREAT | O_CLOEXEC, 0)); if (off) { ssprintf(buf + off, sizeof(buf) - off, "/%s/sepolicy.rule", entry->d_name); unlink(buf); } }); } void remove_modules() { char buf[4096]; int off = check_rules_dir(buf, sizeof(buf)); foreach_module([&](int, dirent *entry, int) { auto uninstaller = MODULEROOT + "/"s + entry->d_name + "/uninstall.sh"; if (access(uninstaller.data(), F_OK) == 0) exec_script(uninstaller.data()); if (off) { ssprintf(buf + off, sizeof(buf) - off, "/%s/sepolicy.rule", entry->d_name); unlink(buf); } }); rm_rf(MODULEROOT); } void exec_module_scripts(const char *stage) { vector<string_view> module_names; std::transform(module_list->begin(), module_list->end(), std::back_inserter(module_names), [](const module_info &info) -> string_view { return info.name; }); exec_module_scripts(stage, module_names); }
17,251
C++
.cpp
463
28.645788
108
0.533911
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11
db.cpp
topjohnwu_Magisk/native/src/core/db.cpp
#include <unistd.h> #include <dlfcn.h> #include <sys/stat.h> #include <consts.hpp> #include <base.hpp> #include <db.hpp> #include <core.hpp> #define DB_VERSION 12 using namespace std; struct sqlite3; static sqlite3 *mDB = nullptr; #define DBLOGV(...) //#define DBLOGV(...) LOGD("magiskdb: " __VA_ARGS__) // SQLite APIs #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ using sqlite3_callback = int (*)(void*, int, char**, char**); static int (*sqlite3_open_v2)(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs); static const char *(*sqlite3_errmsg)(sqlite3 *db); static int (*sqlite3_close)(sqlite3 *db); static void (*sqlite3_free)(void *v); static int (*sqlite3_exec)(sqlite3 *db, const char *sql, sqlite3_callback fn, void *v, char **errmsg); // Internal Android linker APIs static void (*android_get_LD_LIBRARY_PATH)(char *buffer, size_t buffer_size); static void (*android_update_LD_LIBRARY_PATH)(const char *ld_library_path); #define DLERR(ptr) if (!(ptr)) { \ LOGE("db: %s\n", dlerror()); \ return false; \ } #define DLOAD(handle, arg) {\ auto f = dlsym(handle, #arg); \ DLERR(f) \ *(void **) &(arg) = f; \ } #ifdef __LP64__ constexpr char apex_path[] = "/apex/com.android.runtime/lib64:/apex/com.android.art/lib64:/apex/com.android.i18n/lib64:"; #else constexpr char apex_path[] = "/apex/com.android.runtime/lib:/apex/com.android.art/lib:/apex/com.android.i18n/lib:"; #endif static int dl_init = 0; static bool dload_sqlite() { if (dl_init) return dl_init > 0; dl_init = -1; auto sqlite = dlopen("libsqlite.so", RTLD_LAZY); if (!sqlite) { // Should only happen on Android 10+ auto dl = dlopen("libdl_android.so", RTLD_LAZY); DLERR(dl); DLOAD(dl, android_get_LD_LIBRARY_PATH); DLOAD(dl, android_update_LD_LIBRARY_PATH); // Inject APEX into LD_LIBRARY_PATH char ld_path[4096]; memcpy(ld_path, apex_path, sizeof(apex_path)); constexpr int len = sizeof(apex_path) - 1; android_get_LD_LIBRARY_PATH(ld_path + len, sizeof(ld_path) - len); android_update_LD_LIBRARY_PATH(ld_path); sqlite = dlopen("libsqlite.so", RTLD_LAZY); // Revert LD_LIBRARY_PATH just in case android_update_LD_LIBRARY_PATH(ld_path + len); } DLERR(sqlite); DLOAD(sqlite, sqlite3_open_v2); DLOAD(sqlite, sqlite3_errmsg); DLOAD(sqlite, sqlite3_close); DLOAD(sqlite, sqlite3_exec); DLOAD(sqlite, sqlite3_free); dl_init = 1; return true; } int db_strings::get_idx(string_view key) const { int idx = 0; for (const char *k : DB_STRING_KEYS) { if (key == k) break; ++idx; } return idx; } db_settings::db_settings() { // Default settings data[ROOT_ACCESS] = ROOT_ACCESS_APPS_AND_ADB; data[SU_MULTIUSER_MODE] = MULTIUSER_MODE_OWNER_ONLY; data[SU_MNT_NS] = NAMESPACE_MODE_REQUESTER; data[DENYLIST_CONFIG] = false; data[ZYGISK_CONFIG] = MagiskD::get()->is_emulator(); data[BOOTLOOP_COUNT] = 0; } int db_settings::get_idx(string_view key) const { int idx = 0; for (const char *k : DB_SETTING_KEYS) { if (key == k) break; ++idx; } return idx; } static int ver_cb(void *ver, int, char **data, char **) { *((int *) ver) = parse_int(data[0]); return 0; } bool db_result::check_err() { if (!err.empty()) { LOGE("sqlite3_exec: %s\n", err.data()); return true; } return false; } static db_result sql_exec(sqlite3 *db, const char *sql, sqlite3_callback fn, void *v) { char *err = nullptr; sqlite3_exec(db, sql, fn, v, &err); if (err) { db_result r = err; sqlite3_free(err); return r; } return {}; } #define sql_exe_ret(...) if (auto r = sql_exec(__VA_ARGS__); !r) return r #define fn_run_ret(fn) if (auto r = fn(); !r) return r static db_result open_and_init_db(sqlite3 *&db) { if (!dload_sqlite()) return "Cannot load libsqlite.so"; int ret = sqlite3_open_v2(MAGISKDB, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nullptr); if (ret) return sqlite3_errmsg(db); int ver = 0; bool upgrade = false; sql_exe_ret(db, "PRAGMA user_version", ver_cb, &ver); if (ver > DB_VERSION) { // Don't support downgrading database sqlite3_close(db); return "Downgrading database is not supported"; } auto create_policy = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS policies " "(uid INT, policy INT, until INT, logging INT, " "notification INT, PRIMARY KEY(uid))", nullptr, nullptr); }; auto create_settings = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS settings " "(key TEXT, value INT, PRIMARY KEY(key))", nullptr, nullptr); }; auto create_strings = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS strings " "(key TEXT, value TEXT, PRIMARY KEY(key))", nullptr, nullptr); }; auto create_denylist = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS denylist " "(package_name TEXT, process TEXT, PRIMARY KEY(package_name, process))", nullptr, nullptr); }; // Database changelog: // // 0 - 6: DB stored in app private data. There are no longer any code in the project to // migrate these data, so no need to take any of these versions into consideration. // 7 : create table `hidelist` (process TEXT, PRIMARY KEY(process)) // 8 : add new column (package_name TEXT) to table `hidelist` // 9 : rebuild table `hidelist` to change primary key (PRIMARY KEY(package_name, process)) // 10: remove table `logs` // 11: remove table `hidelist` and create table `denylist` (same data structure) // 12: rebuild table `policies` to drop column `package_name` if (/* 0, 1, 2, 3, 4, 5, 6 */ ver <= 6) { fn_run_ret(create_policy); fn_run_ret(create_settings); fn_run_ret(create_strings); fn_run_ret(create_denylist); // Directly jump to latest ver = DB_VERSION; upgrade = true; } if (ver == 7) { sql_exe_ret(db, "BEGIN TRANSACTION;" "ALTER TABLE hidelist RENAME TO hidelist_tmp;" "CREATE TABLE IF NOT EXISTS hidelist " "(package_name TEXT, process TEXT, PRIMARY KEY(package_name, process));" "INSERT INTO hidelist SELECT process as package_name, process FROM hidelist_tmp;" "DROP TABLE hidelist_tmp;" "COMMIT;", nullptr, nullptr); // Directly jump to version 9 ver = 9; upgrade = true; } if (ver == 8) { sql_exe_ret(db, "BEGIN TRANSACTION;" "ALTER TABLE hidelist RENAME TO hidelist_tmp;" "CREATE TABLE IF NOT EXISTS hidelist " "(package_name TEXT, process TEXT, PRIMARY KEY(package_name, process));" "INSERT INTO hidelist SELECT * FROM hidelist_tmp;" "DROP TABLE hidelist_tmp;" "COMMIT;", nullptr, nullptr); ver = 9; upgrade = true; } if (ver == 9) { sql_exe_ret(db, "DROP TABLE IF EXISTS logs", nullptr, nullptr); ver = 10; upgrade = true; } if (ver == 10) { sql_exe_ret(db, "DROP TABLE IF EXISTS hidelist;" "DELETE FROM settings WHERE key='magiskhide';", nullptr, nullptr); fn_run_ret(create_denylist); ver = 11; upgrade = true; } if (ver == 11) { sql_exe_ret(db, "BEGIN TRANSACTION;" "ALTER TABLE policies RENAME TO policies_tmp;" "CREATE TABLE IF NOT EXISTS policies " "(uid INT, policy INT, until INT, logging INT, " "notification INT, PRIMARY KEY(uid));" "INSERT INTO policies " "SELECT uid, policy, until, logging, notification FROM policies_tmp;" "DROP TABLE policies_tmp;" "COMMIT;", nullptr, nullptr); ver = 12; upgrade = true; } if (upgrade) { // Set version char query[32]; sprintf(query, "PRAGMA user_version=%d", ver); sql_exe_ret(db, query, nullptr, nullptr); } return {}; } db_result db_exec(const char *sql) { if (mDB == nullptr) { auto res = open_and_init_db(mDB); if (res.check_err()) { // Open fails, remove and reconstruct unlink(MAGISKDB); res = open_and_init_db(mDB); if (!res) return res; } } if (mDB) { sql_exe_ret(mDB, sql, nullptr, nullptr); } return {}; } static int sqlite_db_row_callback(void *cb, int col_num, char **data, char **col_name) { auto &func = *static_cast<const db_row_cb*>(cb); db_row row; for (int i = 0; i < col_num; ++i) row[col_name[i]] = data[i]; return func(row) ? 0 : 1; } db_result db_exec(const char *sql, const db_row_cb &fn) { if (mDB == nullptr) { auto res = open_and_init_db(mDB); if (res.check_err()) { // Open fails, remove and reconstruct unlink(MAGISKDB); res = open_and_init_db(mDB); if (!res) return res; } } if (mDB) { sql_exe_ret(mDB, sql, sqlite_db_row_callback, (void *) &fn); } return {}; } int get_db_settings(db_settings &cfg, int key) { db_result res; auto settings_cb = [&](db_row &row) -> bool { cfg[row["key"]] = parse_int(row["value"]); DBLOGV("query %s=[%s]\n", row["key"].data(), row["value"].data()); return true; }; if (key >= 0) { char query[128]; ssprintf(query, sizeof(query), "SELECT * FROM settings WHERE key='%s'", DB_SETTING_KEYS[key]); res = db_exec(query, settings_cb); } else { res = db_exec("SELECT * FROM settings", settings_cb); } return res.check_err() ? 1 : 0; } int set_db_settings(int key, int value) { char sql[128]; ssprintf(sql, sizeof(sql), "INSERT OR REPLACE INTO settings VALUES ('%s', %d)", DB_SETTING_KEYS[key], value); return db_exec(sql).check_err() ? 1 : 0; } int get_db_strings(db_strings &str, int key) { db_result res; auto string_cb = [&](db_row &row) -> bool { str[row["key"]] = row["value"]; DBLOGV("query %s=[%s]\n", row["key"].data(), row["value"].data()); return true; }; if (key >= 0) { char query[128]; ssprintf(query, sizeof(query), "SELECT * FROM strings WHERE key='%s'", DB_STRING_KEYS[key]); res = db_exec(query, string_cb); } else { res = db_exec("SELECT * FROM strings", string_cb); } return res.check_err() ? 1 : 0; } void rm_db_strings(int key) { char query[128]; ssprintf(query, sizeof(query), "DELETE FROM strings WHERE key == '%s'", DB_STRING_KEYS[key]); db_exec(query).check_err(); } void exec_sql(owned_fd client) { string sql = read_string(client); auto res = db_exec(sql.data(), [fd = (int) client](db_row &row) -> bool { string out; bool first = true; for (auto it : row) { if (first) first = false; else out += '|'; out += it.first; out += '='; out += it.second; } write_string(fd, out); return true; }); write_int(client, 0); res.check_err(); }
11,999
C++
.cpp
342
27.847953
121
0.574701
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12
resetprop.cpp
topjohnwu_Magisk/native/src/core/resetprop/resetprop.cpp
#include <dlfcn.h> #include <sys/types.h> #include <vector> #include <map> #include <base.hpp> #include <core.hpp> #include <resetprop.hpp> #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_ #include <api/_system_properties.h> #include <system_properties/prop_info.h> using namespace std; #ifdef APPLET_STUB_MAIN #define system_property_set __system_property_set #define system_property_read(...) #define system_property_find __system_property_find #define system_property_read_callback __system_property_read_callback #define system_property_foreach __system_property_foreach #define system_property_wait __system_property_wait #else static int (*system_property_set)(const char*, const char*); static int (*system_property_read)(const prop_info*, char*, char*); static const prop_info *(*system_property_find)(const char*); static void (*system_property_read_callback)( const prop_info*, void (*)(void*, const char*, const char*, uint32_t), void*); static int (*system_property_foreach)(void (*)(const prop_info*, void*), void*); static bool (*system_property_wait)(const prop_info*, uint32_t, uint32_t*, const struct timespec*); #endif struct PropFlags { void setSkipSvc() { flags |= 1; } void setPersist() { flags |= (1 << 1); } void setContext() { flags |= (1 << 2); } void setPersistOnly() { flags |= (1 << 3); setPersist(); } void setWait() { flags |= (1 << 4); } bool isSkipSvc() const { return flags & 1; } bool isPersist() const { return flags & (1 << 1); } bool isContext() const { return flags & (1 << 2); } bool isPersistOnly() const { return flags & (1 << 3); } bool isWait() const { return flags & (1 << 4); } private: uint32_t flags = 0; }; [[noreturn]] static void usage(char* arg0) { fprintf(stderr, R"EOF(resetprop - System Property Manipulation Tool Usage: %s [flags] [arguments...] Read mode arguments: (no arguments) print all properties NAME get property of NAME Write mode arguments: NAME VALUE set property NAME as VALUE -f,--file FILE load and set properties from FILE -d,--delete NAME delete property Wait mode arguments (toggled with -w): NAME wait until property NAME changes NAME OLD_VALUE if value of property NAME is not OLD_VALUE, get value or else wait until property NAME changes General flags: -h,--help show this message -v print verbose output to stderr -w switch to wait mode Read mode flags: -p also read persistent props from storage -P only read persistent props from storage -Z get property context instead of value Write mode flags: -n set properties bypassing property_service -p always write persistent prop changes to storage )EOF", arg0); exit(1); } static bool check_legal_property_name(const char *name) { int namelen = strlen(name); if (namelen < 1) goto illegal; if (name[0] == '.') goto illegal; if (name[namelen - 1] == '.') goto illegal; /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */ /* Don't allow ".." to appear in a property name */ for (size_t i = 0; i < namelen; i++) { if (name[i] == '.') { // i=0 is guaranteed to never have a dot. See above. if (name[i-1] == '.') goto illegal; continue; } if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue; if (name[i] >= 'a' && name[i] <= 'z') continue; if (name[i] >= 'A' && name[i] <= 'Z') continue; if (name[i] >= '0' && name[i] <= '9') continue; goto illegal; } return true; illegal: LOGE("Illegal property name: [%s]\n", name); return false; } static void read_prop_with_cb(const prop_info *pi, void *cb) { if (system_property_read_callback) { auto callback = [](void *cb, const char *name, const char *value, uint32_t serial) { static_cast<prop_cb*>(cb)->exec(name, value, serial); }; system_property_read_callback(pi, callback, cb); } else { char name[PROP_NAME_MAX]; char value[PROP_VALUE_MAX]; name[0] = '\0'; value[0] = '\0'; system_property_read(pi, name, value); static_cast<prop_cb*>(cb)->exec(name, value, pi->serial); } } template<class StringType> struct prop_to_string : prop_cb { void exec(const char *, const char *value, uint32_t s) override { val = value; serial = s; } StringType val; uint32_t serial; }; template<> void prop_to_string<rust::String>::exec(const char *, const char *value, uint32_t s) { // We do not want to crash when values are not UTF-8 val = rust::String::lossy(value); serial = s; } static int set_prop(const char *name, const char *value, PropFlags flags) { if (!check_legal_property_name(name)) return 1; auto pi = const_cast<prop_info *>(__system_property_find(name)); // Delete existing read-only properties if they are or will be long properties, // which cannot directly go through __system_property_update if (str_starts(name, "ro.")) { if (pi != nullptr && (pi->is_long() || strlen(value) >= PROP_VALUE_MAX)) { // Skip pruning nodes as we will add it back ASAP __system_property_delete(name, false); pi = nullptr; } flags.setSkipSvc(); } const char *msg = flags.isSkipSvc() ? "direct modification" : "property_service"; int ret; if (pi != nullptr) { if (flags.isSkipSvc()) { ret = __system_property_update(pi, value, strlen(value)); } else { ret = system_property_set(name, value); } LOGD("resetprop: update prop [%s]: [%s] by %s\n", name, value, msg); } else { if (flags.isSkipSvc()) { ret = __system_property_add(name, strlen(name), value, strlen(value)); } else { ret = system_property_set(name, value); } LOGD("resetprop: create prop [%s]: [%s] by %s\n", name, value, msg); } // When bypassing property_service, persistent props won't be stored in storage. // Explicitly handle this situation. if (ret == 0 && flags.isSkipSvc() && flags.isPersist() && str_starts(name, "persist.")) { ret = persist_set_prop(name, value) ? 0 : 1; } if (ret) { LOGW("resetprop: set prop error\n"); } return ret; } template<class StringType> static StringType get_prop(const char *name, PropFlags flags) { if (!check_legal_property_name(name)) return {}; prop_to_string<StringType> cb; if (flags.isContext()) { auto context = __system_property_get_context(name) ?: ""; LOGD("resetprop: prop context [%s]: [%s]\n", name, context); cb.exec(name, context, -1); return cb.val; } if (!flags.isPersistOnly()) { if (auto pi = system_property_find(name)) { read_prop_with_cb(pi, &cb); LOGD("resetprop: get prop [%s]: [%s]\n", name, cb.val.c_str()); } } if (cb.val.empty() && flags.isPersist() && str_starts(name, "persist.")) persist_get_prop(name, cb); if (cb.val.empty()) LOGD("resetprop: prop [%s] does not exist\n", name); return cb.val; } template<class StringType> static StringType wait_prop(const char *name, const char *old_value) { if (!check_legal_property_name(name)) return {}; const prop_info *pi; auto serial = __system_property_area_serial(); while (!(pi = system_property_find(name))) { LOGD("resetprop: waiting for prop [%s] to exist\n", name); system_property_wait(nullptr, serial, &serial, nullptr); } prop_to_string<StringType> cb; read_prop_with_cb(pi, &cb); while (old_value == nullptr || cb.val == old_value) { LOGD("resetprop: waiting for prop [%s]\n", name); uint32_t new_serial; system_property_wait(pi, cb.serial, &new_serial, nullptr); read_prop_with_cb(pi, &cb); if (old_value == nullptr) break; } LOGD("resetprop: get prop [%s]: [%s]\n", name, cb.val.c_str()); return cb.val; } static void print_props(PropFlags flags) { prop_list list; prop_collector collector(list); if (!flags.isPersistOnly()) system_property_foreach(read_prop_with_cb, &collector); if (flags.isPersist()) persist_get_props(collector); for (auto &[key, val] : list) { const char *v = flags.isContext() ? (__system_property_get_context(key.data()) ?: "") : val.data(); printf("[%s]: [%s]\n", key.data(), v); } } static int delete_prop(const char *name, PropFlags flags) { if (!check_legal_property_name(name)) return 1; LOGD("resetprop: delete prop [%s]\n", name); int ret = __system_property_delete(name, true); if (flags.isPersist() && str_starts(name, "persist.")) { if (persist_delete_prop(name)) ret = 0; } return ret; } static void load_file(const char *filename, PropFlags flags) { LOGD("resetprop: Parse prop file [%s]\n", filename); parse_prop_file(filename, [=](auto key, auto val) -> bool { set_prop(key.data(), val.data(), flags); return true; }); } struct Initialize { Initialize() { #ifndef APPLET_STUB_MAIN #define DLOAD(name) (*(void **) &name = dlsym(RTLD_DEFAULT, "__" #name)) // Load platform implementations DLOAD(system_property_set); DLOAD(system_property_read); DLOAD(system_property_find); DLOAD(system_property_read_callback); DLOAD(system_property_foreach); DLOAD(system_property_wait); #undef DLOAD if (system_property_wait == nullptr) { // The platform API only exist on API 26+ system_property_wait = __system_property_wait; } #endif if (__system_properties_init()) { LOGE("resetprop: __system_properties_init error\n"); } } }; static void InitOnce() { static struct Initialize init; } #define consume_next(val) \ if (argc != 2) usage(argv0); \ val = argv[1]; \ stop_parse = true; \ int resetprop_main(int argc, char *argv[]) { PropFlags flags; char *argv0 = argv[0]; set_log_level_state(LogLevel::Debug, false); const char *prop_file = nullptr; const char *prop_to_rm = nullptr; --argc; ++argv; // Parse flags and -- options while (argc && argv[0][0] == '-') { bool stop_parse = false; for (int idx = 1; true; ++idx) { switch (argv[0][idx]) { case '-': if (argv[0] == "--file"sv) { consume_next(prop_file); } else if (argv[0] == "--delete"sv) { consume_next(prop_to_rm); } else { usage(argv0); } break; case 'd': consume_next(prop_to_rm); continue; case 'f': consume_next(prop_file); continue; case 'n': flags.setSkipSvc(); continue; case 'p': flags.setPersist(); continue; case 'P': flags.setPersistOnly(); continue; case 'v': set_log_level_state(LogLevel::Debug, true); continue; case 'Z': flags.setContext(); continue; case 'w': flags.setWait(); continue; case '\0': break; default: usage(argv0); } break; } --argc; ++argv; if (stop_parse) break; } InitOnce(); if (prop_to_rm) { return delete_prop(prop_to_rm, flags); } if (prop_file) { load_file(prop_file, flags); return 0; } if (flags.isWait()) { if (argc == 0) usage(argv0); auto val = wait_prop<string>(argv[0], argv[1]); if (val.empty()) return 1; printf("%s\n", val.data()); return 0; } switch (argc) { case 0: print_props(flags); return 0; case 1: { auto val = get_prop<string>(argv[0], flags); if (val.empty()) return 1; printf("%s\n", val.data()); return 0; } case 2: return set_prop(argv[0], argv[1], flags); default: usage(argv0); } } /*************** * Public APIs ****************/ template<class StringType> static StringType get_prop_impl(const char *name, bool persist) { InitOnce(); PropFlags flags; if (persist) flags.setPersist(); return get_prop<StringType>(name, flags); } rust::String get_prop_rs(const char *name, bool persist) { return get_prop_impl<rust::String>(name, persist); } string get_prop(const char *name, bool persist) { return get_prop_impl<string>(name, persist); } int delete_prop(const char *name, bool persist) { InitOnce(); PropFlags flags; if (persist) flags.setPersist(); return delete_prop(name, flags); } int set_prop(const char *name, const char *value, bool skip_svc) { InitOnce(); PropFlags flags; if (skip_svc) flags.setSkipSvc(); return set_prop(name, value, flags); } void load_prop_file(const char *filename, bool skip_svc) { InitOnce(); PropFlags flags; if (skip_svc) flags.setSkipSvc(); load_file(filename, flags); }
13,763
C++
.cpp
395
28.124051
99
0.580245
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13
su_daemon.cpp
topjohnwu_Magisk/native/src/core/su/su_daemon.cpp
#include <unistd.h> #include <fcntl.h> #include <pwd.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include <selinux.hpp> #include "su.hpp" #include "pts.hpp" using namespace std; static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER; static shared_ptr<su_info> cached; su_info::su_info(int uid) : uid(uid), eval_uid(-1), access(DEFAULT_SU_ACCESS), mgr_uid(-1), timestamp(0), _lock(PTHREAD_MUTEX_INITIALIZER) {} su_info::~su_info() { pthread_mutex_destroy(&_lock); } mutex_guard su_info::lock() { return mutex_guard(_lock); } bool su_info::is_fresh() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); long current = ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; return current - timestamp < 3000; /* 3 seconds */ } void su_info::refresh() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); timestamp = ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; } void su_info::check_db() { eval_uid = uid; get_db_settings(cfg); // Check multiuser settings switch (cfg[SU_MULTIUSER_MODE]) { case MULTIUSER_MODE_OWNER_ONLY: if (to_user_id(uid) != 0) { eval_uid = -1; access = NO_SU_ACCESS; } break; case MULTIUSER_MODE_OWNER_MANAGED: eval_uid = to_app_id(uid); break; case MULTIUSER_MODE_USER: default: break; } if (eval_uid > 0) { char query[256]; ssprintf(query, sizeof(query), "SELECT policy, logging, notification FROM policies " "WHERE uid=%d AND (until=0 OR until>%li)", eval_uid, time(nullptr)); auto res = db_exec(query, [&](db_row &row) -> bool { access.policy = (policy_t) parse_int(row["policy"]); access.log = parse_int(row["logging"]); access.notify = parse_int(row["notification"]); LOGD("magiskdb: query policy=[%d] log=[%d] notify=[%d]\n", access.policy, access.log, access.notify); return true; }); if (res.check_err()) return; } // We need to check our manager if (access.log || access.notify) { mgr_uid = get_manager(to_user_id(eval_uid), &mgr_pkg, true); } } bool uid_granted_root(int uid) { if (uid == AID_ROOT) return true; db_settings cfg; get_db_settings(cfg); // Check user root access settings switch (cfg[ROOT_ACCESS]) { case ROOT_ACCESS_DISABLED: return false; case ROOT_ACCESS_APPS_ONLY: if (uid == AID_SHELL) return false; break; case ROOT_ACCESS_ADB_ONLY: if (uid != AID_SHELL) return false; break; case ROOT_ACCESS_APPS_AND_ADB: break; } // Check multiuser settings switch (cfg[SU_MULTIUSER_MODE]) { case MULTIUSER_MODE_OWNER_ONLY: if (to_user_id(uid) != 0) return false; break; case MULTIUSER_MODE_OWNER_MANAGED: uid = to_app_id(uid); break; case MULTIUSER_MODE_USER: default: break; } bool granted = false; char query[256]; ssprintf(query, sizeof(query), "SELECT policy FROM policies WHERE uid=%d AND (until=0 OR until>%li)", uid, time(nullptr)); auto res = db_exec(query, [&](db_row &row) -> bool { granted = parse_int(row["policy"]) == ALLOW; return true; }); if (res.check_err()) return false; return granted; } void prune_su_access() { cached.reset(); vector<bool> app_no_list = get_app_no_list(); vector<int> rm_uids; auto res = db_exec("SELECT uid FROM policies", [&](db_row &row) -> bool { int uid = parse_int(row["uid"]); int app_id = to_app_id(uid); if (app_id >= AID_APP_START && app_id <= AID_APP_END) { int app_no = app_id - AID_APP_START; if (app_no >= app_no_list.size() || !app_no_list[app_no]) { // The app_id is no longer installed rm_uids.push_back(uid); } } return true; }); if (res.check_err()) return; for (int uid : rm_uids) { char query[256]; ssprintf(query, sizeof(query), "DELETE FROM policies WHERE uid == %d", uid); db_exec(query).check_err(); } } static shared_ptr<su_info> get_su_info(unsigned uid) { if (uid == AID_ROOT) { auto info = make_shared<su_info>(uid); info->access = SILENT_SU_ACCESS; return info; } shared_ptr<su_info> info; { mutex_guard lock(cache_lock); if (!cached || cached->uid != uid || !cached->is_fresh()) cached = make_shared<su_info>(uid); cached->refresh(); info = cached; } mutex_guard lock = info->lock(); if (info->access.policy == QUERY) { // Not cached, get data from database info->check_db(); // If it's the manager, allow it silently if (to_app_id(info->uid) == to_app_id(info->mgr_uid)) { info->access = SILENT_SU_ACCESS; return info; } // Check su access settings switch (info->cfg[ROOT_ACCESS]) { case ROOT_ACCESS_DISABLED: LOGW("Root access is disabled!\n"); info->access = NO_SU_ACCESS; break; case ROOT_ACCESS_ADB_ONLY: if (info->uid != AID_SHELL) { LOGW("Root access limited to ADB only!\n"); info->access = NO_SU_ACCESS; } break; case ROOT_ACCESS_APPS_ONLY: if (info->uid == AID_SHELL) { LOGW("Root access is disabled for ADB!\n"); info->access = NO_SU_ACCESS; } break; case ROOT_ACCESS_APPS_AND_ADB: default: break; } if (info->access.policy != QUERY) return info; // If still not determined, check if manager exists if (info->mgr_uid < 0) { info->access = NO_SU_ACCESS; return info; } } return info; } // Set effective uid back to root, otherwise setres[ug]id will fail if uid isn't root static void set_identity(uid_t uid, const std::vector<uid_t> &groups) { if (seteuid(0)) { PLOGE("seteuid (root)"); } gid_t gid; if (groups.size() > 0) { if (setgroups(groups.size(), groups.data())) { PLOGE("setgroups"); } gid = groups[0]; } else { gid = uid; } if (setresgid(gid, gid, gid)) { PLOGE("setresgid (%u)", uid); } if (setresuid(uid, uid, uid)) { PLOGE("setresuid (%u)", uid); } } void su_daemon_handler(int client, const sock_cred *cred) { LOGD("su: request from uid=[%d], pid=[%d], client=[%d]\n", cred->uid, cred->pid, client); su_context ctx = { .info = get_su_info(cred->uid), .req = su_request(), .pid = cred->pid }; // Read su_request if (xxread(client, &ctx.req, sizeof(su_req_base)) < 0 || !read_string(client, ctx.req.shell) || !read_string(client, ctx.req.command) || !read_string(client, ctx.req.context) || !read_vector(client, ctx.req.gids)) { LOGW("su: remote process probably died, abort\n"); ctx.info.reset(); write_int(client, DENY); close(client); return; } // If still not determined, ask manager if (ctx.info->access.policy == QUERY) { int fd = app_request(ctx); if (fd < 0) { ctx.info->access.policy = DENY; } else { int ret = read_int_be(fd); ctx.info->access.policy = ret < 0 ? DENY : static_cast<policy_t>(ret); close(fd); } } if (ctx.info->access.log) app_log(ctx); else if (ctx.info->access.notify) app_notify(ctx); // Fail fast if (ctx.info->access.policy == DENY) { LOGW("su: request rejected (%u)\n", ctx.info->uid); ctx.info.reset(); write_int(client, DENY); close(client); return; } // Fork a child root process // // The child process will need to setsid, open a pseudo-terminal // if needed, and eventually exec shell. // The parent process will wait for the result and // send the return code back to our client. if (int child = xfork(); child) { ctx.info.reset(); // Wait result LOGD("su: waiting child pid=[%d]\n", child); int status, code; if (waitpid(child, &status, 0) > 0) code = WEXITSTATUS(status); else code = -1; LOGD("su: return code=[%d]\n", code); write(client, &code, sizeof(code)); close(client); return; } LOGD("su: fork handler\n"); // Abort upon any error occurred exit_on_error(true); // ack write_int(client, 0); // Become session leader xsetsid(); // The FDs for each of the streams int infd = recv_fd(client); int outfd = recv_fd(client); int errfd = recv_fd(client); // App need a PTY if (read_int(client)) { string pts; string ptmx; auto magiskpts = get_magisk_tmp() + "/"s SHELLPTS; if (access(magiskpts.data(), F_OK)) { pts = "/dev/pts"; ptmx = "/dev/ptmx"; } else { pts = magiskpts; ptmx = magiskpts + "/ptmx"; } int ptmx_fd = xopen(ptmx.data(), O_RDWR); grantpt(ptmx_fd); unlockpt(ptmx_fd); int pty_num = get_pty_num(ptmx_fd); if (pty_num < 0) { // Kernel issue? Fallback to /dev/pts close(ptmx_fd); pts = "/dev/pts"; ptmx_fd = xopen("/dev/ptmx", O_RDWR); grantpt(ptmx_fd); unlockpt(ptmx_fd); pty_num = get_pty_num(ptmx_fd); } send_fd(client, ptmx_fd); close(ptmx_fd); string pts_slave = pts + "/" + to_string(pty_num); LOGD("su: pts_slave=[%s]\n", pts_slave.data()); // Opening the TTY has to occur after the // fork() and setsid() so that it becomes // our controlling TTY and not the daemon's int ptsfd = xopen(pts_slave.data(), O_RDWR); if (infd < 0) infd = ptsfd; if (outfd < 0) outfd = ptsfd; if (errfd < 0) errfd = ptsfd; } // Swap out stdin, stdout, stderr xdup2(infd, STDIN_FILENO); xdup2(outfd, STDOUT_FILENO); xdup2(errfd, STDERR_FILENO); close(infd); close(outfd); close(errfd); close(client); // Handle namespaces if (ctx.req.target == -1) ctx.req.target = ctx.pid; else if (ctx.req.target == 0) ctx.info->cfg[SU_MNT_NS] = NAMESPACE_MODE_GLOBAL; else if (ctx.info->cfg[SU_MNT_NS] == NAMESPACE_MODE_GLOBAL) ctx.info->cfg[SU_MNT_NS] = NAMESPACE_MODE_REQUESTER; switch (ctx.info->cfg[SU_MNT_NS]) { case NAMESPACE_MODE_GLOBAL: LOGD("su: use global namespace\n"); break; case NAMESPACE_MODE_REQUESTER: LOGD("su: use namespace of pid=[%d]\n", ctx.req.target); if (switch_mnt_ns(ctx.req.target)) LOGD("su: setns failed, fallback to global\n"); break; case NAMESPACE_MODE_ISOLATE: LOGD("su: use new isolated namespace\n"); switch_mnt_ns(ctx.req.target); xunshare(CLONE_NEWNS); xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr); break; } const char *argv[4] = { nullptr }; argv[0] = ctx.req.login ? "-" : ctx.req.shell.data(); if (!ctx.req.command.empty()) { argv[1] = "-c"; argv[2] = ctx.req.command.data(); } // Setup environment umask(022); char path[32]; ssprintf(path, sizeof(path), "/proc/%d/cwd", ctx.pid); char cwd[4096]; if (realpath(path, cwd, sizeof(cwd)) > 0) chdir(cwd); ssprintf(path, sizeof(path), "/proc/%d/environ", ctx.pid); auto env = full_read(path); clearenv(); for (size_t pos = 0; pos < env.size(); ++pos) { putenv(env.data() + pos); pos = env.find_first_of('\0', pos); if (pos == std::string::npos) break; } if (!ctx.req.keepenv) { struct passwd *pw; pw = getpwuid(ctx.req.uid); if (pw) { setenv("HOME", pw->pw_dir, 1); setenv("USER", pw->pw_name, 1); setenv("LOGNAME", pw->pw_name, 1); setenv("SHELL", ctx.req.shell.data(), 1); } } // Unblock all signals sigset_t block_set; sigemptyset(&block_set); sigprocmask(SIG_SETMASK, &block_set, nullptr); if (!ctx.req.context.empty()) { auto f = xopen_file("/proc/self/attr/exec", "we"); if (f) fprintf(f.get(), "%s", ctx.req.context.data()); } set_identity(ctx.req.uid, ctx.req.gids); execvp(ctx.req.shell.data(), (char **) argv); fprintf(stderr, "Cannot execute %s: %s\n", ctx.req.shell.data(), strerror(errno)); PLOGE("exec"); }
13,266
C++
.cpp
408
24.583333
93
0.548637
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
14
connect.cpp
topjohnwu_Magisk/native/src/core/su/connect.cpp
#include <sys/types.h> #include <sys/wait.h> #include <base.hpp> #include <selinux.hpp> #include <consts.hpp> #include "su.hpp" using namespace std; #define CALL_PROVIDER \ "/system/bin/app_process", "/system/bin", "com.android.commands.content.Content", \ "call", "--uri", target, "--user", user, "--method", action #define START_ACTIVITY \ "/system/bin/app_process", "/system/bin", "com.android.commands.am.Am", \ "start", "-p", target, "--user", user, "-a", "android.intent.action.VIEW", \ "-f", "0x18800020", "--es", "action", action // 0x18800020 = FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_MULTIPLE_TASK| // FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|FLAG_INCLUDE_STOPPED_PACKAGES #define get_cmd(to) \ ((to).command.empty() ? \ ((to).shell.empty() ? DEFAULT_SHELL : (to).shell.data()) : \ (to).command.data()) class Extra { const char *key; enum { INT, BOOL, STRING, INTLIST, } type; union { int int_val; bool bool_val; const char *str_val; const vector<uint32_t> *intlist_val; }; string str; public: Extra(const char *k, int v): key(k), type(INT), int_val(v) {} Extra(const char *k, bool v): key(k), type(BOOL), bool_val(v) {} Extra(const char *k, const char *v): key(k), type(STRING), str_val(v) {} Extra(const char *k, const vector<uint32_t> *v): key(k), type(INTLIST), intlist_val(v) {} void add_intent(vector<const char *> &vec) { const char *val; switch (type) { case INT: vec.push_back("--ei"); str = to_string(int_val); val = str.data(); break; case BOOL: vec.push_back("--ez"); val = bool_val ? "true" : "false"; break; case STRING: vec.push_back("--es"); val = str_val; break; case INTLIST: vec.push_back("--es"); for (auto i : *intlist_val) { str += to_string(i); str += ","; } if (!str.empty()) str.pop_back(); val = str.data(); break; } vec.push_back(key); vec.push_back(val); } void add_bind(vector<const char *> &vec) { char buf[32]; str = key; switch (type) { case INT: str += ":i:"; ssprintf(buf, sizeof(buf), "%d", int_val); str += buf; break; case BOOL: str += ":b:"; str += bool_val ? "true" : "false"; break; case STRING: str += ":s:"; if (SDK_INT >= 30) { string tmp = str_val; replace_all(tmp, "\\", "\\\\"); replace_all(tmp, ":", "\\:"); str += tmp; } else { str += str_val; } break; case INTLIST: str += ":s:"; for (auto i : *intlist_val) { str += to_string(i); str += ","; } if (str.back() == ',') str.pop_back(); break; } vec.push_back("--extra"); vec.push_back(str.data()); } }; static bool check_no_error(int fd) { char buf[1024]; auto out = xopen_file(fd, "r"); while (fgets(buf, sizeof(buf), out.get())) { if (strncasecmp(buf, "Error", 5) == 0) { LOGD("exec_cmd: %s\n", buf); return false; } } return true; } static void exec_cmd(const char *action, vector<Extra> &data, const shared_ptr<su_info> &info, bool provider = true) { char target[128]; char user[4]; ssprintf(user, sizeof(user), "%d", to_user_id(info->eval_uid)); // First try content provider call method if (provider) { ssprintf(target, sizeof(target), "content://%s.provider", info->mgr_pkg.data()); vector<const char *> args{ CALL_PROVIDER }; for (auto &e : data) { e.add_bind(args); } args.push_back(nullptr); exec_t exec { .err = true, .fd = -1, .pre_exec = [] { setenv("CLASSPATH", "/system/framework/content.jar", 1); }, .argv = args.data() }; exec_command_sync(exec); if (check_no_error(exec.fd)) return; } // Then try start activity with package name strscpy(target, info->mgr_pkg.data(), sizeof(target)); vector<const char *> args{ START_ACTIVITY }; for (auto &e : data) { e.add_intent(args); } args.push_back(nullptr); exec_t exec { .fd = -2, .pre_exec = [] { setenv("CLASSPATH", "/system/framework/am.jar", 1); }, .fork = fork_dont_care, .argv = args.data() }; exec_command(exec); } void app_log(const su_context &ctx) { if (fork_dont_care() == 0) { vector<Extra> extras; extras.reserve(9); extras.emplace_back("from.uid", ctx.info->uid); extras.emplace_back("to.uid", static_cast<int>(ctx.req.uid)); extras.emplace_back("pid", ctx.pid); extras.emplace_back("policy", ctx.info->access.policy); extras.emplace_back("target", ctx.req.target); extras.emplace_back("context", ctx.req.context.data()); extras.emplace_back("gids", &ctx.req.gids); extras.emplace_back("command", get_cmd(ctx.req)); extras.emplace_back("notify", (bool) ctx.info->access.notify); exec_cmd("log", extras, ctx.info); exit(0); } } void app_notify(const su_context &ctx) { if (fork_dont_care() == 0) { vector<Extra> extras; extras.reserve(3); extras.emplace_back("from.uid", ctx.info->uid); extras.emplace_back("pid", ctx.pid); extras.emplace_back("policy", ctx.info->access.policy); exec_cmd("notify", extras, ctx.info); exit(0); } } int app_request(const su_context &ctx) { // Create FIFO char fifo[64]; ssprintf(fifo, sizeof(fifo), "%s/" INTLROOT "/su_request_%d", get_magisk_tmp(), ctx.pid); mkfifo(fifo, 0600); chown(fifo, ctx.info->mgr_uid, ctx.info->mgr_uid); setfilecon(fifo, MAGISK_FILE_CON); // Send request vector<Extra> extras; extras.reserve(3); extras.emplace_back("fifo", fifo); extras.emplace_back("uid", ctx.info->eval_uid); extras.emplace_back("pid", ctx.pid); exec_cmd("request", extras, ctx.info, false); // Wait for data input for at most 70 seconds // Open with O_RDWR to prevent FIFO open block int fd = xopen(fifo, O_RDWR | O_CLOEXEC); struct pollfd pfd = { .fd = fd, .events = POLLIN }; if (xpoll(&pfd, 1, 70 * 1000) <= 0) { close(fd); fd = -1; } unlink(fifo); return fd; }
6,835
C++
.cpp
211
24.49763
93
0.530445
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16
su.cpp
topjohnwu_Magisk/native/src/core/su/su.cpp
/* * Copyright 2017 - 2023, John Wu (@topjohnwu) * Copyright 2015, Pierre-Hugues Husson <phh@phh.me> * Copyright 2010, Adam Shanks (@ChainsDD) * Copyright 2008, Zinx Verituse (@zinxv) */ #include <unistd.h> #include <getopt.h> #include <fcntl.h> #include <pwd.h> #include <sched.h> #include <sys/types.h> #include <sys/stat.h> #include <consts.hpp> #include <base.hpp> #include <flags.h> #include "su.hpp" #include "pts.hpp" int quit_signals[] = { SIGALRM, SIGABRT, SIGHUP, SIGPIPE, SIGQUIT, SIGTERM, SIGINT, 0 }; [[noreturn]] static void usage(int status) { FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr; fprintf(stream, "MagiskSU\n\n" "Usage: su [options] [-] [user [argument...]]\n\n" "Options:\n" " -c, --command COMMAND Pass COMMAND to the invoked shell\n" " -g, --group GROUP Specify the primary group\n" " -G, --supp-group GROUP Specify a supplementary group.\n" " The first specified supplementary group is also used\n" " as a primary group if the option -g is not specified.\n" " -Z, --context CONTEXT Change SELinux context\n" " -t, --target PID PID to take mount namespace from\n" " -h, --help Display this help message and exit\n" " -, -l, --login Pretend the shell to be a login shell\n" " -m, -p,\n" " --preserve-environment Preserve the entire environment\n" " -s, --shell SHELL Use SHELL instead of the default " DEFAULT_SHELL "\n" " -v, --version Display version number and exit\n" " -V Display version code and exit\n" " -mm, -M,\n" " --mount-master Force run in the global mount namespace\n\n"); exit(status); } static void sighandler(int sig) { restore_stdin(); // Assume we'll only be called before death // See note before sigaction() in set_stdin_raw() // // Now, close all standard I/O to cause the pumps // to exit so we can continue and retrieve the exit // code close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); // Put back all the default handlers struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = SIG_DFL; for (int i = 0; quit_signals[i]; ++i) { sigaction(quit_signals[i], &act, nullptr); } } static void setup_sighandlers(void (*handler)(int)) { struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = handler; for (int i = 0; quit_signals[i]; ++i) { sigaction(quit_signals[i], &act, nullptr); } } int su_client_main(int argc, char *argv[]) { int c; struct option long_opts[] = { { "command", required_argument, nullptr, 'c' }, { "help", no_argument, nullptr, 'h' }, { "login", no_argument, nullptr, 'l' }, { "preserve-environment", no_argument, nullptr, 'p' }, { "shell", required_argument, nullptr, 's' }, { "version", no_argument, nullptr, 'v' }, { "context", required_argument, nullptr, 'Z' }, { "mount-master", no_argument, nullptr, 'M' }, { "target", required_argument, nullptr, 't' }, { "group", required_argument, nullptr, 'g' }, { "supp-group", required_argument, nullptr, 'G' }, { nullptr, 0, nullptr, 0 }, }; su_request su_req; for (int i = 0; i < argc; i++) { // Replace -cn and -z with -Z for backwards compatibility if (strcmp(argv[i], "-cn") == 0 || strcmp(argv[i], "-z") == 0) strcpy(argv[i], "-Z"); // Replace -mm with -M for supporting getopt_long else if (strcmp(argv[i], "-mm") == 0) strcpy(argv[i], "-M"); } while ((c = getopt_long(argc, argv, "c:hlmps:VvuZ:Mt:g:G:", long_opts, nullptr)) != -1) { switch (c) { case 'c': for (int i = optind - 1; i < argc; ++i) { if (!su_req.command.empty()) su_req.command += ' '; su_req.command += argv[i]; } optind = argc; break; case 'h': usage(EXIT_SUCCESS); case 'l': su_req.login = true; break; case 'm': case 'p': su_req.keepenv = true; break; case 's': su_req.shell = optarg; break; case 'V': printf("%d\n", MAGISK_VER_CODE); exit(EXIT_SUCCESS); case 'v': printf("%s\n", MAGISK_VERSION ":MAGISKSU"); exit(EXIT_SUCCESS); case 'Z': su_req.context = optarg; break; case 'M': case 't': if (su_req.target != -1) { fprintf(stderr, "Can't use -M and -t at the same time\n"); usage(EXIT_FAILURE); } if (optarg == nullptr) { su_req.target = 0; } else { su_req.target = parse_int(optarg); if (*optarg == '-' || su_req.target == -1) { fprintf(stderr, "Invalid PID: %s\n", optarg); usage(EXIT_FAILURE); } } break; case 'g': case 'G': if (int gid = parse_int(optarg); gid >= 0) { su_req.gids.insert(c == 'g' ? su_req.gids.begin() : su_req.gids.end(), gid); } else { fprintf(stderr, "Invalid GID: %s\n", optarg); usage(EXIT_FAILURE); } break; default: /* Bionic getopt_long doesn't terminate its error output by newline */ fprintf(stderr, "\n"); usage(2); } } if (optind < argc && strcmp(argv[optind], "-") == 0) { su_req.login = true; optind++; } /* username or uid */ if (optind < argc) { struct passwd *pw; pw = getpwnam(argv[optind]); if (pw) su_req.uid = pw->pw_uid; else su_req.uid = parse_int(argv[optind]); optind++; } int ptmx, fd; // Connect to client fd = connect_daemon(+RequestCode::SUPERUSER); // Send su_request xwrite(fd, &su_req, sizeof(su_req_base)); write_string(fd, su_req.shell); write_string(fd, su_req.command); write_string(fd, su_req.context); write_vector(fd, su_req.gids); // Wait for ack from daemon if (read_int(fd)) { // Fast fail fprintf(stderr, "%s\n", strerror(EACCES)); return EACCES; } // Determine which one of our streams are attached to a TTY int atty = 0; if (isatty(STDIN_FILENO)) atty |= ATTY_IN; if (isatty(STDOUT_FILENO)) atty |= ATTY_OUT; if (isatty(STDERR_FILENO)) atty |= ATTY_ERR; // Send stdin send_fd(fd, (atty & ATTY_IN) ? -1 : STDIN_FILENO); // Send stdout send_fd(fd, (atty & ATTY_OUT) ? -1 : STDOUT_FILENO); // Send stderr send_fd(fd, (atty & ATTY_ERR) ? -1 : STDERR_FILENO); if (atty) { // We need a PTY. Get one. write_int(fd, 1); ptmx = recv_fd(fd); } else { write_int(fd, 0); } if (atty) { setup_sighandlers(sighandler); watch_sigwinch_async(STDOUT_FILENO, ptmx); pump_stdin_async(ptmx); pump_stdout_blocking(ptmx); } // Get the exit code int code = read_int(fd); close(fd); return code; }
8,039
C++
.cpp
215
28.376744
96
0.496153
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
17
cli.cpp
topjohnwu_Magisk/native/src/core/deny/cli.cpp
#include <sys/wait.h> #include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include "deny.hpp" using namespace std; [[noreturn]] static void usage() { fprintf(stderr, R"EOF(DenyList Config CLI Usage: magisk --denylist [action [arguments...] ] Actions: status Return the enforcement status enable Enable denylist enforcement disable Disable denylist enforcement add PKG [PROC] Add a new target to the denylist rm PKG [PROC] Remove target(s) from the denylist ls Print the current denylist exec CMDs... Execute commands in isolated mount namespace and do all unmounts )EOF"); exit(1); } void denylist_handler(int client, const sock_cred *cred) { if (client < 0) { revert_unmount(); return; } int req = read_int(client); int res = DenyResponse::ERROR; switch (req) { case DenyRequest::ENFORCE: res = enable_deny(); break; case DenyRequest::DISABLE: res = disable_deny(); break; case DenyRequest::ADD: res = add_list(client); break; case DenyRequest::REMOVE: res = rm_list(client); break; case DenyRequest::LIST: ls_list(client); return; case DenyRequest::STATUS: res = denylist_enforced ? DenyResponse::ENFORCED : DenyResponse::NOT_ENFORCED; break; default: // Unknown request code break; } write_int(client, res); close(client); } int denylist_cli(int argc, char **argv) { if (argc < 2) usage(); int req; if (argv[1] == "enable"sv) req = DenyRequest::ENFORCE; else if (argv[1] == "disable"sv) req = DenyRequest::DISABLE; else if (argv[1] == "add"sv) req = DenyRequest::ADD; else if (argv[1] == "rm"sv) req = DenyRequest::REMOVE; else if (argv[1] == "ls"sv) req = DenyRequest::LIST; else if (argv[1] == "status"sv) req = DenyRequest::STATUS; else if (argv[1] == "exec"sv && argc > 2) { xunshare(CLONE_NEWNS); xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr); revert_unmount(); execvp(argv[2], argv + 2); exit(1); } else { usage(); } // Send request int fd = connect_daemon(+RequestCode::DENYLIST); write_int(fd, req); if (req == DenyRequest::ADD || req == DenyRequest::REMOVE) { write_string(fd, argv[2]); write_string(fd, argv[3] ? argv[3] : ""); } // Get response int res = read_int(fd); if (res < 0 || res >= DenyResponse::END) res = DenyResponse::ERROR; switch (res) { case DenyResponse::NOT_ENFORCED: fprintf(stderr, "Denylist is not enforced\n"); goto return_code; case DenyResponse::ENFORCED: fprintf(stderr, "Denylist is enforced\n"); goto return_code; case DenyResponse::ITEM_EXIST: fprintf(stderr, "Target already exists in denylist\n"); goto return_code; case DenyResponse::ITEM_NOT_EXIST: fprintf(stderr, "Target does not exist in denylist\n"); goto return_code; case DenyResponse::NO_NS: fprintf(stderr, "The kernel does not support mount namespace\n"); goto return_code; case DenyResponse::INVALID_PKG: fprintf(stderr, "Invalid package / process name\n"); goto return_code; case DenyResponse::ERROR: fprintf(stderr, "deny: Daemon error\n"); return -1; case DenyResponse::OK: break; default: __builtin_unreachable(); } if (req == DenyRequest::LIST) { string out; for (;;) { read_string(fd, out); if (out.empty()) break; printf("%s\n", out.data()); } } return_code: return req == DenyRequest::STATUS ? res != DenyResponse::ENFORCED : res != DenyResponse::OK; }
3,953
C++
.cpp
130
23.907692
96
0.5948
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
18
logcat.cpp
topjohnwu_Magisk/native/src/core/deny/logcat.cpp
#include <unistd.h> #include <string> #include <cinttypes> #include <android/log.h> #include <sys/syscall.h> #include <base.hpp> #include "deny.hpp" using namespace std; struct logger_entry { uint16_t len; /* length of the payload */ uint16_t hdr_size; /* sizeof(struct logger_entry) */ int32_t pid; /* generating process's pid */ uint32_t tid; /* generating process's tid */ uint32_t sec; /* seconds since Epoch */ uint32_t nsec; /* nanoseconds */ uint32_t lid; /* log id of the payload, bottom 4 bits currently */ uint32_t uid; /* generating process's uid */ }; #define LOGGER_ENTRY_MAX_LEN (5 * 1024) struct log_msg { union [[gnu::aligned(4)]] { unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1]; struct logger_entry entry; }; }; struct AndroidLogEntry { time_t tv_sec; long tv_nsec; android_LogPriority priority; int32_t uid; int32_t pid; int32_t tid; const char *tag; size_t tagLen; size_t messageLen; const char *message; }; struct [[gnu::packed]] android_event_header_t { int32_t tag; // Little Endian Order }; struct [[gnu::packed]] android_event_int_t { int8_t type; // EVENT_TYPE_INT int32_t data; // Little Endian Order }; struct [[gnu::packed]] android_event_string_t { int8_t type; // EVENT_TYPE_STRING; int32_t length; // Little Endian Order char data[]; }; struct [[gnu::packed]] android_event_list_t { int8_t type; // EVENT_TYPE_LIST int8_t element_count; } ; // 30014 am_proc_start (User|1|5),(PID|1|5),(UID|1|5),(Process Name|3),(Type|3),(Component|3) struct [[gnu::packed]] android_event_am_proc_start { android_event_header_t tag; android_event_list_t list; android_event_int_t user; android_event_int_t pid; android_event_int_t uid; android_event_string_t process_name; // android_event_string_t type; // android_event_string_t component; }; // 3040 boot_progress_ams_ready (time|2|3) extern "C" { [[gnu::weak]] struct logger_list *android_logger_list_alloc(int mode, unsigned int tail, pid_t pid); [[gnu::weak]] void android_logger_list_free(struct logger_list *list); [[gnu::weak]] int android_logger_list_read(struct logger_list *list, struct log_msg *log_msg); [[gnu::weak]] struct logger *android_logger_open(struct logger_list *list, log_id_t id); [[gnu::weak]] int android_log_processLogBuffer(struct logger_entry *buf, AndroidLogEntry *entry); } // zygote pid -> mnt ns static map<int, struct stat> zygote_map; bool logcat_exit; static int read_ns(const int pid, struct stat *st) { char path[32]; sprintf(path, "/proc/%d/ns/mnt", pid); return stat(path, st); } static int parse_ppid(int pid) { char path[32]; int ppid; sprintf(path, "/proc/%d/stat", pid); auto stat = open_file(path, "re"); if (!stat) return -1; // PID COMM STATE PPID ..... fscanf(stat.get(), "%*d %*s %*c %d", &ppid); return ppid; } static void check_zygote() { zygote_map.clear(); int proc = open("/proc", O_RDONLY | O_CLOEXEC); auto proc_dir = xopen_dir(proc); if (!proc_dir) return; struct stat st{}; for (dirent *entry; (entry = readdir(proc_dir.get()));) { int pid = parse_int(entry->d_name); if (pid <= 0) continue; if (fstatat(proc, entry->d_name, &st, 0)) continue; if (st.st_uid != 0) continue; if (proc_context_match(pid, "u:r:zygote:s0") && parse_ppid(pid) == 1) { if (read_ns(pid, &st) == 0) { LOGI("logcat: zygote PID=[%d]\n", pid); zygote_map[pid] = st; } } } } static void process_main_buffer(struct log_msg *msg) { AndroidLogEntry entry{}; if (android_log_processLogBuffer(&msg->entry, &entry) < 0) return; entry.tagLen--; auto tag = string_view(entry.tag, entry.tagLen); static bool ready = false; if (tag == "AppZygote") { if (entry.uid != 1000) return; if (entry.message[0] == 'S') { ready = true; } else { ready = false; } return; } if (!ready || tag != "AppZygoteInit") return; if (!proc_context_match(msg->entry.pid, "u:r:app_zygote:s0")) return; ready = false; char cmdline[1024]; sprintf(cmdline, "/proc/%d/cmdline", msg->entry.pid); if (auto f = open_file(cmdline, "re")) { fgets(cmdline, sizeof(cmdline), f.get()); } else { return; } if (is_deny_target(entry.uid, cmdline)) { int pid = msg->entry.pid; kill(pid, SIGSTOP); if (fork_dont_care() == 0) { LOGI("logcat: revert [%s] PID=[%d] UID=[%d]\n", cmdline, pid, entry.uid); revert_unmount(pid); kill(pid, SIGCONT); _exit(0); } } else { LOGD("logcat: skip [%s] PID=[%d] UID=[%d]\n", cmdline, msg->entry.pid, entry.uid); } } static void process_events_buffer(struct log_msg *msg) { if (msg->entry.uid != 1000) return; auto event_data = &msg->buf[msg->entry.hdr_size]; auto event_header = reinterpret_cast<const android_event_header_t *>(event_data); if (event_header->tag == 30014) { auto am_proc_start = reinterpret_cast<const android_event_am_proc_start *>(event_data); auto proc = string_view(am_proc_start->process_name.data, am_proc_start->process_name.length); if (is_deny_target(am_proc_start->uid.data, proc)) { int pid = am_proc_start->pid.data; if (fork_dont_care() == 0) { int ppid = parse_ppid(pid); auto it = zygote_map.find(ppid); if (it == zygote_map.end()) { LOGW("logcat: skip [%.*s] PID=[%d] UID=[%d] PPID=[%d]; parent not zygote\n", (int) proc.length(), proc.data(), pid, am_proc_start->uid.data, ppid); _exit(0); } char path[16]; ssprintf(path, sizeof(path), "/proc/%d", pid); struct stat st{}; int fd = syscall(__NR_pidfd_open, pid, 0); if (fd > 0 && setns(fd, CLONE_NEWNS) == 0) { pid = getpid(); } else { close(fd); fd = -1; } while (read_ns(pid, &st) == 0 && it->second.st_ino == st.st_ino) { if (stat(path, &st) == 0 && st.st_uid == 0) { usleep(10 * 1000); } else { LOGW("logcat: skip [%.*s] PID=[%s] UID=[%d]; namespace not isolated\n", (int) proc.length(), proc.data(), path + 6, am_proc_start->uid.data); _exit(0); } if (fd > 0) setns(fd, CLONE_NEWNS); } close(fd); LOGI("logcat: revert [%.*s] PID=[%d] UID=[%d]\n", (int) proc.length(), proc.data(), pid, am_proc_start->uid.data); revert_unmount(pid); _exit(0); } } else { LOGD("logcat: skip [%.*s] PID=[%d] UID=[%d]\n", (int) proc.length(), proc.data(), am_proc_start->pid.data, am_proc_start->uid.data); } return; } if (event_header->tag == 3040) { LOGD("logcat: soft reboot\n"); check_zygote(); } } [[noreturn]] void run() { while (true) { const unique_ptr<logger_list, decltype(&android_logger_list_free)> logger_list{ android_logger_list_alloc(0, 1, 0), &android_logger_list_free}; for (log_id id: {LOG_ID_MAIN, LOG_ID_EVENTS}) { auto *logger = android_logger_open(logger_list.get(), id); if (logger == nullptr) continue; } struct log_msg msg{}; while (true) { if (!denylist_enforced) { break; } if (android_logger_list_read(logger_list.get(), &msg) <= 0) { break; } switch (msg.entry.lid) { case LOG_ID_EVENTS: process_events_buffer(&msg); break; case LOG_ID_MAIN: process_main_buffer(&msg); default: break; } } if (!denylist_enforced) { break; } sleep(1); } LOGD("logcat: terminate\n"); pthread_exit(nullptr); } void *logcat(void *) { check_zygote(); run(); }
8,702
C++
.cpp
243
27.242798
100
0.537694
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19
utils.cpp
topjohnwu_Magisk/native/src/core/deny/utils.cpp
#include <sys/types.h> #include <sys/stat.h> #include <sys/inotify.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <set> #include <consts.hpp> #include <base.hpp> #include <db.hpp> #include <core.hpp> #include "deny.hpp" using namespace std; // For the following data structures: // If package name == ISOLATED_MAGIC, or app ID == -1, it means isolated service // Package name -> list of process names static unique_ptr<map<string, set<string, StringCmp>, StringCmp>> pkg_to_procs_; #define pkg_to_procs (*pkg_to_procs_) // app ID -> list of pkg names (string_view points to a pkg_to_procs key) static unique_ptr<map<int, set<string_view>>> app_id_to_pkgs_; #define app_id_to_pkgs (*app_id_to_pkgs_) // Locks the data structures above static pthread_mutex_t data_lock = PTHREAD_MUTEX_INITIALIZER; atomic<bool> denylist_enforced = false; static int get_app_id(const vector<int> &users, const string &pkg) { struct stat st{}; char buf[PATH_MAX]; for (const auto &user_id: users) { ssprintf(buf, sizeof(buf), "%s/%d/%s", APP_DATA_DIR, user_id, pkg.data()); if (stat(buf, &st) == 0) { return to_app_id(st.st_uid); } } return 0; } static void collect_users(vector<int> &users) { auto data_dir = xopen_dir(APP_DATA_DIR); if (!data_dir) return; dirent *entry; while ((entry = xreaddir(data_dir.get()))) { users.emplace_back(parse_int(entry->d_name)); } } static int get_app_id(const string &pkg) { if (pkg == ISOLATED_MAGIC) return -1; vector<int> users; collect_users(users); return get_app_id(users, pkg); } static void update_app_id(int app_id, const string &pkg, bool remove) { if (app_id <= 0) return; if (remove) { if (auto it = app_id_to_pkgs.find(app_id); it != app_id_to_pkgs.end()) { it->second.erase(pkg); if (it->second.empty()) { app_id_to_pkgs.erase(it); } } } else { app_id_to_pkgs[app_id].emplace(pkg); } } // Leave /proc fd opened as we're going to read from it repeatedly static DIR *procfp; template<class F> static void crawl_procfs(const F &fn) { rewinddir(procfp); dirent *dp; int pid; while ((dp = readdir(procfp))) { pid = parse_int(dp->d_name); if (pid > 0 && !fn(pid)) break; } } static inline bool str_eql(string_view a, string_view b) { return a == b; } template<bool str_op(string_view, string_view) = &str_eql> static bool proc_name_match(int pid, string_view name) { char buf[4019]; sprintf(buf, "/proc/%d/cmdline", pid); if (auto fp = open_file(buf, "re")) { fgets(buf, sizeof(buf), fp.get()); if (str_op(buf, name)) { return true; } } return false; } bool proc_context_match(int pid, string_view context) { char buf[PATH_MAX]; sprintf(buf, "/proc/%d/attr/current", pid); if (auto fp = open_file(buf, "re")) { fgets(buf, sizeof(buf), fp.get()); if (str_starts(buf, context)) { return true; } } return false; } template<bool matcher(int, string_view) = &proc_name_match> static void kill_process(const char *name, bool multi = false) { crawl_procfs([=](int pid) -> bool { if (matcher(pid, name)) { kill(pid, SIGKILL); LOGD("denylist: kill PID=[%d] (%s)\n", pid, name); return multi; } return true; }); } static bool validate(const char *pkg, const char *proc) { bool pkg_valid = false; bool proc_valid = true; if (str_eql(pkg, ISOLATED_MAGIC)) { pkg_valid = true; for (char c; (c = *proc); ++proc) { if (isalnum(c) || c == '_' || c == '.') continue; if (c == ':') break; proc_valid = false; break; } } else { for (char c; (c = *pkg); ++pkg) { if (isalnum(c) || c == '_') continue; if (c == '.') { pkg_valid = true; continue; } pkg_valid = false; break; } for (char c; (c = *proc); ++proc) { if (isalnum(c) || c == '_' || c == ':' || c == '.') continue; proc_valid = false; break; } } return pkg_valid && proc_valid; } static bool add_hide_set(const char *pkg, const char *proc) { auto p = pkg_to_procs[pkg].emplace(proc); if (!p.second) return false; LOGI("denylist add: [%s/%s]\n", pkg, proc); if (!denylist_enforced) return true; if (str_eql(pkg, ISOLATED_MAGIC)) { // Kill all matching isolated processes kill_process<&proc_name_match<str_starts>>(proc, true); } else { kill_process(proc); } return true; } void scan_deny_apps() { if (!app_id_to_pkgs_) return; app_id_to_pkgs.clear(); char sql[4096]; vector<int> users; collect_users(users); for (auto it = pkg_to_procs.begin(); it != pkg_to_procs.end();) { if (it->first == ISOLATED_MAGIC) { it++; continue; } int app_id = get_app_id(users, it->first); if (app_id == 0) { LOGI("denylist rm: [%s]\n", it->first.data()); ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'", it->first.data()); db_exec(sql).check_err(); it = pkg_to_procs.erase(it); } else { update_app_id(app_id, it->first, false); it++; } } } static void clear_data() { pkg_to_procs_.reset(nullptr); app_id_to_pkgs_.reset(nullptr); } static bool ensure_data() { if (pkg_to_procs_) return true; LOGI("denylist: initializing internal data structures\n"); default_new(pkg_to_procs_); auto res = db_exec("SELECT * FROM denylist", [](db_row &row) -> bool { add_hide_set(row["package_name"].data(), row["process"].data()); return true; }); if (res.check_err()) goto error; default_new(app_id_to_pkgs_); scan_deny_apps(); return true; error: clear_data(); return false; } static int add_list(const char *pkg, const char *proc) { if (proc[0] == '\0') proc = pkg; if (!validate(pkg, proc)) return DenyResponse::INVALID_PKG; { mutex_guard lock(data_lock); if (!ensure_data()) return DenyResponse::ERROR; int app_id = get_app_id(pkg); if (app_id == 0) return DenyResponse::INVALID_PKG; if (!add_hide_set(pkg, proc)) return DenyResponse::ITEM_EXIST; auto it = pkg_to_procs.find(pkg); update_app_id(app_id, it->first, false); } // Add to database char sql[4096]; ssprintf(sql, sizeof(sql), "INSERT INTO denylist (package_name, process) VALUES('%s', '%s')", pkg, proc); return db_exec(sql).check_err() ? DenyResponse::ERROR : DenyResponse::OK; } int add_list(int client) { string pkg = read_string(client); string proc = read_string(client); return add_list(pkg.data(), proc.data()); } static int rm_list(const char *pkg, const char *proc) { { mutex_guard lock(data_lock); if (!ensure_data()) return DenyResponse::ERROR; bool remove = false; auto it = pkg_to_procs.find(pkg); if (it != pkg_to_procs.end()) { if (proc[0] == '\0') { update_app_id(get_app_id(pkg), it->first, true); pkg_to_procs.erase(it); remove = true; LOGI("denylist rm: [%s]\n", pkg); } else if (it->second.erase(proc) != 0) { remove = true; LOGI("denylist rm: [%s/%s]\n", pkg, proc); if (it->second.empty()) { update_app_id(get_app_id(pkg), it->first, true); pkg_to_procs.erase(it); } } } if (!remove) return DenyResponse::ITEM_NOT_EXIST; } char sql[4096]; if (proc[0] == '\0') ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'", pkg); else ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s' AND process='%s'", pkg, proc); return db_exec(sql).check_err() ? DenyResponse::ERROR : DenyResponse::OK; } int rm_list(int client) { string pkg = read_string(client); string proc = read_string(client); return rm_list(pkg.data(), proc.data()); } void ls_list(int client) { { mutex_guard lock(data_lock); if (!ensure_data()) { write_int(client, static_cast<int>(DenyResponse::ERROR)); return; } scan_deny_apps(); write_int(client,static_cast<int>(DenyResponse::OK)); for (const auto &[pkg, procs] : pkg_to_procs) { for (const auto &proc : procs) { write_int(client, pkg.size() + proc.size() + 1); xwrite(client, pkg.data(), pkg.size()); xwrite(client, "|", 1); xwrite(client, proc.data(), proc.size()); } } } write_int(client, 0); close(client); } int enable_deny() { if (denylist_enforced) { return DenyResponse::OK; } else { mutex_guard lock(data_lock); if (access("/proc/self/ns/mnt", F_OK) != 0) { LOGW("The kernel does not support mount namespace\n"); return DenyResponse::NO_NS; } if (procfp == nullptr && (procfp = opendir("/proc")) == nullptr) return DenyResponse::ERROR; LOGI("* Enable DenyList\n"); if (!ensure_data()) return DenyResponse::ERROR; denylist_enforced = true; if (!zygisk_enabled) { if (new_daemon_thread(&logcat)) { denylist_enforced = false; return DenyResponse::ERROR; } } // On Android Q+, also kill blastula pool and all app zygotes if (SDK_INT >= 29) { kill_process("usap32", true); kill_process("usap64", true); kill_process<&proc_context_match>("u:r:app_zygote:s0", true); } } set_db_settings(DENYLIST_CONFIG, true); return DenyResponse::OK; } int disable_deny() { if (denylist_enforced.exchange(false)) { LOGI("* Disable DenyList\n"); } set_db_settings(DENYLIST_CONFIG, false); return DenyResponse::OK; } void initialize_denylist() { if (!denylist_enforced) { db_settings dbs; get_db_settings(dbs, DENYLIST_CONFIG); if (dbs[DENYLIST_CONFIG]) enable_deny(); } } bool is_deny_target(int uid, string_view process) { mutex_guard lock(data_lock); if (!ensure_data()) return false; int app_id = to_app_id(uid); if (app_id >= 90000) { if (auto it = pkg_to_procs.find(ISOLATED_MAGIC); it != pkg_to_procs.end()) { for (const auto &s : it->second) { if (str_starts(process, s)) return true; } } return false; } else { auto it = app_id_to_pkgs.find(app_id); if (it == app_id_to_pkgs.end()) return false; for (const auto &pkg : it->second) { if (pkg_to_procs.find(pkg)->second.count(process)) return true; } } return false; }
11,628
C++
.cpp
365
24.271233
92
0.550161
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20
main.cpp
topjohnwu_Magisk/native/src/core/zygisk/main.cpp
#include <sys/mount.h> #include <android/dlext.h> #include <dlfcn.h> #include <consts.hpp> #include <base.hpp> #include <core.hpp> #include <selinux.hpp> #include "zygisk.hpp" using namespace std; static void zygiskd(int socket) { if (getuid() != 0 || fcntl(socket, F_GETFD) < 0) exit(-1); init_thread_pool(); #if defined(__LP64__) set_nice_name("zygiskd64"); LOGI("* Launching zygiskd64\n"); #else set_nice_name("zygiskd32"); LOGI("* Launching zygiskd32\n"); #endif // Load modules using comp_entry = void(*)(int); vector<comp_entry> modules; { vector<int> module_fds = recv_fds(socket); for (int fd : module_fds) { comp_entry entry = nullptr; struct stat s{}; if (fstat(fd, &s) == 0 && S_ISREG(s.st_mode)) { android_dlextinfo info { .flags = ANDROID_DLEXT_USE_LIBRARY_FD, .library_fd = fd, }; if (void *h = android_dlopen_ext("/jit-cache", RTLD_LAZY, &info)) { *(void **) &entry = dlsym(h, "zygisk_companion_entry"); } else { LOGW("Failed to dlopen zygisk module: %s\n", dlerror()); } } modules.push_back(entry); close(fd); } } // ack write_int(socket, 0); // Start accepting requests pollfd pfd = { socket, POLLIN, 0 }; for (;;) { poll(&pfd, 1, -1); if (pfd.revents && !(pfd.revents & POLLIN)) { // Something bad happened in magiskd, terminate zygiskd exit(0); } int client = recv_fd(socket); if (client < 0) { // Something bad happened in magiskd, terminate zygiskd exit(0); } int module_id = read_int(client); if (module_id >= 0 && module_id < modules.size() && modules[module_id]) { exec_task([=, entry = modules[module_id]] { struct stat s1; fstat(client, &s1); entry(client); // Only close client if it is the same file so we don't // accidentally close a re-used file descriptor. // This check is required because the module companion // handler could've closed the file descriptor already. if (struct stat s2; fstat(client, &s2) == 0) { if (s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino) { close(client); } } }); } else { close(client); } } } // Entrypoint where we need to re-exec ourselves // This should only ever be called internally int zygisk_main(int argc, char *argv[]) { android_logging(); if (argc == 3 && argv[1] == "companion"sv) { zygiskd(parse_int(argv[2])); } return 0; }
2,938
C++
.cpp
88
24
83
0.517606
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
21
entry.cpp
topjohnwu_Magisk/native/src/core/zygisk/entry.cpp
#include <libgen.h> #include <dlfcn.h> #include <sys/prctl.h> #include <sys/mount.h> #include <android/log.h> #include <android/dlext.h> #include <base.hpp> #include <consts.hpp> #include "zygisk.hpp" #include "module.hpp" using namespace std; string native_bridge = "0"; static bool is_compatible_with(uint32_t) { zygisk_logging(); hook_entry(); ZLOGD("load success\n"); return false; } extern "C" [[maybe_unused]] NativeBridgeCallbacks NativeBridgeItf { .version = 2, .padding = {}, .isCompatibleWith = &is_compatible_with, }; // The following code runs in zygote/app process static inline bool should_load_modules(uint32_t flags) { return (flags & UNMOUNT_MASK) != UNMOUNT_MASK && (flags & PROCESS_IS_MAGISK_APP) != PROCESS_IS_MAGISK_APP; } int remote_get_info(int uid, const char *process, uint32_t *flags, vector<int> &fds) { if (int fd = zygisk_request(ZygiskRequest::GET_INFO); fd >= 0) { write_int(fd, uid); write_string(fd, process); xxread(fd, flags, sizeof(*flags)); if (should_load_modules(*flags)) { fds = recv_fds(fd); } return fd; } return -1; } // The following code runs in magiskd static vector<int> get_module_fds(bool is_64_bit) { vector<int> fds; // All fds passed to send_fds have to be valid file descriptors. // To workaround this issue, send over STDOUT_FILENO as an indicator of an // invalid fd as it will always be /dev/null in magiskd #if defined(__LP64__) if (is_64_bit) { std::transform(module_list->begin(), module_list->end(), std::back_inserter(fds), [](const module_info &info) { return info.z64 < 0 ? STDOUT_FILENO : info.z64; }); } else #endif { std::transform(module_list->begin(), module_list->end(), std::back_inserter(fds), [](const module_info &info) { return info.z32 < 0 ? STDOUT_FILENO : info.z32; }); } return fds; } static bool get_exe(int pid, char *buf, size_t sz) { char exe[128]; if (ssprintf(exe, sizeof(exe), "/proc/%d/exe", pid) < 0) return false; return xreadlink(exe, buf, sz) > 0; } static pthread_mutex_t zygiskd_lock = PTHREAD_MUTEX_INITIALIZER; static int zygiskd_sockets[] = { -1, -1 }; #define zygiskd_socket zygiskd_sockets[is_64_bit] static void connect_companion(int client, bool is_64_bit) { mutex_guard g(zygiskd_lock); if (zygiskd_socket >= 0) { // Make sure the socket is still valid pollfd pfd = { zygiskd_socket, 0, 0 }; poll(&pfd, 1, 0); if (pfd.revents) { // Any revent means error close(zygiskd_socket); zygiskd_socket = -1; } } if (zygiskd_socket < 0) { int fds[2]; socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fds); zygiskd_socket = fds[0]; if (fork_dont_care() == 0) { char exe[64]; #if defined(__LP64__) ssprintf(exe, sizeof(exe), "%s/magisk%s", get_magisk_tmp(), (is_64_bit ? "" : "32")); #else ssprintf(exe, sizeof(exe), "%s/magisk", get_magisk_tmp()); #endif // This fd has to survive exec fcntl(fds[1], F_SETFD, 0); char buf[16]; ssprintf(buf, sizeof(buf), "%d", fds[1]); execl(exe, "", "zygisk", "companion", buf, (char *) nullptr); exit(-1); } close(fds[1]); vector<int> module_fds = get_module_fds(is_64_bit); send_fds(zygiskd_socket, module_fds.data(), module_fds.size()); // Wait for ack if (read_int(zygiskd_socket) != 0) { LOGE("zygiskd startup error\n"); return; } } send_fd(zygiskd_socket, client); } extern bool uid_granted_root(int uid); static void get_process_info(int client, const sock_cred *cred) { int uid = read_int(client); string process = read_string(client); uint32_t flags = 0; if (is_deny_target(uid, process)) { flags |= PROCESS_ON_DENYLIST; } if (get_manager(to_user_id(uid)) == uid) { flags |= PROCESS_IS_MAGISK_APP; } if (denylist_enforced) { flags |= DENYLIST_ENFORCING; } if (uid_granted_root(uid)) { flags |= PROCESS_GRANTED_ROOT; } xwrite(client, &flags, sizeof(flags)); if (should_load_modules(flags)) { char buf[256]; if (!get_exe(cred->pid, buf, sizeof(buf))) { LOGW("zygisk: remote process %d probably died, abort\n", cred->pid); send_fd(client, -1); return; } vector<int> fds = get_module_fds(str_ends(buf, "64")); send_fds(client, fds.data(), fds.size()); } if (uid != 1000 || process != "system_server") return; // Collect module status from system_server int slots = read_int(client); dynamic_bitset bits; for (int i = 0; i < slots; ++i) { dynamic_bitset::slot_type l = 0; xxread(client, &l, sizeof(l)); bits.emplace_back(l); } for (int id = 0; id < module_list->size(); ++id) { if (!as_const(bits)[id]) { // Either not a zygisk module, or incompatible char buf[4096]; ssprintf(buf, sizeof(buf), MODULEROOT "/%s/zygisk", module_list->operator[](id).name.data()); if (int dirfd = open(buf, O_RDONLY | O_CLOEXEC); dirfd >= 0) { close(xopenat(dirfd, "unloaded", O_CREAT | O_RDONLY, 0644)); close(dirfd); } } } } static void get_moddir(int client) { int id = read_int(client); char buf[4096]; ssprintf(buf, sizeof(buf), MODULEROOT "/%s", module_list->operator[](id).name.data()); int dfd = xopen(buf, O_RDONLY | O_CLOEXEC); send_fd(client, dfd); close(dfd); } void zygisk_handler(int client, const sock_cred *cred) { int code = read_int(client); char buf[256]; switch (code) { case ZygiskRequest::GET_INFO: get_process_info(client, cred); break; case ZygiskRequest::CONNECT_COMPANION: if (get_exe(cred->pid, buf, sizeof(buf))) { connect_companion(client, str_ends(buf, "64")); } else { LOGW("zygisk: remote process %d probably died, abort\n", cred->pid); } break; case ZygiskRequest::GET_MODDIR: get_moddir(client); break; default: // Unknown code break; } close(client); } void reset_zygisk(bool restore) { if (!zygisk_enabled) return; static atomic_uint zygote_start_count{1}; if (!restore) { close(zygiskd_sockets[0]); close(zygiskd_sockets[1]); zygiskd_sockets[0] = zygiskd_sockets[1] = -1; } if (restore) { zygote_start_count = 1; } else if (zygote_start_count.fetch_add(1) > 3) { LOGW("zygote crashes too many times, rolling-back\n"); restore = true; } if (restore) { string native_bridge_orig = "0"; if (native_bridge.length() > strlen(ZYGISKLDR)) { native_bridge_orig = native_bridge.substr(strlen(ZYGISKLDR)); } set_prop(NBPROP, native_bridge_orig.data()); } else { set_prop(NBPROP, native_bridge.data()); } }
7,255
C++
.cpp
214
27.238318
97
0.589795
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
53