Refactor daemon connection

This commit is contained in:
LoveSy 2022-02-12 23:43:36 +08:00 committed by John Wu
parent c82a46c1ee
commit 7999b66c3c
14 changed files with 312 additions and 237 deletions

View File

@ -14,6 +14,7 @@
#include <selinux.hpp> #include <selinux.hpp>
#include "core.hpp" #include "core.hpp"
#include "zygisk/deny/deny.hpp"
using namespace std; using namespace std;

View File

@ -133,61 +133,63 @@ static void poll_ctrl_handler(pollfd *pfd) {
} }
} }
static void handle_request_async(int client, int code, const sock_cred &cred) { static void handle_request_async(int client, DaemonRequest code, const sock_cred &cred) {
// using enum DAEMON_REQUEST;
switch (code) { switch (code) {
case DENYLIST: case DaemonRequest::DENYLIST:
denylist_handler(client, &cred); denylist_handler(client, &cred);
break; break;
case SUPERUSER: case DaemonRequest::SUPERUSER:
su_daemon_handler(client, &cred); su_daemon_handler(client, &cred);
break; break;
case POST_FS_DATA: case DaemonRequest::POST_FS_DATA:
post_fs_data(client); post_fs_data(client);
break; break;
case LATE_START: case DaemonRequest::LATE_START:
late_start(client); late_start(client);
break; break;
case BOOT_COMPLETE: case DaemonRequest::BOOT_COMPLETE:
boot_complete(client); boot_complete(client);
break; break;
case SQLITE_CMD: case DaemonRequest::SQLITE_CMD:
exec_sql(client); exec_sql(client);
break; break;
case REMOVE_MODULES: case DaemonRequest::REMOVE_MODULES:
remove_modules(); remove_modules();
write_int(client, 0); write_int(client, 0);
close(client); close(client);
reboot(); reboot();
break; break;
case ZYGISK_REQUEST: case DaemonRequest::ZYGISK_REQUEST:
case ZYGISK_PASSTHROUGH:
zygisk_handler(client, &cred); zygisk_handler(client, &cred);
break; break;
default: default:
close(client); __builtin_unreachable();
break;
} }
} }
static void handle_request_sync(int client, int code) { static void handle_request_sync(int client, DaemonRequest code) {
// using enum DAEMON_REQUEST;
switch (code) { switch (code) {
case CHECK_VERSION: case DaemonRequest::CHECK_VERSION:
write_string(client, MAGISK_VERSION ":MAGISK"); write_string(client, MAGISK_VERSION ":MAGISK");
break; break;
case CHECK_VERSION_CODE: case DaemonRequest::CHECK_VERSION_CODE:
write_int(client, MAGISK_VER_CODE); write_int(client, MAGISK_VER_CODE);
break; break;
case GET_PATH: case DaemonRequest::GET_PATH:
write_string(client, MAGISKTMP.data()); write_string(client, MAGISKTMP.data());
break; break;
case START_DAEMON: case DaemonRequest::START_DAEMON:
setup_logfile(true); setup_logfile(true);
break; break;
case STOP_DAEMON: case DaemonRequest::STOP_DAEMON:
denylist_handler(-1, nullptr); denylist_handler(-1, nullptr);
write_int(client, 0); write_int(client, 0);
// Terminate the daemon! // Terminate the daemon!
exit(0); exit(0);
default:
__builtin_unreachable();
} }
} }
@ -195,11 +197,17 @@ static bool is_client(pid_t pid) {
// Verify caller is the same as server // Verify caller is the same as server
char path[32]; char path[32];
sprintf(path, "/proc/%d/exe", pid); sprintf(path, "/proc/%d/exe", pid);
struct stat st; struct stat st{};
return !(stat(path, &st) || st.st_dev != self_st.st_dev || st.st_ino != self_st.st_ino); return !(stat(path, &st) || st.st_dev != self_st.st_dev || st.st_ino != self_st.st_ino);
} }
inline static void write_response(int client, DaemonResponse res) {
write_int(client, static_cast<std::underlying_type_t<DaemonResponse>>(res));
}
static void handle_request(pollfd *pfd) { static void handle_request(pollfd *pfd) {
// using enum DAEMON_REQUEST;
// using enum DAEMON_RESPONSE;
int client = xaccept4(pfd->fd, nullptr, nullptr, SOCK_CLOEXEC); int client = xaccept4(pfd->fd, nullptr, nullptr, SOCK_CLOEXEC);
// Verify client credentials // Verify client credentials
@ -207,6 +215,7 @@ static void handle_request(pollfd *pfd) {
bool is_root; bool is_root;
bool is_zygote; bool is_zygote;
int code; int code;
DaemonRequest req;
if (!get_client_cred(client, &cred)) if (!get_client_cred(client, &cred))
goto done; goto done;
@ -217,44 +226,46 @@ static void handle_request(pollfd *pfd) {
goto done; goto done;
code = read_int(client); code = read_int(client);
if (code < 0 || (code & DAEMON_CODE_MASK) >= DAEMON_CODE_END) static_assert(is_scoped_enum_v<DaemonRequest>);
if (code < 0 || code >= DaemonRequest::END || code == DaemonRequest::_SYNC_BARRIER_)
goto done; goto done;
req = static_cast<DaemonRequest>(code);
// Check client permissions // Check client permissions
switch (code) { switch (req) {
case POST_FS_DATA: case DaemonRequest::POST_FS_DATA:
case LATE_START: case DaemonRequest::LATE_START:
case BOOT_COMPLETE: case DaemonRequest::BOOT_COMPLETE:
case SQLITE_CMD: case DaemonRequest::SQLITE_CMD:
case GET_PATH: case DaemonRequest::GET_PATH:
case DENYLIST: case DaemonRequest::DENYLIST:
case STOP_DAEMON: case DaemonRequest::STOP_DAEMON:
if (!is_root) { if (!is_root) {
write_int(client, ROOT_REQUIRED); write_response(client, DaemonResponse::ROOT_REQUIRED);
goto done; goto done;
} }
break; break;
case REMOVE_MODULES: case DaemonRequest::REMOVE_MODULES:
if (!is_root && cred.uid != UID_SHELL) { if (!is_root && cred.uid != UID_SHELL) {
write_int(client, 1); write_response(client, DaemonResponse::ROOT_REQUIRED);
goto done; goto done;
} }
break; break;
case ZYGISK_REQUEST: default:
if (!is_zygote) {
write_int(client, DAEMON_ERROR);
goto done;
}
break; break;
} }
if (code & SYNC_FLAG) { write_response(client, DaemonResponse::OK);
handle_request_sync(client, code);
if (req < DaemonRequest::_SYNC_BARRIER_) {
handle_request_sync(client, req);
goto done; goto done;
} }
// Handle complex requests in another thread // Handle complex requests in another thread
exec_task([=] { handle_request_async(client, code, cred); }); exec_task([=] { handle_request_async(client, req, cred); });
return; return;
done: done:
@ -376,7 +387,7 @@ static void daemon_entry() {
sockaddr_un sun{}; sockaddr_un sun{};
socklen_t len = setup_sockaddr(&sun, MAIN_SOCKET); socklen_t len = setup_sockaddr(&sun, MAIN_SOCKET);
fd = xsocket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); fd = xsocket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (xbind(fd, (sockaddr*) &sun, len)) if (xbind(fd, (sockaddr *) &sun, len))
exit(1); exit(1);
xlisten(fd, 10); xlisten(fd, 10);
@ -391,11 +402,12 @@ static void daemon_entry() {
poll_loop(); poll_loop();
} }
int connect_daemon(bool create) { int connect_daemon(DaemonRequest req, bool create) {
// using enum DAEMON_RESPONSE;
sockaddr_un sun{}; sockaddr_un sun{};
socklen_t len = setup_sockaddr(&sun, MAIN_SOCKET); socklen_t len = setup_sockaddr(&sun, MAIN_SOCKET);
int fd = xsocket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); int fd = xsocket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (connect(fd, (sockaddr*) &sun, len)) { if (connect(fd, (sockaddr *) &sun, len)) {
if (!create || getuid() != UID_ROOT) { if (!create || getuid() != UID_ROOT) {
LOGE("No daemon is currently running!\n"); LOGE("No daemon is currently running!\n");
close(fd); close(fd);
@ -407,8 +419,27 @@ int connect_daemon(bool create) {
daemon_entry(); daemon_entry();
} }
while (connect(fd, (struct sockaddr*) &sun, len)) while (connect(fd, (struct sockaddr *) &sun, len))
usleep(10000); usleep(10000);
} }
write_int(fd, static_cast<int>(req));
int ret = read_int(fd);
auto res = (ret < DaemonResponse::ERROR || ret >= DaemonResponse::END) ? DaemonResponse::ERROR
: static_cast<DaemonResponse>(ret);
switch (res) {
case DaemonResponse::OK:
break;
case DaemonResponse::ERROR:
LOGE("Daemon error\n");
exit(-1);
case DaemonResponse::ROOT_REQUIRED:
LOGE("Root is required for this operation\n");
exit(-1);
case DaemonResponse::INVALID_REQUEST:
LOGE("Invalid request\n");
exit(-1);
case DaemonResponse::END:
__builtin_unreachable();
}
return fd; return fd;
} }

View File

@ -50,20 +50,19 @@ Available applets:
} }
int magisk_main(int argc, char *argv[]) { int magisk_main(int argc, char *argv[]) {
// using enum DAEMON_REQUEST;
if (argc < 2) if (argc < 2)
usage(); usage();
if (argv[1] == "-c"sv) { if (argv[1] == "-c"sv) {
printf(MAGISK_VERSION ":MAGISK (" str(MAGISK_VER_CODE) ")\n"); printf(MAGISK_VERSION ":MAGISK (" str(MAGISK_VER_CODE) ")\n");
return 0; return 0;
} else if (argv[1] == "-v"sv) { } else if (argv[1] == "-v"sv) {
int fd = connect_daemon(); int fd = connect_daemon(DaemonRequest::CHECK_VERSION);
write_int(fd, CHECK_VERSION);
string v = read_string(fd); string v = read_string(fd);
printf("%s\n", v.data()); printf("%s\n", v.data());
return 0; return 0;
} else if (argv[1] == "-V"sv) { } else if (argv[1] == "-V"sv) {
int fd = connect_daemon(); int fd = connect_daemon(DaemonRequest::CHECK_VERSION_CODE);
write_int(fd, CHECK_VERSION_CODE);
printf("%d\n", read_int(fd)); printf("%d\n", read_int(fd));
return 0; return 0;
} else if (argv[1] == "--list"sv) { } else if (argv[1] == "--list"sv) {
@ -76,37 +75,32 @@ int magisk_main(int argc, char *argv[]) {
} else if (argv[1] == "--restorecon"sv) { } else if (argv[1] == "--restorecon"sv) {
restorecon(); restorecon();
return 0; return 0;
} else if (argc >= 4 && argv[1] == "--clone-attr"sv) {; } else if (argc >= 4 && argv[1] == "--clone-attr"sv) {
clone_attr(argv[2], argv[3]); clone_attr(argv[2], argv[3]);
return 0; return 0;
} else if (argc >= 4 && argv[1] == "--clone"sv) { } else if (argc >= 4 && argv[1] == "--clone"sv) {
cp_afc(argv[2], argv[3]); cp_afc(argv[2], argv[3]);
return 0; return 0;
} else if (argv[1] == "--daemon"sv) { } else if (argv[1] == "--daemon"sv) {
int fd = connect_daemon(true); int fd = connect_daemon(DaemonRequest::START_DAEMON, true);
write_int(fd, START_DAEMON); close(fd);
return 0; return 0;
} else if (argv[1] == "--stop"sv) { } else if (argv[1] == "--stop"sv) {
int fd = connect_daemon(); int fd = connect_daemon(DaemonRequest::STOP_DAEMON);
write_int(fd, STOP_DAEMON);
return read_int(fd); return read_int(fd);
} else if (argv[1] == "--post-fs-data"sv) { } else if (argv[1] == "--post-fs-data"sv) {
int fd = connect_daemon(true); int fd = connect_daemon(DaemonRequest::POST_FS_DATA, true);
write_int(fd, POST_FS_DATA);
return read_int(fd); return read_int(fd);
} else if (argv[1] == "--service"sv) { } else if (argv[1] == "--service"sv) {
int fd = connect_daemon(true); int fd = connect_daemon(DaemonRequest::LATE_START, true);
write_int(fd, LATE_START);
return read_int(fd); return read_int(fd);
} else if (argv[1] == "--boot-complete"sv) { } else if (argv[1] == "--boot-complete"sv) {
int fd = connect_daemon(true); int fd = connect_daemon(DaemonRequest::BOOT_COMPLETE, true);
write_int(fd, BOOT_COMPLETE);
return read_int(fd); return read_int(fd);
} else if (argv[1] == "--denylist"sv) { } else if (argv[1] == "--denylist"sv) {
return denylist_cli(argc - 1, argv + 1); return denylist_cli(argc - 1, argv + 1);
}else if (argc >= 3 && argv[1] == "--sqlite"sv) { } else if (argc >= 3 && argv[1] == "--sqlite"sv) {
int fd = connect_daemon(); int fd = connect_daemon(DaemonRequest::SQLITE_CMD);
write_int(fd, SQLITE_CMD);
write_string(fd, argv[2]); write_string(fd, argv[2]);
string res; string res;
for (;;) { for (;;) {
@ -116,12 +110,10 @@ int magisk_main(int argc, char *argv[]) {
printf("%s\n", res.data()); printf("%s\n", res.data());
} }
} else if (argv[1] == "--remove-modules"sv) { } else if (argv[1] == "--remove-modules"sv) {
int fd = connect_daemon(); int fd = connect_daemon(DaemonRequest::REMOVE_MODULES);
write_int(fd, REMOVE_MODULES);
return read_int(fd); return read_int(fd);
} else if (argv[1] == "--path"sv) { } else if (argv[1] == "--path"sv) {
int fd = connect_daemon(); int fd = connect_daemon(DaemonRequest::GET_PATH);
write_int(fd, GET_PATH);
string path = read_string(fd); string path = read_string(fd);
printf("%s\n", path.data()); printf("%s\n", path.data());
return 0; return 0;

View File

@ -9,20 +9,17 @@
#include <socket.hpp> #include <socket.hpp>
// Daemon command code flags/masks
enum : int {
SYNC_FLAG = (1 << 30),
DAEMON_CODE_MASK = std::numeric_limits<int>::max() >> 1
};
// Daemon command codes // Daemon command codes
enum : int { enum class DaemonRequest: int {
START_DAEMON = SYNC_FLAG | 0, START_DAEMON,
CHECK_VERSION = SYNC_FLAG | 1, CHECK_VERSION,
CHECK_VERSION_CODE = SYNC_FLAG | 2, CHECK_VERSION_CODE,
GET_PATH = SYNC_FLAG | 3, GET_PATH,
STOP_DAEMON = SYNC_FLAG | 4, STOP_DAEMON,
SUPERUSER = 5,
_SYNC_BARRIER_,
SUPERUSER,
POST_FS_DATA, POST_FS_DATA,
LATE_START, LATE_START,
BOOT_COMPLETE, BOOT_COMPLETE,
@ -30,16 +27,16 @@ enum : int {
SQLITE_CMD, SQLITE_CMD,
REMOVE_MODULES, REMOVE_MODULES,
ZYGISK_REQUEST, ZYGISK_REQUEST,
ZYGISK_PASSTHROUGH, END,
DAEMON_CODE_END,
}; };
// Return codes for daemon // Return codes for daemon
enum : int { enum class DaemonResponse: int {
DAEMON_ERROR = -1, ERROR = -1,
DAEMON_SUCCESS = 0, OK = 0,
ROOT_REQUIRED, ROOT_REQUIRED,
DAEMON_LAST INVALID_REQUEST,
END
}; };
struct module_info { struct module_info {
@ -55,7 +52,7 @@ extern int app_process_32;
extern int app_process_64; extern int app_process_64;
extern std::vector<module_info> *module_list; extern std::vector<module_info> *module_list;
int connect_daemon(bool create = false); int connect_daemon(DaemonRequest req, bool create = false);
// Poll control // Poll control
using poll_callback = void(*)(pollfd*); using poll_callback = void(*)(pollfd*);
@ -81,5 +78,4 @@ void zygisk_handler(int client, const sock_cred *cred);
// Denylist // Denylist
void initialize_denylist(); void initialize_denylist();
int disable_deny();
int denylist_cli(int argc, char **argv); int denylist_cli(int argc, char **argv);

View File

@ -240,7 +240,7 @@ void SARBase::patch_rootdir() {
make_pair(SPLIT_PLAT_CIL, "xxx"), /* Force loading monolithic sepolicy */ make_pair(SPLIT_PLAT_CIL, "xxx"), /* Force loading monolithic sepolicy */
make_pair(MONOPOLICY, sepol) /* Redirect /sepolicy to custom path */ make_pair(MONOPOLICY, sepol) /* Redirect /sepolicy to custom path */
}); });
if (avd_hack) { if constexpr (avd_hack) {
// Force disable early mount on original init // Force disable early mount on original init
init.patch({ make_pair("android,fstab", "xxx") }); init.patch({ make_pair("android,fstab", "xxx") });
} }

View File

@ -159,10 +159,7 @@ int su_client_main(int argc, char *argv[]) {
int ptmx, fd; int ptmx, fd;
// Connect to client // Connect to client
fd = connect_daemon(); fd = connect_daemon(DaemonRequest::SUPERUSER);
// Tell the daemon we are su
write_int(fd, SUPERUSER);
// Send su_request // Send su_request
xwrite(fd, &su_req, sizeof(su_req_base)); xwrite(fd, &su_req, sizeof(su_req_base));

View File

@ -5,6 +5,8 @@
#include <functional> #include <functional>
#include <string_view> #include <string_view>
#include <bitset> #include <bitset>
#include <compare>
#include "xwrap.hpp"
#define UID_ROOT 0 #define UID_ROOT 0
#define UID_SHELL 2000 #define UID_SHELL 2000
@ -197,3 +199,32 @@ void exec_command_async(Args &&...args) {
}; };
exec_command(exec); exec_command(exec);
} }
template <class _Tp, bool = std::is_enum_v<_Tp> >
struct __is_scoped_enum_helper : std::false_type {};
template <class _Tp>
struct __is_scoped_enum_helper<_Tp, true>
: public std::bool_constant<!std::is_convertible_v<_Tp, std::underlying_type_t<_Tp> > > {};
template <class _Tp>
struct is_scoped_enum
: public __is_scoped_enum_helper<_Tp> {};
template <class _Tp>
inline constexpr bool is_scoped_enum_v = is_scoped_enum<_Tp>::value;
template<typename Enum> requires( is_scoped_enum_v<Enum> )
constexpr inline auto operator <=> (std::underlying_type_t<Enum> a, Enum b) {
return a <=> static_cast<std::underlying_type_t<Enum>>(b);
}
template<typename Enum> requires( is_scoped_enum_v<Enum> )
constexpr inline auto operator != (std::underlying_type_t<Enum> a, Enum b) {
return a != static_cast<std::underlying_type_t<Enum>>(b);
}
template<typename Enum> requires( is_scoped_enum_v<Enum> )
constexpr inline auto operator == (std::underlying_type_t<Enum> a, Enum b) {
return a == static_cast<std::underlying_type_t<Enum>>(b);
}

View File

@ -32,31 +32,40 @@ void denylist_handler(int client, const sock_cred *cred) {
return; return;
} }
int req = read_int(client); DenyResponse res = DenyResponse::ERROR;
int res = DAEMON_ERROR;
switch (req) { int code = read_int(client);
case ENFORCE_DENY: auto req = static_cast<DenyRequest>(code);
res = enable_deny();
break; if (code < 0 || code >= DenyRequest::END) {
case DISABLE_DENY: goto done;
res = disable_deny();
break;
case ADD_LIST:
res = add_list(client);
break;
case RM_LIST:
res = rm_list(client);
break;
case LS_LIST:
ls_list(client);
return;
case DENY_STATUS:
res = (zygisk_enabled && denylist_enforced) ? DENY_IS_ENFORCED : DENY_NOT_ENFORCED;
break;
} }
write_int(client, res); 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 = (zygisk_enabled && denylist_enforced) ? DenyResponse::ENFORCED
: DenyResponse::NOT_ENFORCED;
break;
case DenyRequest::END:
__builtin_unreachable();
}
done:
write_int(client, static_cast<int>(res));
close(client); close(client);
} }
@ -64,19 +73,19 @@ int denylist_cli(int argc, char **argv) {
if (argc < 2) if (argc < 2)
usage(); usage();
int req; DenyRequest req;
if (argv[1] == "enable"sv) if (argv[1] == "enable"sv)
req = ENFORCE_DENY; req = DenyRequest::ENFORCE;
else if (argv[1] == "disable"sv) else if (argv[1] == "disable"sv)
req = DISABLE_DENY; req = DenyRequest::DISABLE;
else if (argv[1] == "add"sv) else if (argv[1] == "add"sv)
req = ADD_LIST; req = DenyRequest::ADD;
else if (argv[1] == "rm"sv) else if (argv[1] == "rm"sv)
req = RM_LIST; req = DenyRequest::REMOVE;
else if (argv[1] == "ls"sv) else if (argv[1] == "ls"sv)
req = LS_LIST; req = DenyRequest::LIST;
else if (argv[1] == "status"sv) else if (argv[1] == "status"sv)
req = DENY_STATUS; req = DenyRequest::STATUS;
else if (argv[1] == "exec"sv && argc > 2) { else if (argv[1] == "exec"sv && argc > 2) {
xunshare(CLONE_NEWNS); xunshare(CLONE_NEWNS);
xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr); xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr);
@ -88,56 +97,54 @@ int denylist_cli(int argc, char **argv) {
} }
// Send request // Send request
int fd = connect_daemon(); int fd = deny_request(req);
write_int(fd, DENYLIST); if (req == DenyRequest::ADD || req == DenyRequest::REMOVE) {
write_int(fd, req);
if (req == ADD_LIST || req == RM_LIST) {
write_string(fd, argv[2]); write_string(fd, argv[2]);
write_string(fd, argv[3] ? argv[3] : ""); write_string(fd, argv[3] ? argv[3] : "");
} }
// Get response // Get response
int code = read_int(fd); int code = read_int(fd);
switch (code) { auto res = (code < 0 || code >= DenyResponse::END) ? DenyResponse::ERROR
case DAEMON_SUCCESS: : static_cast<DenyResponse>(code);
break; switch (res) {
case DENY_NOT_ENFORCED: case DenyResponse::NOT_ENFORCED:
fprintf(stderr, "Denylist is not enforced\n"); fprintf(stderr, "Denylist is not enforced\n");
goto return_code; goto return_code;
case DENY_IS_ENFORCED: case DenyResponse::ENFORCED:
fprintf(stderr, "Denylist is enforced\n"); fprintf(stderr, "Denylist is enforced\n");
goto return_code; goto return_code;
case DENYLIST_ITEM_EXIST: case DenyResponse::ITEM_EXIST:
fprintf(stderr, "Target already exists in denylist\n"); fprintf(stderr, "Target already exists in denylist\n");
goto return_code; goto return_code;
case DENYLIST_ITEM_NOT_EXIST: case DenyResponse::ITEM_NOT_EXIST:
fprintf(stderr, "Target does not exist in denylist\n"); fprintf(stderr, "Target does not exist in denylist\n");
goto return_code; goto return_code;
case DENY_NO_NS: case DenyResponse::NO_NS:
fprintf(stderr, "The kernel does not support mount namespace\n"); fprintf(stderr, "The kernel does not support mount namespace\n");
goto return_code; goto return_code;
case DENYLIST_INVALID_PKG: case DenyResponse::INVALID_PKG:
fprintf(stderr, "Invalid package / process name\n"); fprintf(stderr, "Invalid package / process name\n");
goto return_code; goto return_code;
case ROOT_REQUIRED: case DenyResponse::ERROR:
fprintf(stderr, "Root is required for this operation\n"); fprintf(stderr, "deny: Daemon error\n");
goto return_code; return -1;
case DAEMON_ERROR: case DenyResponse::OK:
default: break;
fprintf(stderr, "Daemon error\n"); case DenyResponse::END:
return DAEMON_ERROR; __builtin_unreachable();
} }
if (req == LS_LIST) { if (req == DenyRequest::LIST) {
string res; string out;
for (;;) { for (;;) {
read_string(fd, res); read_string(fd, out);
if (res.empty()) if (out.empty())
break; break;
printf("%s\n", res.data()); printf("%s\n", out.data());
} }
} }
return_code: return_code:
return req == DENY_STATUS ? (code == DENY_IS_ENFORCED ? 0 : 1) : code != DAEMON_SUCCESS; return req == DenyRequest::STATUS ? res != DenyResponse::ENFORCED : res != DenyResponse::OK;
} }

