Restructure project files

This commit is contained in:
topjohnwu
2023-11-08 01:46:02 -08:00
parent ecb31eed40
commit 65c18f9c09
44 changed files with 85 additions and 113 deletions

View File

@@ -0,0 +1,146 @@
#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 = (zygisk_enabled && 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(MainRequest::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;
}

View File

@@ -0,0 +1,46 @@
#pragma once
#include <pthread.h>
#include <string_view>
#include <functional>
#include <map>
#include <atomic>
#include <core.hpp>
#define ISOLATED_MAGIC "isolated"
namespace DenyRequest {
enum : int {
ENFORCE,
DISABLE,
ADD,
REMOVE,
LIST,
STATUS,
END
};
}
namespace DenyResponse {
enum : int {
OK,
ENFORCED,
NOT_ENFORCED,
ITEM_EXIST,
ITEM_NOT_EXIST,
INVALID_PKG,
NO_NS,
ERROR,
END
};
}
// CLI entries
int enable_deny();
int disable_deny();
int add_list(int client);
int rm_list(int client);
void ls_list(int client);

View File

@@ -0,0 +1,42 @@
#include <set>
#include <sys/mount.h>
#include <consts.hpp>
#include <base.hpp>
#include <core.hpp>
#include "deny.hpp"
using namespace std;
static void lazy_unmount(const char* mountpoint) {
if (umount2(mountpoint, MNT_DETACH) != -1)
LOGD("denylist: Unmounted (%s)\n", mountpoint);
}
void revert_unmount() {
set<string> targets;
// Unmount dummy skeletons and MAGISKTMP
// since mirror nodes are always mounted under skeleton, we don't have to specifically unmount
for (auto &info: parse_mount_info("self")) {
if (info.source == "magisk" || info.source == "worker" || // magisktmp tmpfs
info.root.starts_with("/adb/modules")) { // bind mount from data partition
targets.insert(info.target);
}
}
if (targets.empty()) return;
auto last_target = *targets.cbegin() + '/';
for (auto iter = next(targets.cbegin()); iter != targets.cend();) {
if (iter->starts_with(last_target)) {
iter = targets.erase(iter);
} else {
last_target = *iter++ + '/';
}
}
for (auto &s : targets)
lazy_unmount(s.data());
}

View File

@@ -0,0 +1,417 @@
#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;
atomic_flag skip_pkg_rescan;
// 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;
#define do_kill (zygisk_enabled && denylist_enforced)
static void rescan_apps() {
LOGD("denylist: rescanning apps\n");
app_id_to_pkgs.clear();
auto data_dir = xopen_dir(APP_DATA_DIR);
if (!data_dir)
return;
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()))) {
struct stat st{};
// For each package
if (xfstatat(dfd, entry->d_name, &st, 0))
continue;
int app_id = to_app_id(st.st_uid);
if (auto it = pkg_to_procs.find(entry->d_name); it != pkg_to_procs.end()) {
app_id_to_pkgs[app_id].insert(it->first);
}
}
} else {
close(dfd);
}
}
}
static void update_pkg_uid(const string &pkg, bool remove) {
auto data_dir = xopen_dir(APP_DATA_DIR);
if (!data_dir)
return;
dirent *entry;
struct stat st{};
char buf[PATH_MAX] = {0};
// For each user
while ((entry = xreaddir(data_dir.get()))) {
ssprintf(buf, sizeof(buf), "%s/%s", entry->d_name, pkg.data());
if (fstatat(dirfd(data_dir.get()), buf, &st, 0) == 0) {
int app_id = to_app_id(st.st_uid);
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].insert(pkg);
}
break;
}
}
}
// 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;
}
static 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 (!do_kill)
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;
}
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_);
char *err = db_exec("SELECT * FROM denylist", [](db_row &row) -> bool {
add_hide_set(row["package_name"].data(), row["process"].data());
return true;
});
db_err_cmd(err, goto error)
default_new(app_id_to_pkgs_);
rescan_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;
if (!add_hide_set(pkg, proc))
return DenyResponse::ITEM_EXIST;
auto it = pkg_to_procs.find(pkg);
update_pkg_uid(it->first, false);
}
// Add to database
char sql[4096];
ssprintf(sql, sizeof(sql),
"INSERT INTO denylist (package_name, process) VALUES('%s', '%s')", pkg, proc);
char *err = db_exec(sql);
db_err_cmd(err, return DenyResponse::ERROR)
return 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_pkg_uid(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_pkg_uid(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);
char *err = db_exec(sql);
db_err_cmd(err, return DenyResponse::ERROR)
return 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;
}
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);
}
static void update_deny_config() {
char sql[64];
sprintf(sql, "REPLACE INTO settings (key,value) VALUES('%s',%d)",
DB_SETTING_KEYS[DENYLIST_CONFIG], denylist_enforced.load());
char *err = db_exec(sql);
db_err(err);
}
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");
denylist_enforced = true;
if (!ensure_data()) {
denylist_enforced = false;
return DenyResponse::ERROR;
}
// On Android Q+, also kill blastula pool and all app zygotes
if (SDK_INT >= 29 && zygisk_enabled) {
kill_process("usap32", true);
kill_process("usap64", true);
kill_process<&proc_context_match>("u:r:app_zygote:s0", true);
}
}
update_deny_config();
return DenyResponse::OK;
}
int disable_deny() {
if (denylist_enforced) {
denylist_enforced = false;
LOGI("* Disable DenyList\n");
}
update_deny_config();
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;
if (!skip_pkg_rescan.test_and_set())
rescan_apps();
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;
}