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);
66 void exec_logw(const char* fmt, ...) {
69 char logline[PATH_MAX];
71 vsnprintf(logline, PATH_MAX, fmt, args);
73 exec_log("w", logline);
75 void exec_logd(const char* fmt, ...) {
78 char logline[PATH_MAX];
80 vsnprintf(logline, PATH_MAX, fmt, args);
82 exec_log("d", logline);
85 static int from_init(struct su_initiator *from)
87 char path[PATH_MAX], exe[PATH_MAX];
88 char args[4096], *argv0, *argv_rest;
95 from->pid = getppid();
97 /* Get the command line */
98 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
99 fd = open(path, O_RDONLY);
101 PLOGE("Opening command line");
104 len = read(fd, args, sizeof(args));
107 if (len < 0 || len == sizeof(args)) {
108 PLOGEV("Reading command line", err);
114 for (i = 0; i < len; i++) {
115 if (args[i] == '\0') {
117 argv_rest = &args[i+1];
126 strncpy(from->args, argv_rest, sizeof(from->args));
127 from->args[sizeof(from->args)-1] = '\0';
129 from->args[0] = '\0';
132 /* If this isn't app_process, use the real path instead of argv[0] */
133 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
134 len = readlink(path, exe, sizeof(exe));
136 PLOGE("Getting exe path");
140 if (strcmp(exe, "/system/bin/app_process")) {
144 strncpy(from->bin, argv0, sizeof(from->bin));
145 from->bin[sizeof(from->bin)-1] = '\0';
150 static void read_options(struct su_context *ctx)
154 if ((fp = fopen(REQUESTOR_OPTIONS, "r"))) {
155 fgets(mode, sizeof(mode), fp);
156 if (strcmp(mode, "user\n") == 0) {
157 ctx->user.owner_mode = 0;
158 } else if (strcmp(mode, "owner\n") == 0) {
159 ctx->user.owner_mode = 1;
164 static void user_init(struct su_context *ctx)
166 if (ctx->from.uid > 99999) {
167 ctx->user.userid = ctx->from.uid / 100000;
168 if (!ctx->user.owner_mode) {
169 snprintf(ctx->user.data_path, PATH_MAX, "/data/user/%d/%s",
170 ctx->user.userid, REQUESTOR);
171 snprintf(ctx->user.store_path, PATH_MAX, "/data/user/%d/%s/files/stored",
172 ctx->user.userid, REQUESTOR);
173 snprintf(ctx->user.store_default, PATH_MAX, "/data/user/%d/%s/files/stored/default",
174 ctx->user.userid, REQUESTOR);
179 static void populate_environment(const struct su_context *ctx)
186 pw = getpwuid(ctx->to.uid);
188 setenv("HOME", pw->pw_dir, 1);
189 setenv("SHELL", ctx->to.shell, 1);
190 if (ctx->to.login || ctx->to.uid) {
191 setenv("USER", pw->pw_name, 1);
192 setenv("LOGNAME", pw->pw_name, 1);
197 void set_identity(unsigned int uid)
200 * Set effective uid back to root, otherwise setres[ug]id will fail
204 PLOGE("seteuid (root)");
207 if (setresgid(uid, uid, uid)) {
208 PLOGE("setresgid (%u)", uid);
211 if (setresuid(uid, uid, uid)) {
212 PLOGE("setresuid (%u)", uid);
217 static void socket_cleanup(struct su_context *ctx)
219 if (ctx && ctx->sock_path[0]) {
220 if (unlink(ctx->sock_path))
221 PLOGE("unlink (%s)", ctx->sock_path);
222 ctx->sock_path[0] = 0;
227 * For use in signal handlers/atexit-function
228 * NOTE: su_ctx points to main's local variable.
229 * It's OK due to the program uses exit(3), not return from main()
231 static struct su_context *su_ctx = NULL;
233 static void cleanup(void)
235 socket_cleanup(su_ctx);
238 static void cleanup_signal(int sig)
240 socket_cleanup(su_ctx);
244 void sigchld_handler(int sig)
246 child_cleanup(su_ctx);
250 static int socket_create_temp(char *path, size_t len)
253 struct sockaddr_un sun;
255 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
260 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
261 PLOGE("fcntl FD_CLOEXEC");
265 memset(&sun, 0, sizeof(sun));
266 sun.sun_family = AF_LOCAL;
267 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
268 memset(sun.sun_path, 0, sizeof(sun.sun_path));
269 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
272 * Delete the socket to protect from situations when
273 * something bad occured previously and the kernel reused pid from that process.
274 * Small probability, isn't it.
276 unlink(sun.sun_path);
278 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
283 if (listen(fd, 1) < 0) {
294 static int socket_accept(int serv_fd)
300 /* Wait 20 seconds for a connection, then give up. */
304 FD_SET(serv_fd, &fds);
306 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
307 } while (rc < 0 && errno == EINTR);
313 fd = accept(serv_fd, NULL, NULL);
322 static int socket_send_request(int fd, const struct su_context *ctx)
325 size_t bin_size, cmd_size;
328 #define write_token(fd, data) \
330 uint32_t __data = htonl(data); \
331 size_t __count = sizeof(__data); \
332 size_t __len = write((fd), &__data, __count); \
333 if (__len != __count) { \
334 PLOGE("write(" #data ")"); \
339 write_token(fd, PROTO_VERSION);
340 write_token(fd, PATH_MAX);
341 write_token(fd, ARG_MAX);
342 write_token(fd, ctx->from.uid);
343 write_token(fd, ctx->to.uid);
344 bin_size = strlen(ctx->from.bin) + 1;
345 write_token(fd, bin_size);
346 len = write(fd, ctx->from.bin, bin_size);
347 if (len != bin_size) {
351 cmd = get_command(&ctx->to);
352 cmd_size = strlen(cmd) + 1;
353 write_token(fd, cmd_size);
354 len = write(fd, cmd, cmd_size);
355 if (len != cmd_size) {
362 static int socket_receive_result(int fd, char *result, ssize_t result_len)
366 len = read(fd, result, result_len-1);
368 PLOGE("read(result)");
376 static void usage(int status)
378 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
381 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
383 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
384 " -h, --help display this help message and exit\n"
385 " -, -l, --login pretend the shell to be a login shell\n"
387 " --preserve-environment do not change environment variables\n"
388 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
389 " -v, --version display version number and exit\n"
390 " -V display version code and exit,\n"
391 " this is used almost exclusively by Superuser.apk\n");
395 static __attribute__ ((noreturn)) void deny(struct su_context *ctx)
397 char *cmd = get_command(&ctx->to);
399 // No send to UI denied requests for shell and root users (they are in the log)
400 if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
401 send_intent(ctx, DENY, ACTION_RESULT);
403 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
404 fprintf(stderr, "%s\n", strerror(EACCES));
408 static __attribute__ ((noreturn)) void allow(struct su_context *ctx)
414 // No send to UI accepted requests for shell and root users (they are in the log)
415 if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
416 send_intent(ctx, ALLOW, ACTION_RESULT);
419 arg0 = strrchr (ctx->to.shell, '/');
420 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
422 int s = strlen(arg0) + 2;
433 populate_environment(ctx);
434 set_identity(ctx->to.uid);
437 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
438 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
440 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
441 ctx->from.uid, ctx->from.bin,
442 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
443 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
444 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
446 argc = ctx->to.optind;
447 if (ctx->to.command) {
448 ctx->to.argv[--argc] = ctx->to.command;
449 ctx->to.argv[--argc] = "-c";
451 ctx->to.argv[--argc] = arg0;
452 execv(ctx->to.shell, ctx->to.argv + argc);
455 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
460 * CyanogenMod-specific behavior
462 * we can't simply use the property service, since we aren't launched from init
463 * and can't trust the location of the property workspace.
464 * Find the properties ourselves.
466 int access_disabled(const struct su_initiator *from)
469 char build_type[PROPERTY_VALUE_MAX];
470 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
473 data = read_file("/system/build.prop");
474 if (check_property(data, "ro.cm.version")) {
475 get_property(data, build_type, "ro.build.type", "");
478 data = read_file("/default.prop");
479 get_property(data, debuggable, "ro.debuggable", "0");
481 /* only allow su on debuggable builds */
482 if (strcmp("1", debuggable) != 0) {
483 LOGE("Root access is disabled on non-debug builds");
487 data = read_file("/data/property/persist.sys.root_access");
490 if (len >= PROPERTY_VALUE_MAX)
491 memcpy(enabled, "1", 2);
493 memcpy(enabled, data, len + 1);
496 memcpy(enabled, "1", 2);
498 /* enforce persist.sys.root_access on non-eng builds for apps */
499 if (strcmp("eng", build_type) != 0 &&
500 from->uid != AID_SHELL && from->uid != AID_ROOT &&
501 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
502 LOGE("Apps root access is disabled by system setting - "
503 "enable it under settings -> developer options");
507 /* disallow su in a shell if appropriate */
508 if (from->uid == AID_SHELL &&
509 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
510 LOGE("Shell root access is disabled by a system setting - "
511 "enable it under settings -> developer options");
519 int main(int argc, char *argv[])
521 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
522 /* The same list than GLibc at this point */
523 static const char* const unsec_vars[] = {
547 "LD_AOUT_LIBRARY_PATH",
549 // not listed in linker, used due to system() call
552 const char* const* cp = unsec_vars;
553 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
560 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
561 * This occurs on Android 4.0+
563 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
567 struct su_context ctx = {
578 .shell = DEFAULT_SHELL,
587 .data_path = REQUESTOR_DATA_PATH,
588 .store_path = REQUESTOR_STORED_PATH,
589 .store_default = REQUESTOR_STORED_DEFAULT,
593 int c, socket_serv_fd, fd;
594 char buf[64], *result;
596 struct option long_opts[] = {
597 { "command", required_argument, NULL, 'c' },
598 { "help", no_argument, NULL, 'h' },
599 { "login", no_argument, NULL, 'l' },
600 { "preserve-environment", no_argument, NULL, 'p' },
601 { "shell", required_argument, NULL, 's' },
602 { "version", no_argument, NULL, 'v' },
603 { NULL, 0, NULL, 0 },
606 while ((c = getopt_long(argc, argv, "+c:hlmps:Vv", long_opts, NULL)) != -1) {
609 ctx.to.command = optarg;
622 ctx.to.shell = optarg;
625 printf("%d\n", VERSION_CODE);
628 printf("%s\n", VERSION);
631 /* Bionic getopt_long doesn't terminate its error output by newline */
632 fprintf(stderr, "\n");
636 if (optind < argc && !strcmp(argv[optind], "-")) {
640 /* username or uid */
641 if (optind < argc && strcmp(argv[optind], "--")) {
643 pw = getpwnam(argv[optind]);
647 /* It seems we shouldn't do this at all */
649 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
650 if (errno || *endptr) {
651 LOGE("Unknown id: %s\n", argv[optind]);
652 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
656 ctx.to.uid = pw->pw_uid;
660 if (optind < argc && !strcmp(argv[optind], "--")) {
663 ctx.to.optind = optind;
666 if (from_init(&ctx.from) < 0) {
673 if (ctx.user.owner_mode == -1 && ctx.user.userid != 0)
676 if (access_disabled(&ctx.from))
679 ctx.umask = umask(027);
681 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL)
684 if (stat(ctx.user.data_path, &st) < 0) {
689 if (st.st_gid != st.st_uid)
691 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
692 (int)st.st_uid, (int)st.st_gid);
696 mkdir(REQUESTOR_CACHE_PATH, 0770);
697 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
698 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
702 if (setgroups(0, NULL)) {
706 if (setegid(st.st_gid)) {
707 PLOGE("setegid (%lu)", st.st_gid);
710 if (seteuid(st.st_uid)) {
711 PLOGE("seteuid (%lu)", st.st_uid);
715 dballow = database_check(&ctx);
717 case INTERACTIVE: break;
718 case ALLOW: allow(&ctx); /* never returns */
720 default: deny(&ctx); /* never returns too */
723 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
725 if (socket_serv_fd < 0) {
729 signal(SIGHUP, cleanup_signal);
730 signal(SIGPIPE, cleanup_signal);
731 signal(SIGTERM, cleanup_signal);
732 signal(SIGQUIT, cleanup_signal);
733 signal(SIGINT, cleanup_signal);
734 signal(SIGABRT, cleanup_signal);
736 if (send_intent(&ctx, INTERACTIVE, ACTION_REQUEST) < 0) {
742 fd = socket_accept(socket_serv_fd);
746 if (socket_send_request(fd, &ctx)) {
749 if (socket_receive_result(fd, buf, sizeof(buf))) {
754 close(socket_serv_fd);
755 socket_cleanup(&ctx);
759 #define SOCKET_RESPONSE "socket:"
760 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
761 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
763 result += sizeof(SOCKET_RESPONSE) - 1;
765 if (!strcmp(result, "DENY")) {
767 } else if (!strcmp(result, "ALLOW")) {
770 LOGE("unknown response from Superuser Requestor: %s", result);