View File

@ -10,11 +10,36 @@
#define ISOLATED_MAGIC "isolated" #define ISOLATED_MAGIC "isolated"
enum class DenyRequest : int {
ENFORCE,
DISABLE,
ADD,
REMOVE,
LIST,
STATUS,
END
};
enum class DenyResponse: int {
OK,
ENFORCED,
NOT_ENFORCED,
ITEM_EXIST,
ITEM_NOT_EXIST,
INVALID_PKG,
NO_NS,
ERROR,
END
};
// CLI entries // CLI entries
int enable_deny(); DenyResponse enable_deny();
int disable_deny(); DenyResponse disable_deny();
int add_list(int client); DenyResponse add_list(int client);
int rm_list(int client); DenyResponse rm_list(int client);
void ls_list(int client); void ls_list(int client);
// Utility functions // Utility functions
@ -25,20 +50,8 @@ void revert_unmount();
extern std::atomic<bool> denylist_enforced; extern std::atomic<bool> denylist_enforced;
extern std::atomic<int> cached_manager_app_id; extern std::atomic<int> cached_manager_app_id;
enum : int { inline int deny_request(DenyRequest req) {
ENFORCE_DENY, int fd = connect_daemon(DaemonRequest::DENYLIST);
DISABLE_DENY, write_int(fd, static_cast<std::underlying_type_t<DenyRequest>>(req));
ADD_LIST, return fd;
RM_LIST, }
LS_LIST,
DENY_STATUS,
};
enum : int {
DENY_IS_ENFORCED = DAEMON_LAST + 1,
DENY_NOT_ENFORCED,
DENYLIST_ITEM_EXIST,
DENYLIST_ITEM_NOT_EXIST,
DENYLIST_INVALID_PKG,
DENY_NO_NS,
};

