-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjrunas.cpp
More file actions
304 lines (264 loc) · 9.5 KB
/
Copy pathjrunas.cpp
File metadata and controls
304 lines (264 loc) · 9.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include <dlfcn.h>
#include <errno.h>
#include <error.h>
#include <grp.h>
#include <limits.h>
#include <paths.h>
#include <poll.h>
#include <pty.h>
#include <pwd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/capability.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "android_ids.h"
#include "packages_list.h"
#ifndef UID_MAX
#define UID_MAX UINT_MAX
#endif
static void check_directory(const char* path, uid_t uid) {
struct stat st;
if (TEMP_FAILURE_RETRY(lstat(path, &st)) == -1) {
error(1, errno, "couldn't stat %s", path);
}
if (!S_ISDIR(st.st_mode)) {
error(1, 0, "%s not a directory: %o", path, st.st_mode);
}
if (st.st_uid != uid || st.st_gid != uid) {
error(1, 0, "%s has wrong owner: %d/%d, not %d", path, st.st_uid, st.st_gid, uid);
}
if ((st.st_mode & (S_IROTH | S_IWOTH)) != 0) {
error(1, 0, "%s readable or writable by others: %o", path, st.st_mode);
}
}
static void check_data_path(const char* package_name, const char* data_path, uid_t uid) {
if (data_path[0] != '/') {
error(1, 0, "%s data path not absolute: %s", package_name, data_path);
}
for (int nn = 1; data_path[nn] != '\0'; nn++) {
char subpath[PATH_MAX];
if (data_path[nn] != '/') continue;
if (data_path[nn + 1] == '\0') break;
if (nn >= (int)(sizeof subpath)) {
error(1, 0, "%s data path too long: %s", package_name, data_path);
}
if (nn >= 3 && data_path[nn - 3] == '/' && data_path[nn - 2] == '.' &&
data_path[nn - 1] == '.') {
error(1, 0, "%s contains '..': %s", package_name, data_path);
}
memcpy(subpath, data_path, nn);
subpath[nn] = '\0';
check_directory(subpath, AID_SYSTEM);
}
check_directory(data_path, uid);
}
static std::vector<gid_t> get_supplementary_gids(uid_t userAppId) {
std::vector<gid_t> gids;
int size = getgroups(0, nullptr);
if (size < 0) error(1, errno, "getgroups failed");
gids.resize(size);
if (size > 0) {
size = getgroups(size, gids.data());
if (size != static_cast<int>(gids.size())) error(1, errno, "getgroups failed");
}
gid_t shared_app_gid =
userAppId % AID_USER_OFFSET - AID_APP_START + AID_SHARED_GID_START;
gids.push_back(shared_app_gid);
gids.push_back(AID_READPROC);
return gids;
}
typedef int (*selinux_setcontext_fn)(uid_t, int, const char*, const char*);
static void set_selinux_context(uid_t uid, const char* seinfo, const char* pkgname) {
void* handle = dlopen("libselinux.so", RTLD_NOW);
if (handle == nullptr) error(1, 0, "dlopen libselinux.so failed: %s", dlerror());
auto set_context =
reinterpret_cast<selinux_setcontext_fn>(dlsym(handle, "selinux_android_setcontext"));
if (set_context == nullptr) {
error(1, 0, "dlsym selinux_android_setcontext failed: %s", dlerror());
}
std::string context = std::string(seinfo) + ":fromRunAs";
if (set_context(uid, 0, context.c_str(), pkgname) < 0) {
error(1, errno, "couldn't set SELinux security context '%s'", context.c_str());
}
}
static void retain_ptrace_capability() {
__user_cap_header_struct hdr = {};
hdr.version = _LINUX_CAPABILITY_VERSION_3;
hdr.pid = 0;
__user_cap_data_struct data[2] = {};
const unsigned int idx = CAP_SYS_PTRACE >> 5;
const unsigned int bit = 1u << (CAP_SYS_PTRACE & 31);
data[idx].effective = bit;
data[idx].permitted = bit;
data[idx].inheritable = bit;
if (capset(&hdr, data) != 0) error(1, errno, "capset(CAP_SYS_PTRACE) failed");
if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_SYS_PTRACE, 0, 0) != 0) {
error(1, errno, "PR_CAP_AMBIENT_RAISE(CAP_SYS_PTRACE) failed");
}
}
static void become_app_and_exec(uid_t app_id, const char* seinfo, const char* pkgname,
const std::string& data_dir, char** cmd_argv,
bool keep_ptrace) {
std::vector<gid_t> gids = get_supplementary_gids(app_id);
if (setgroups(gids.size(), gids.data()) == -1) error(1, errno, "setgroups failed");
if (keep_ptrace && prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
error(1, errno, "PR_SET_KEEPCAPS failed");
}
if (setresgid(app_id, app_id, app_id) == -1) error(1, errno, "setresgid failed");
if (setresuid(app_id, app_id, app_id) == -1) error(1, errno, "setresuid failed");
if (keep_ptrace) retain_ptrace_capability();
set_selinux_context(app_id, seinfo, pkgname);
if (TEMP_FAILURE_RETRY(chdir(data_dir.c_str())) == -1) {
error(1, errno, "couldn't chdir to package's data directory '%s'", data_dir.c_str());
}
setenv("HOME", data_dir.c_str(), 1);
setenv("PATH", _PATH_DEFPATH, 1);
unsetenv("IFS");
passwd* pw = getpwuid(app_id);
if (pw != nullptr) {
setenv("LOGNAME", pw->pw_name, 1);
setenv("SHELL", pw->pw_shell, 1);
setenv("USER", pw->pw_name, 1);
}
if (cmd_argv[0] != nullptr) {
execvp(cmd_argv[0], cmd_argv);
error(1, errno, "exec failed for %s", cmd_argv[0]);
}
execlp(_PATH_BSHELL, "sh", nullptr);
error(1, errno, "exec failed");
}
static volatile sig_atomic_t g_window_changed = 0;
static void handle_sigwinch(int) { g_window_changed = 1; }
static void write_all(int fd, const char* buf, size_t len) {
while (len > 0) {
ssize_t n = write(fd, buf, len);
if (n < 0) {
if (errno == EINTR) continue;
return;
}
buf += n;
len -= static_cast<size_t>(n);
}
}
static int run_on_pty(uid_t app_id, const char* seinfo, const char* pkgname,
const std::string& data_dir, char** cmd_argv, bool keep_ptrace) {
int ref_tty = isatty(STDOUT_FILENO) ? STDOUT_FILENO : STDIN_FILENO;
struct termios ref_attr;
bool have_attr = (tcgetattr(ref_tty, &ref_attr) == 0);
struct winsize ws;
bool have_ws = (ioctl(ref_tty, TIOCGWINSZ, &ws) == 0);
int master, slave;
if (openpty(&master, &slave, nullptr, have_attr ? &ref_attr : nullptr,
have_ws ? &ws : nullptr) == -1) {
error(1, errno, "openpty failed");
}
pid_t pid = fork();
if (pid == -1) error(1, errno, "fork failed");
if (pid == 0) {
close(master);
setsid();
ioctl(slave, TIOCSCTTY, 0);
dup2(slave, STDIN_FILENO);
dup2(slave, STDOUT_FILENO);
dup2(slave, STDERR_FILENO);
if (slave > STDERR_FILENO) close(slave);
become_app_and_exec(app_id, seinfo, pkgname, data_dir, cmd_argv, keep_ptrace);
_exit(127);
}
close(slave);
struct termios orig;
bool raw_set = false;
if (isatty(STDIN_FILENO) && tcgetattr(STDIN_FILENO, &orig) == 0) {
struct termios raw = orig;
cfmakeraw(&raw);
if (tcsetattr(STDIN_FILENO, TCSANOW, &raw) == 0) raw_set = true;
}
struct sigaction sa = {};
sa.sa_handler = handle_sigwinch;
sigaction(SIGWINCH, &sa, nullptr);
struct pollfd fds[2];
fds[0].fd = master;
fds[0].events = POLLIN;
fds[1].fd = STDIN_FILENO;
fds[1].events = POLLIN;
char buf[8192];
for (;;) {
if (poll(fds, 2, -1) < 0) {
if (errno != EINTR) break;
if (g_window_changed) {
g_window_changed = 0;
if (ioctl(ref_tty, TIOCGWINSZ, &ws) == 0) ioctl(master, TIOCSWINSZ, &ws);
}
continue;
}
if (fds[0].revents & POLLIN) {
ssize_t n = read(master, buf, sizeof buf);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) break;
write_all(STDOUT_FILENO, buf, static_cast<size_t>(n));
}
if (fds[1].fd >= 0 && (fds[1].revents & POLLIN)) {
ssize_t n = read(STDIN_FILENO, buf, sizeof buf);
if (n > 0) write_all(master, buf, static_cast<size_t>(n));
else if (!(n < 0 && errno == EINTR)) fds[1].fd = -1;
}
if (fds[0].revents & (POLLHUP | POLLERR)) break;
}
if (raw_set) tcsetattr(STDIN_FILENO, TCSANOW, &orig);
close(master);
int status;
if (waitpid(pid, &status, 0) == -1) return 1;
if (WIFEXITED(status)) return WEXITSTATUS(status);
if (WIFSIGNALED(status)) return 128 + WTERMSIG(status);
return 1;
}
int main(int argc, char* argv[]) {
const char* usage =
"usage: jrunas [--ptrace] <package-name> [--user <id>] [<command> [<args>]]";
int argi = 1;
bool keep_ptrace = false;
if (argi < argc && strcmp(argv[argi], "--ptrace") == 0) {
keep_ptrace = true;
argi++;
}
if (argi >= argc) error(1, 0, "%s", usage);
char* pkgname = argv[argi++];
int userId = 0;
if (argc - argi >= 2 && strcmp(argv[argi], "--user") == 0) {
userId = atoi(argv[argi + 1]);
if (userId < 0) error(1, 0, "negative user id: %d", userId);
argi += 2;
}
bool is_root = (getuid() == AID_ROOT);
gid_t old_egid = getegid();
if (!is_root && setegid(AID_PACKAGE_INFO) == -1) {
error(1, errno, "setegid(AID_PACKAGE_INFO) failed");
}
pkg_info info = parse_packages_list("/data/system/packages.list", pkgname);
if (!is_root && setegid(old_egid) == -1) {
error(1, errno, "couldn't restore egid");
}
if (!info.found || info.uid == 0) error(1, 0, "unknown package: %s", pkgname);
if ((UID_MAX - info.uid) / AID_USER_OFFSET < (uid_t)userId) {
error(1, 0, "user id too big: %d", userId);
}
uid_t userAppId = (AID_USER_OFFSET * userId) + info.uid;
if (userAppId < AID_APP_START) error(1, 0, "package not an application: %s", pkgname);
std::string data_dir = "/data/user/" + std::to_string(userId) + "/" + pkgname;
check_data_path(pkgname, data_dir.c_str(), userAppId);
char** cmd_argv = argv + argi;
if (isatty(STDIN_FILENO) || isatty(STDOUT_FILENO)) {
return run_on_pty(userAppId, info.seinfo.c_str(), pkgname, data_dir, cmd_argv, keep_ptrace);
}
become_app_and_exec(userAppId, info.seinfo.c_str(), pkgname, data_dir, cmd_argv, keep_ptrace);
return 1;
}