2 ** Copyright 2010, Adam Shanks (@ChainsDD)
3 ** Copyright 2008, Zinx Verituse (@zinxv)
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
9 ** http://www.apache.org/licenses/LICENSE-2.0
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
18 #include <sys/types.h>
19 #include <sys/socket.h>
22 #include <sys/select.h>
34 #include <sys/types.h>
41 struct passwd* ppwd = getpwnam("shell");
49 void exec_log(char *priority, char* logline) {
51 if ((pid = fork()) == 0) {
52 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline);
57 void exec_loge(const char* fmt, ...) {
60 char logline[PATH_MAX];
62 vsnprintf(logline, PATH_MAX, fmt, args);
64 exec_log("e", logline);
67 void exec_logw(const char* fmt, ...) {
70 char logline[PATH_MAX];
72 vsnprintf(logline, PATH_MAX, fmt, args);
74 exec_log("w", logline);
77 void exec_logd(const char* fmt, ...) {
80 char logline[PATH_MAX];
82 vsnprintf(logline, PATH_MAX, fmt, args);
84 exec_log("d", logline);
87 static int from_init(struct su_initiator *from) {
88 char path[PATH_MAX], exe[PATH_MAX];
89 char args[4096], *argv0, *argv_rest;
96 from->pid = getppid();
98 /* Get the command line */
99 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
100 fd = open(path, O_RDONLY);
102 PLOGE("Opening command line");
105 len = read(fd, args, sizeof(args));
108 if (len < 0 || len == sizeof(args)) {
109 PLOGEV("Reading command line", err);
115 for (i = 0; i < len; i++) {
116 if (args[i] == '\0') {
118 argv_rest = &args[i+1];
127 strncpy(from->args, argv_rest, sizeof(from->args));
128 from->args[sizeof(from->args)-1] = '\0';
130 from->args[0] = '\0';
133 /* If this isn't app_process, use the real path instead of argv[0] */
134 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
135 len = readlink(path, exe, sizeof(exe));
137 PLOGE("Getting exe path");
141 if (strcmp(exe, "/system/bin/app_process")) {
145 strncpy(from->bin, argv0, sizeof(from->bin));
146 from->bin[sizeof(from->bin)-1] = '\0';
151 static void read_options(struct su_context *ctx) {
154 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
155 fgets(mode, sizeof(mode), fp);
156 if (strcmp(mode, "user\n") == 0) {
157 ctx->user.multiuser_mode = MULTIUSER_MODE_USER;
158 } else if (strcmp(mode, "owner\n") == 0) {
159 ctx->user.multiuser_mode = MULTIUSER_MODE_OWNER;
165 static void user_init(struct su_context *ctx) {
166 if (ctx->from.uid > 99999) {
167 ctx->user.android_user_id = ctx->from.uid / 100000;
168 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
169 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
174 static void populate_environment(const struct su_context *ctx) {
180 pw = getpwuid(ctx->to.uid);
182 setenv("HOME", pw->pw_dir, 1);
183 setenv("SHELL", ctx->to.shell, 1);
184 if (ctx->to.login || ctx->to.uid) {
185 setenv("USER", pw->pw_name, 1);
186 setenv("LOGNAME", pw->pw_name, 1);
191 void set_identity(unsigned int uid) {
193 * Set effective uid back to root, otherwise setres[ug]id will fail
197 PLOGE("seteuid (root)");
200 if (setresgid(uid, uid, uid)) {
201 PLOGE("setresgid (%u)", uid);
204 if (setresuid(uid, uid, uid)) {
205 PLOGE("setresuid (%u)", uid);
210 static void socket_cleanup(struct su_context *ctx) {
211 if (ctx && ctx->sock_path[0]) {
212 if (unlink(ctx->sock_path))
213 PLOGE("unlink (%s)", ctx->sock_path);
214 ctx->sock_path[0] = 0;
219 * For use in signal handlers/atexit-function
220 * NOTE: su_ctx points to main's local variable.
221 * It's OK due to the program uses exit(3), not return from main()
223 static struct su_context *su_ctx = NULL;
225 static void cleanup(void) {
226 socket_cleanup(su_ctx);
229 static void cleanup_signal(int sig) {
230 socket_cleanup(su_ctx);
234 void sigchld_handler(int sig) {
235 child_cleanup(su_ctx);
239 static int socket_create_temp(char *path, size_t len) {
241 struct sockaddr_un sun;
243 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
248 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
249 PLOGE("fcntl FD_CLOEXEC");
253 memset(&sun, 0, sizeof(sun));
254 sun.sun_family = AF_LOCAL;
255 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
256 memset(sun.sun_path, 0, sizeof(sun.sun_path));
257 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
260 * Delete the socket to protect from situations when
261 * something bad occured previously and the kernel reused pid from that process.
262 * Small probability, isn't it.
264 unlink(sun.sun_path);
266 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
271 if (listen(fd, 1) < 0) {
282 static int socket_accept(int serv_fd) {
287 /* Wait 20 seconds for a connection, then give up. */
291 FD_SET(serv_fd, &fds);
293 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
294 } while (rc < 0 && errno == EINTR);
300 fd = accept(serv_fd, NULL, NULL);
309 static int socket_send_request(int fd, const struct su_context *ctx) {
311 size_t bin_size, cmd_size;
314 #define write_token(fd, data) \
316 uint32_t __data = htonl(data); \
317 size_t __count = sizeof(__data); \
318 size_t __len = write((fd), &__data, __count); \
319 if (__len != __count) { \
320 PLOGE("write(" #data ")"); \
325 write_token(fd, PROTO_VERSION);
326 write_token(fd, PATH_MAX);
327 write_token(fd, ARG_MAX);
328 write_token(fd, ctx->from.uid);
329 write_token(fd, ctx->to.uid);
330 bin_size = strlen(ctx->from.bin) + 1;
331 write_token(fd, bin_size);
332 len = write(fd, ctx->from.bin, bin_size);
333 if (len != bin_size) {
337 cmd = get_command(&ctx->to);
338 cmd_size = strlen(cmd) + 1;
339 write_token(fd, cmd_size);
340 len = write(fd, cmd, cmd_size);
341 if (len != cmd_size) {
348 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
351 len = read(fd, result, result_len-1);
353 PLOGE("read(result)");
361 static void usage(int status) {
362 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
365 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
367 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
368 " -h, --help display this help message and exit\n"
369 " -, -l, --login pretend the shell to be a login shell\n"
371 " --preserve-environment do not change environment variables\n"
372 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
373 " -v, --version display version number and exit\n"
374 " -V display version code and exit,\n"
375 " this is used almost exclusively by Superuser.apk\n");
379 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
380 char *cmd = get_command(&ctx->to);
382 // No send to UI denied requests for shell and root users (they are in the log)
383 if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
384 send_result(ctx, DENY);
386 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
387 fprintf(stderr, "%s\n", strerror(EACCES));
391 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
396 // No send to UI accepted requests for shell and root users (they are in the log)
397 if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
398 send_result(ctx, ALLOW);
401 arg0 = strrchr (ctx->to.shell, '/');
402 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
404 int s = strlen(arg0) + 2;
415 populate_environment(ctx);
416 set_identity(ctx->to.uid);
419 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
420 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
422 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
423 ctx->from.uid, ctx->from.bin,
424 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
425 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
426 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
428 argc = ctx->to.optind;
429 if (ctx->to.command) {
430 ctx->to.argv[--argc] = ctx->to.command;
431 ctx->to.argv[--argc] = "-c";
433 ctx->to.argv[--argc] = arg0;
434 execv(ctx->to.shell, ctx->to.argv + argc);
437 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
442 * CyanogenMod-specific behavior
444 * we can't simply use the property service, since we aren't launched from init
445 * and can't trust the location of the property workspace.
446 * Find the properties ourselves.
448 int access_disabled(const struct su_initiator *from) {
450 char build_type[PROPERTY_VALUE_MAX];
451 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
454 data = read_file("/system/build.prop");
455 if (check_property(data, "ro.cm.version")) {
456 get_property(data, build_type, "ro.build.type", "");
459 data = read_file("/default.prop");
460 get_property(data, debuggable, "ro.debuggable", "0");
462 /* only allow su on debuggable builds */
463 if (strcmp("1", debuggable) != 0) {
464 LOGE("Root access is disabled on non-debug builds");
468 data = read_file("/data/property/persist.sys.root_access");
471 if (len >= PROPERTY_VALUE_MAX)
472 memcpy(enabled, "1", 2);
474 memcpy(enabled, data, len + 1);
477 memcpy(enabled, "1", 2);
479 /* enforce persist.sys.root_access on non-eng builds for apps */
480 if (strcmp("eng", build_type) != 0 &&
481 from->uid != AID_SHELL && from->uid != AID_ROOT &&
482 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
483 LOGE("Apps root access is disabled by system setting - "
484 "enable it under settings -> developer options");
488 /* disallow su in a shell if appropriate */
489 if (from->uid == AID_SHELL &&
490 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
491 LOGE("Shell root access is disabled by a system setting - "
492 "enable it under settings -> developer options");
500 int main(int argc, char *argv[]) {
501 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
502 /* The same list than GLibc at this point */
503 static const char* const unsec_vars[] = {
527 "LD_AOUT_LIBRARY_PATH",
529 // not listed in linker, used due to system() call
532 const char* const* cp = unsec_vars;
533 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
540 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
541 * This occurs on Android 4.0+
543 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
547 struct su_context ctx = {
558 .shell = DEFAULT_SHELL,
565 .android_user_id = 0,
566 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
567 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
571 int c, socket_serv_fd, fd;
572 char buf[64], *result;
574 struct option long_opts[] = {
575 { "command", required_argument, NULL, 'c' },
576 { "help", no_argument, NULL, 'h' },
577 { "login", no_argument, NULL, 'l' },
578 { "preserve-environment", no_argument, NULL, 'p' },
579 { "shell", required_argument, NULL, 's' },
580 { "version", no_argument, NULL, 'v' },
581 { NULL, 0, NULL, 0 },
584 while ((c = getopt_long(argc, argv, "+c:hlmps:Vv", long_opts, NULL)) != -1) {
587 ctx.to.command = optarg;
600 ctx.to.shell = optarg;
603 printf("%d\n", VERSION_CODE);
606 printf("%s\n", VERSION);
609 /* Bionic getopt_long doesn't terminate its error output by newline */
610 fprintf(stderr, "\n");
614 if (optind < argc && !strcmp(argv[optind], "-")) {
618 /* username or uid */
619 if (optind < argc && strcmp(argv[optind], "--")) {
621 pw = getpwnam(argv[optind]);
625 /* It seems we shouldn't do this at all */
627 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
628 if (errno || *endptr) {
629 LOGE("Unknown id: %s\n", argv[optind]);
630 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
634 ctx.to.uid = pw->pw_uid;
638 if (optind < argc && !strcmp(argv[optind], "--")) {
641 ctx.to.optind = optind;
644 if (from_init(&ctx.from) < 0) {
651 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0)
654 if (access_disabled(&ctx.from))
657 ctx.umask = umask(027);
659 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL)
662 if (stat(ctx.user.database_path, &st) < 0) {
667 if (st.st_gid != st.st_uid)
669 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
670 (int)st.st_uid, (int)st.st_gid);
674 mkdir(REQUESTOR_CACHE_PATH, 0770);
675 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
676 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
680 if (setgroups(0, NULL)) {
684 if (setegid(st.st_gid)) {
685 PLOGE("setegid (%lu)", st.st_gid);
688 if (seteuid(st.st_uid)) {
689 PLOGE("seteuid (%lu)", st.st_uid);
693 dballow = database_check(&ctx);
695 case INTERACTIVE: break;
696 case ALLOW: allow(&ctx); /* never returns */
698 default: deny(&ctx); /* never returns too */
701 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
703 if (socket_serv_fd < 0) {
707 signal(SIGHUP, cleanup_signal);
708 signal(SIGPIPE, cleanup_signal);
709 signal(SIGTERM, cleanup_signal);
710 signal(SIGQUIT, cleanup_signal);
711 signal(SIGINT, cleanup_signal);
712 signal(SIGABRT, cleanup_signal);
714 if (send_request(&ctx) < 0) {
720 fd = socket_accept(socket_serv_fd);
724 if (socket_send_request(fd, &ctx)) {
727 if (socket_receive_result(fd, buf, sizeof(buf))) {
732 close(socket_serv_fd);
733 socket_cleanup(&ctx);
737 #define SOCKET_RESPONSE "socket:"
738 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
739 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
741 result += sizeof(SOCKET_RESPONSE) - 1;
743 if (!strcmp(result, "DENY")) {
745 } else if (!strcmp(result, "ALLOW")) {
748 LOGE("unknown response from Superuser Requestor: %s", result);