View File

@ -226,20 +226,20 @@ error:
return false; return false;
} }
static int add_list(const char *pkg, const char *proc) { static DenyResponse add_list(const char *pkg, const char *proc) {
if (proc[0] == '\0') if (proc[0] == '\0')
proc = pkg; proc = pkg;
if (!validate(pkg, proc)) if (!validate(pkg, proc))
return DENYLIST_INVALID_PKG; return DenyResponse::INVALID_PKG;
{ {
mutex_guard lock(data_lock); mutex_guard lock(data_lock);
if (!ensure_data()) if (!ensure_data())
return DAEMON_ERROR; return DenyResponse::ERROR;
auto p = add_hide_set(pkg, proc); auto p = add_hide_set(pkg, proc);
if (!p.second) if (!p.second)
return DENYLIST_ITEM_EXIST; return DenyResponse::ITEM_EXIST;
update_pkg_uid(*p.first, false); update_pkg_uid(*p.first, false);
} }
@ -248,21 +248,21 @@ static int add_list(const char *pkg, const char *proc) {
snprintf(sql, sizeof(sql), snprintf(sql, sizeof(sql),
"INSERT INTO denylist (package_name, process) VALUES('%s', '%s')", pkg, proc); "INSERT INTO denylist (package_name, process) VALUES('%s', '%s')", pkg, proc);
char *err = db_exec(sql); char *err = db_exec(sql);
db_err_cmd(err, return DAEMON_ERROR) db_err_cmd(err, return DenyResponse::ERROR)
return DAEMON_SUCCESS; return DenyResponse::OK;
} }
int add_list(int client) { DenyResponse add_list(int client) {
string pkg = read_string(client); string pkg = read_string(client);
string proc = read_string(client); string proc = read_string(client);
return add_list(pkg.data(), proc.data()); return add_list(pkg.data(), proc.data());
} }
static int rm_list(const char *pkg, const char *proc) { static DenyResponse rm_list(const char *pkg, const char *proc) {
{ {
mutex_guard lock(data_lock); mutex_guard lock(data_lock);
if (!ensure_data()) if (!ensure_data())
return DAEMON_ERROR; return DenyResponse::ERROR;
bool remove = false; bool remove = false;
@ -284,7 +284,7 @@ static int rm_list(const char *pkg, const char *proc) {
} }
if (!remove) if (!remove)
return DENYLIST_ITEM_NOT_EXIST; return DenyResponse::ITEM_NOT_EXIST;
} }
char sql[4096]; char sql[4096];
@ -294,11 +294,11 @@ static int rm_list(const char *pkg, const char *proc) {
snprintf(sql, sizeof(sql), snprintf(sql, sizeof(sql),
"DELETE FROM denylist WHERE package_name='%s' AND process='%s'", pkg, proc); "DELETE FROM denylist WHERE package_name='%s' AND process='%s'", pkg, proc);
char *err = db_exec(sql); char *err = db_exec(sql);
db_err_cmd(err, return DAEMON_ERROR) db_err_cmd(err, return DenyResponse::ERROR)
return DAEMON_SUCCESS; return DenyResponse::OK;
} }
int rm_list(int client) { DenyResponse rm_list(int client) {
string pkg = read_string(client); string pkg = read_string(client);
string proc = read_string(client); string proc = read_string(client);
return rm_list(pkg.data(), proc.data()); return rm_list(pkg.data(), proc.data());
@ -308,11 +308,11 @@ void ls_list(int client) {
{ {
mutex_guard lock(data_lock); mutex_guard lock(data_lock);
if (!ensure_data()) { if (!ensure_data()) {
write_int(client, DAEMON_ERROR); write_int(client, static_cast<int>(DenyResponse::ERROR));
return; return;
} }
write_int(client, DAEMON_SUCCESS); write_int(client,static_cast<int>(DenyResponse::OK));
for (const auto &[pkg, procs] : pkg_to_procs) { for (const auto &[pkg, procs] : pkg_to_procs) {
for (const auto &proc : procs) { for (const auto &proc : procs) {
@ -342,19 +342,19 @@ static void update_deny_config() {
db_err(err); db_err(err);
} }
int enable_deny() { DenyResponse enable_deny() {
if (denylist_enforced) { if (denylist_enforced) {
return DAEMON_SUCCESS; return DenyResponse::OK;
} else { } else {
mutex_guard lock(data_lock); mutex_guard lock(data_lock);
if (access("/proc/self/ns/mnt", F_OK) != 0) { if (access("/proc/self/ns/mnt", F_OK) != 0) {
LOGW("The kernel does not support mount namespace\n"); LOGW("The kernel does not support mount namespace\n");
return DENY_NO_NS; return DenyResponse::NO_NS;
} }
if (procfp == nullptr && (procfp = opendir("/proc")) == nullptr) if (procfp == nullptr && (procfp = opendir("/proc")) == nullptr)
return DAEMON_ERROR; return DenyResponse::ERROR;
LOGI("* Enable DenyList\n"); LOGI("* Enable DenyList\n");
@ -362,7 +362,7 @@ int enable_deny() {
if (!ensure_data()) { if (!ensure_data()) {
denylist_enforced = false; denylist_enforced = false;
return DAEMON_ERROR; return DenyResponse::ERROR;
} }
// On Android Q+, also kill blastula pool and all app zygotes // On Android Q+, also kill blastula pool and all app zygotes
@ -374,16 +374,16 @@ int enable_deny() {
} }
update_deny_config(); update_deny_config();
return DAEMON_SUCCESS; return DenyResponse::OK;
} }
int disable_deny() { DenyResponse disable_deny() {
if (denylist_enforced) { if (denylist_enforced) {
denylist_enforced = false; denylist_enforced = false;
LOGI("* Disable DenyList\n"); LOGI("* Disable DenyList\n");
} }
update_deny_config(); update_deny_config();
return DAEMON_SUCCESS; return DenyResponse::OK;
} }
void initialize_denylist() { void initialize_denylist() {

View File

@ -142,9 +142,7 @@ static int zygisk_log(int prio, const char *fmt, va_list ap) {
if (logd_fd < 0) { if (logd_fd < 0) {
// Change logging temporarily to prevent infinite recursion and stack overflow // Change logging temporarily to prevent infinite recursion and stack overflow
android_logging(); android_logging();
if (int fd = connect_daemon(); fd >= 0) { if (int fd = zygisk_request(ZygiskRequest::GET_LOG_PIPE); fd >= 0) {
write_int(fd, ZYGISK_REQUEST);
write_int(fd, ZYGISK_GET_LOG_PIPE);
if (read_int(fd) == 0) { if (read_int(fd) == 0) {
logd_fd = recv_fd(fd); logd_fd = recv_fd(fd);
} }
@ -178,10 +176,7 @@ static inline bool should_load_modules(uint32_t flags) {
} }
int remote_get_info(int uid, const char *process, uint32_t *flags, vector<int> &fds) { int remote_get_info(int uid, const char *process, uint32_t *flags, vector<int> &fds) {
if (int fd = connect_daemon(); fd >= 0) { if (int fd = zygisk_request(ZygiskRequest::GET_INFO); fd >= 0) {
write_int(fd, ZYGISK_REQUEST);
write_int(fd, ZYGISK_GET_INFO);
write_int(fd, uid); write_int(fd, uid);
write_string(fd, process); write_string(fd, process);
xxread(fd, flags, sizeof(*flags)); xxread(fd, flags, sizeof(*flags));
@ -404,28 +399,39 @@ static void get_moddir(int client) {
} }
void zygisk_handler(int client, const sock_cred *cred) { void zygisk_handler(int client, const sock_cred *cred) {
// using enum ZYGISK_REQUEST;
int code = read_int(client); int code = read_int(client);
char buf[256]; char buf[256];
switch (code) { if (code < ZygiskRequest::SETUP || code >= ZygiskRequest::END) {
case ZYGISK_SETUP: write_int(client, -1);
return;
}
auto req = static_cast<ZygiskRequest>(code);
if (req != ZygiskRequest::PASSTHROUGH && cred->context != "u:r:zygote:s0") {
return;
}
switch (req) {
case ZygiskRequest::SETUP:
setup_files(client, cred); setup_files(client, cred);
break; break;
case ZYGISK_PASSTHROUGH: case ZygiskRequest::PASSTHROUGH:
magiskd_passthrough(client); magiskd_passthrough(client);
break; break;
case ZYGISK_GET_INFO: case ZygiskRequest::GET_INFO:
get_process_info(client, cred); get_process_info(client, cred);
break; break;
case ZYGISK_GET_LOG_PIPE: case ZygiskRequest::GET_LOG_PIPE:
send_log_pipe(client); send_log_pipe(client);
break; break;
case ZYGISK_CONNECT_COMPANION: case ZygiskRequest::CONNECT_COMPANION:
get_exe(cred->pid, buf, sizeof(buf)); get_exe(cred->pid, buf, sizeof(buf));
connect_companion(client, str_ends(buf, "64")); connect_companion(client, str_ends(buf, "64"));
break; break;
case ZYGISK_GET_MODDIR: case ZygiskRequest::GET_MODDIR:
get_moddir(client); get_moddir(client);
break; break;
case ZygiskRequest::END:
__builtin_unreachable();
} }
close(client); close(client);
} }

View File

@ -317,9 +317,7 @@ bool ZygiskModule::RegisterModule(ApiTable *table, long *module) {
} }
int ZygiskModule::connectCompanion() const { int ZygiskModule::connectCompanion() const {
if (int fd = connect_daemon(); fd >= 0) { if (int fd = zygisk_request(ZygiskRequest::CONNECT_COMPANION); fd >= 0) {
write_int(fd, ZYGISK_REQUEST);
write_int(fd, ZYGISK_CONNECT_COMPANION);
write_int(fd, id); write_int(fd, id);
return fd; return fd;
} }
@ -327,9 +325,7 @@ int ZygiskModule::connectCompanion() const {
} }
int ZygiskModule::getModuleDir() const { int ZygiskModule::getModuleDir() const {
if (int fd = connect_daemon(); fd >= 0) { if (int fd = zygisk_request(ZygiskRequest::GET_MODDIR); fd >= 0) {
write_int(fd, ZYGISK_REQUEST);
write_int(fd, ZYGISK_GET_MODDIR);
write_int(fd, id); write_int(fd, id);
int dfd = recv_fd(fd); int dfd = recv_fd(fd);
close(fd); close(fd);

View File

@ -57,11 +57,8 @@ int app_process_main(int argc, char *argv[]) {
return 1; return 1;
} }
if (int socket = connect_daemon(); socket >= 0) { if (int socket = zygisk_request(ZygiskRequest::SETUP); socket >= 0) {
do { do {
write_int(socket, ZYGISK_REQUEST);
write_int(socket, ZYGISK_SETUP);
if (read_int(socket) != 0) if (read_int(socket) != 0)
break; break;
@ -176,9 +173,7 @@ int zygisk_main(int argc, char *argv[]) {
int is_64_bit = parse_int(argv[3]); int is_64_bit = parse_int(argv[3]);
if (fcntl(client, F_GETFD) < 0) if (fcntl(client, F_GETFD) < 0)
return 1; return 1;
if (int magiskd = connect_daemon(); magiskd >= 0) { if (int magiskd = zygisk_request(ZygiskRequest::PASSTHROUGH); magiskd >= 0) {
write_int(magiskd, ZYGISK_PASSTHROUGH);
write_int(magiskd, ZYGISK_PASSTHROUGH);
write_int(magiskd, is_64_bit); write_int(magiskd, is_64_bit);
if (read_int(magiskd) != 0) { if (read_int(magiskd) != 0) {

View File

@ -3,18 +3,21 @@
#include <stdint.h> #include <stdint.h>
#include <jni.h> #include <jni.h>
#include <vector> #include <vector>
#include <daemon.hpp>
#define INJECT_ENV_1 "MAGISK_INJ_1" #define INJECT_ENV_1 "MAGISK_INJ_1"
#define INJECT_ENV_2 "MAGISK_INJ_2" #define INJECT_ENV_2 "MAGISK_INJ_2"
#define MAGISKFD_ENV "MAGISKFD" #define MAGISKFD_ENV "MAGISKFD"
#define MAGISKTMP_ENV "MAGISKTMP" #define MAGISKTMP_ENV "MAGISKTMP"
enum : int { enum class ZygiskRequest : int {
ZYGISK_SETUP, SETUP,
ZYGISK_GET_INFO, GET_INFO,
ZYGISK_GET_LOG_PIPE, GET_LOG_PIPE,
ZYGISK_CONNECT_COMPANION, CONNECT_COMPANION,
ZYGISK_GET_MODDIR, GET_MODDIR,
PASSTHROUGH,
END
}; };
#if defined(__LP64__) #if defined(__LP64__)
@ -47,3 +50,10 @@ extern void *self_handle;
void hook_functions(); void hook_functions();
int remote_get_info(int uid, const char *process, uint32_t *flags, std::vector<int> &fds); int remote_get_info(int uid, const char *process, uint32_t *flags, std::vector<int> &fds);
int remote_request_unmount(); int remote_request_unmount();
inline int zygisk_request(ZygiskRequest req) {
int fd = connect_daemon(DaemonRequest::ZYGISK_REQUEST, false);
write_int(fd, static_cast<int>(req));
return fd;
}