Implement su_daemon in Rust

This commit is contained in:
topjohnwu
2025-02-02 22:08:41 +08:00
committed by John Wu
parent ab86732c89
commit a786801141
15 changed files with 857 additions and 710 deletions
+197 -25
View File
@@ -13,13 +13,24 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <algorithm>
#include <consts.hpp>
#include <base.hpp>
#include <flags.h>
#include <core.hpp>
#include "su.hpp"
#include "pts.hpp"
using namespace std;
#define DEFAULT_SHELL "/system/bin/sh"
// Constants for atty
#define ATTY_IN (1 << 0)
#define ATTY_OUT (1 << 1)
#define ATTY_ERR (1 << 2)
int quit_signals[] = { SIGALRM, SIGABRT, SIGHUP, SIGPIPE, SIGQUIT, SIGTERM, SIGINT, 0 };
[[noreturn]] static void usage(int status) {
@@ -97,7 +108,7 @@ int su_client_main(int argc, char *argv[]) {
{ nullptr, 0, nullptr, 0 },
};
su_request su_req;
auto req = SuRequest::New();
for (int i = 0; i < argc; i++) {
// Replace -cn and -z with -Z for backwards compatibility
@@ -110,25 +121,28 @@ int su_client_main(int argc, char *argv[]) {
while ((c = getopt_long(argc, argv, "c:hlmps:VvuZ:Mt:g:G:", long_opts, nullptr)) != -1) {
switch (c) {
case 'c':
case 'c': {
string command;
for (int i = optind - 1; i < argc; ++i) {
if (!su_req.command.empty())
su_req.command += ' ';
su_req.command += argv[i];
if (!command.empty())
command += ' ';
command += argv[i];
}
req.command = command;
optind = argc;
break;
}
case 'h':
usage(EXIT_SUCCESS);
case 'l':
su_req.login = true;
req.login = true;
break;
case 'm':
case 'p':
su_req.keepenv = true;
req.keep_env = true;
break;
case 's':
su_req.shell = optarg;
req.shell = optarg;
break;
case 'V':
printf("%d\n", MAGISK_VER_CODE);
@@ -137,33 +151,36 @@ int su_client_main(int argc, char *argv[]) {
printf("%s\n", MAGISK_VERSION ":MAGISKSU");
exit(EXIT_SUCCESS);
case 'Z':
su_req.context = optarg;
req.context = optarg;
break;
case 'M':
case 't':
if (su_req.target != -1) {
if (req.target_pid != -1) {
fprintf(stderr, "Can't use -M and -t at the same time\n");
usage(EXIT_FAILURE);
}
if (optarg == nullptr) {
su_req.target = 0;
req.target_pid = 0;
} else {
su_req.target = parse_int(optarg);
if (*optarg == '-' || su_req.target == -1) {
req.target_pid = parse_int(optarg);
if (*optarg == '-' || req.target_pid == -1) {
fprintf(stderr, "Invalid PID: %s\n", optarg);
usage(EXIT_FAILURE);
}
}
break;
case 'g':
case 'G':
case 'G': {
vector<gid_t> gids;
if (int gid = parse_int(optarg); gid >= 0) {
su_req.gids.insert(c == 'g' ? su_req.gids.begin() : su_req.gids.end(), gid);
gids.insert(c == 'g' ? gids.begin() : gids.end(), gid);
} else {
fprintf(stderr, "Invalid GID: %s\n", optarg);
usage(EXIT_FAILURE);
}
std::copy(gids.begin(), gids.end(), std::back_inserter(req.gids));
break;
}
default:
/* Bionic getopt_long doesn't terminate its error output by newline */
fprintf(stderr, "\n");
@@ -172,7 +189,7 @@ int su_client_main(int argc, char *argv[]) {
}
if (optind < argc && strcmp(argv[optind], "-") == 0) {
su_req.login = true;
req.login = true;
optind++;
}
/* username or uid */
@@ -180,9 +197,9 @@ int su_client_main(int argc, char *argv[]) {
struct passwd *pw;
pw = getpwnam(argv[optind]);
if (pw)
su_req.uid = pw->pw_uid;
req.target_uid = pw->pw_uid;
else
su_req.uid = parse_int(argv[optind]);
req.target_uid = parse_int(argv[optind]);
optind++;
}
@@ -191,12 +208,8 @@ int su_client_main(int argc, char *argv[]) {
// 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);
// Send request
req.write_to_fd(fd);
// Wait for ack from daemon
if (read_int(fd)) {
@@ -239,3 +252,162 @@ int su_client_main(int argc, char *argv[]) {
return code;
}
// Set effective uid back to root, otherwise setres[ug]id will fail if uid isn't root
static void set_identity(int uid, const rust::Vec<gid_t> &groups) {
if (seteuid(0)) {
PLOGE("seteuid (root)");
}
gid_t gid;
if (!groups.empty()) {
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 exec_root_shell(int client, int pid, SuRequest &req, MntNsMode mode) {
// 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 (req.target_pid == -1)
req.target_pid = pid;
else if (req.target_pid == 0)
mode = MntNsMode::Global;
else if (mode == MntNsMode::Global)
mode = MntNsMode::Requester;
switch (mode) {
case MntNsMode::Global:
LOGD("su: use global namespace\n");
break;
case MntNsMode::Requester:
LOGD("su: use namespace of pid=[%d]\n", req.target_pid);
switch_mnt_ns(req.target_pid);
break;
case MntNsMode::Isolate:
LOGD("su: use new isolated namespace\n");
switch_mnt_ns(req.target_pid);
xunshare(CLONE_NEWNS);
xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr);
break;
}
const char *argv[4] = { nullptr };
argv[0] = req.login ? "-" : req.shell.c_str();
if (!req.command.empty()) {
argv[1] = "-c";
argv[2] = req.command.c_str();
}
// Setup environment
umask(022);
char path[32];
ssprintf(path, sizeof(path), "/proc/%d/cwd", pid);
char cwd[4096];
if (realpath(path, cwd, sizeof(cwd)) > 0)
chdir(cwd);
ssprintf(path, sizeof(path), "/proc/%d/environ", 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 (!req.keep_env) {
struct passwd *pw;
pw = getpwuid(req.target_uid);
if (pw) {
setenv("HOME", pw->pw_dir, 1);
setenv("USER", pw->pw_name, 1);
setenv("LOGNAME", pw->pw_name, 1);
setenv("SHELL", req.shell.c_str(), 1);
}
}
// Unblock all signals
sigset_t block_set;
sigemptyset(&block_set);
sigprocmask(SIG_SETMASK, &block_set, nullptr);
if (!req.context.empty()) {
auto f = xopen_file("/proc/self/attr/exec", "we");
if (f) fprintf(f.get(), "%s", req.context.c_str());
}
set_identity(req.target_uid, req.gids);
execvp(req.shell.c_str(), (char **) argv);
fprintf(stderr, "Cannot execute %s: %s\n", req.shell.c_str(), strerror(errno));
PLOGE("exec");
}