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 int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
54 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
57 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline);
62 void exec_loge(const char* fmt, ...) {
65 char logline[PATH_MAX];
67 vsnprintf(logline, PATH_MAX, fmt, args);
69 exec_log("e", logline);
72 void exec_logw(const char* fmt, ...) {
75 char logline[PATH_MAX];
77 vsnprintf(logline, PATH_MAX, fmt, args);
79 exec_log("w", logline);
82 void exec_logd(const char* fmt, ...) {
85 char logline[PATH_MAX];
87 vsnprintf(logline, PATH_MAX, fmt, args);
89 exec_log("d", logline);
92 static int from_init(struct su_initiator *from) {
93 char path[PATH_MAX], exe[PATH_MAX];
94 char args[4096], *argv0, *argv_rest;
100 from->uid = getuid();
101 from->pid = getppid();
103 /* Get the command line */
104 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
105 fd = open(path, O_RDONLY);
107 PLOGE("Opening command line");
110 len = read(fd, args, sizeof(args));
113 if (len < 0 || len == sizeof(args)) {
114 PLOGEV("Reading command line", err);
120 for (i = 0; i < len; i++) {
121 if (args[i] == '\0') {
123 argv_rest = &args[i+1];
132 strncpy(from->args, argv_rest, sizeof(from->args));
133 from->args[sizeof(from->args)-1] = '\0';
135 from->args[0] = '\0';
138 /* If this isn't app_process, use the real path instead of argv[0] */
139 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
140 len = readlink(path, exe, sizeof(exe));
142 PLOGE("Getting exe path");
146 if (strcmp(exe, "/system/bin/app_process")) {
150 strncpy(from->bin, argv0, sizeof(from->bin));
151 from->bin[sizeof(from->bin)-1] = '\0';
156 static void read_options(struct su_context *ctx) {
159 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
160 fgets(mode, sizeof(mode), fp);
161 LOGD("multiuser mode: %s", mode);
162 if (strcmp(mode, "user\n") == 0) {
163 ctx->user.multiuser_mode = MULTIUSER_MODE_USER;
164 } else if (strcmp(mode, "owner\n") == 0) {
165 ctx->user.multiuser_mode = MULTIUSER_MODE_OWNER;
171 static void user_init(struct su_context *ctx) {
172 if (ctx->from.uid > 99999) {
173 ctx->user.android_user_id = ctx->from.uid / 100000;
174 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
175 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
180 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) {
199 * Set effective uid back to root, otherwise setres[ug]id will fail
203 PLOGE("seteuid (root)");
206 if (setresgid(uid, uid, uid)) {
207 PLOGE("setresgid (%u)", uid);
210 if (setresuid(uid, uid, uid)) {
211 PLOGE("setresuid (%u)", uid);
216 static void socket_cleanup(struct su_context *ctx) {
217 if (ctx && ctx->sock_path[0]) {
218 if (unlink(ctx->sock_path))
219 PLOGE("unlink (%s)", ctx->sock_path);
220 ctx->sock_path[0] = 0;
225 * For use in signal handlers/atexit-function
226 * NOTE: su_ctx points to main's local variable.
227 * It's OK due to the program uses exit(3), not return from main()
229 static struct su_context *su_ctx = NULL;
231 static void cleanup(void) {
232 socket_cleanup(su_ctx);
235 static void cleanup_signal(int sig) {
236 socket_cleanup(su_ctx);
240 void sigchld_handler(int sig) {
241 child_cleanup(su_ctx);
245 static int socket_create_temp(char *path, size_t len) {
247 struct sockaddr_un sun;
249 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
254 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
255 PLOGE("fcntl FD_CLOEXEC");
259 memset(&sun, 0, sizeof(sun));
260 sun.sun_family = AF_LOCAL;
261 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
262 memset(sun.sun_path, 0, sizeof(sun.sun_path));
263 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
266 * Delete the socket to protect from situations when
267 * something bad occured previously and the kernel reused pid from that process.
268 * Small probability, isn't it.
270 unlink(sun.sun_path);
272 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
277 if (listen(fd, 1) < 0) {
288 static int socket_accept(int serv_fd) {
293 /* Wait 20 seconds for a connection, then give up. */
297 FD_SET(serv_fd, &fds);
300 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
301 } while (rc < 0 && errno == EINTR);
307 fd = accept(serv_fd, NULL, NULL);
316 static int socket_send_request(int fd, const struct su_context *ctx) {
318 size_t bin_size, cmd_size;
321 #define write_token(fd, data) \
323 uint32_t __data = htonl(data); \
324 size_t __count = sizeof(__data); \
325 size_t __len = write((fd), &__data, __count); \
326 if (__len != __count) { \
327 PLOGE("write(" #data ")"); \
332 write_token(fd, PROTO_VERSION);
333 write_token(fd, PATH_MAX);
334 write_token(fd, ARG_MAX);
335 write_token(fd, ctx->from.uid);
336 write_token(fd, ctx->to.uid);
337 bin_size = strlen(ctx->from.bin) + 1;
338 write_token(fd, bin_size);
339 len = write(fd, ctx->from.bin, bin_size);
340 if (len != bin_size) {
344 cmd = get_command(&ctx->to);
345 cmd_size = strlen(cmd) + 1;
346 write_token(fd, cmd_size);
347 len = write(fd, cmd, cmd_size);
348 if (len != cmd_size) {
355 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
358 LOGD("waiting for result");
359 len = read(fd, result, result_len-1);
361 PLOGE("read(result)");
369 static void usage(int status) {
370 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
373 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
375 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
376 " -h, --help display this help message and exit\n"
377 " -, -l, --login pretend the shell to be a login shell\n"
379 " --preserve-environment do not change environment variables\n"
380 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
381 " -v, --version display version number and exit\n"
382 " -V display version code and exit,\n"
383 " this is used almost exclusively by Superuser.apk\n");
387 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
388 char *cmd = get_command(&ctx->to);
390 // No send to UI denied requests for shell and root users (they are in the log)
391 if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
392 send_result(ctx, DENY);
394 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
395 fprintf(stderr, "%s\n", strerror(EACCES));
399 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
404 // No send to UI accepted requests for shell and root users (they are in the log)
405 if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
406 send_result(ctx, ALLOW);
409 arg0 = strrchr (ctx->to.shell, '/');
410 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
412 int s = strlen(arg0) + 2;
423 populate_environment(ctx);
424 set_identity(ctx->to.uid);
427 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
428 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
430 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
431 ctx->from.uid, ctx->from.bin,
432 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
433 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
434 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
436 argc = ctx->to.optind;
437 if (ctx->to.command) {
438 ctx->to.argv[--argc] = ctx->to.command;
439 ctx->to.argv[--argc] = "-c";
441 ctx->to.argv[--argc] = arg0;
442 execv(ctx->to.shell, ctx->to.argv + argc);
445 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
450 * CyanogenMod-specific behavior
452 * we can't simply use the property service, since we aren't launched from init
453 * and can't trust the location of the property workspace.
454 * Find the properties ourselves.
456 int access_disabled(const struct su_initiator *from) {
458 char build_type[PROPERTY_VALUE_MAX];
459 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
462 data = read_file("/system/build.prop");
463 if (check_property(data, "ro.cm.version")) {
464 get_property(data, build_type, "ro.build.type", "");
467 data = read_file("/default.prop");
468 get_property(data, debuggable, "ro.debuggable", "0");
470 /* only allow su on debuggable builds */
471 if (strcmp("1", debuggable) != 0) {
472 LOGE("Root access is disabled on non-debug builds");
476 data = read_file("/data/property/persist.sys.root_access");
479 if (len >= PROPERTY_VALUE_MAX)
480 memcpy(enabled, "1", 2);
482 memcpy(enabled, data, len + 1);
485 memcpy(enabled, "1", 2);
487 /* enforce persist.sys.root_access on non-eng builds for apps */
488 if (strcmp("eng", build_type) != 0 &&
489 from->uid != AID_SHELL && from->uid != AID_ROOT &&
490 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
491 LOGE("Apps root access is disabled by system setting - "
492 "enable it under settings -> developer options");
496 /* disallow su in a shell if appropriate */
497 if (from->uid == AID_SHELL &&
498 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
499 LOGE("Shell root access is disabled by a system setting - "
500 "enable it under settings -> developer options");
508 int main(int argc, char *argv[]) {
509 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
510 /* The same list than GLibc at this point */
511 static const char* const unsec_vars[] = {
535 "LD_AOUT_LIBRARY_PATH",
537 // not listed in linker, used due to system() call
540 const char* const* cp = unsec_vars;
541 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
548 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
549 * This occurs on Android 4.0+
551 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
555 struct su_context ctx = {
566 .shell = DEFAULT_SHELL,
573 .android_user_id = 0,
574 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
575 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
579 int c, socket_serv_fd, fd;
580 char buf[64], *result;
582 struct option long_opts[] = {
583 { "command", required_argument, NULL, 'c' },
584 { "help", no_argument, NULL, 'h' },
585 { "login", no_argument, NULL, 'l' },
586 { "preserve-environment", no_argument, NULL, 'p' },
587 { "shell", required_argument, NULL, 's' },
588 { "version", no_argument, NULL, 'v' },
589 { NULL, 0, NULL, 0 },
592 while ((c = getopt_long(argc, argv, "+c:hlmps:Vv", long_opts, NULL)) != -1) {
595 ctx.to.command = optarg;
608 ctx.to.shell = optarg;
611 printf("%d\n", VERSION_CODE);
614 printf("%s\n", VERSION);
617 /* Bionic getopt_long doesn't terminate its error output by newline */
618 fprintf(stderr, "\n");
622 if (optind < argc && !strcmp(argv[optind], "-")) {
626 /* username or uid */
627 if (optind < argc && strcmp(argv[optind], "--")) {
629 pw = getpwnam(argv[optind]);
633 /* It seems we shouldn't do this at all */
635 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
636 if (errno || *endptr) {
637 LOGE("Unknown id: %s\n", argv[optind]);
638 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
642 ctx.to.uid = pw->pw_uid;
646 if (optind < argc && !strcmp(argv[optind], "--")) {
649 ctx.to.optind = optind;
652 if (from_init(&ctx.from) < 0) {
659 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
660 LOGD("multiuser mode: owner only");
664 if (access_disabled(&ctx.from)) {
665 LOGD("access_disabled");
669 ctx.umask = umask(027);
671 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL)
674 if (stat(ctx.user.database_path, &st) < 0) {
675 PLOGE("stat %s", ctx.user.database_path);
679 if (st.st_gid != st.st_uid)
681 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
682 (int)st.st_uid, (int)st.st_gid);
686 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
687 LOGD("mkdir: %d", ret);
688 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
689 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
693 if (setgroups(0, NULL)) {
697 if (setegid(st.st_gid)) {
698 PLOGE("setegid (%lu)", st.st_gid);
701 if (seteuid(st.st_uid)) {
702 PLOGE("seteuid (%lu)", st.st_uid);
706 dballow = database_check(&ctx);
712 allow(&ctx); /* never returns */
716 deny(&ctx); /* never returns too */
719 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
721 if (socket_serv_fd < 0) {
725 signal(SIGHUP, cleanup_signal);
726 signal(SIGPIPE, cleanup_signal);
727 signal(SIGTERM, cleanup_signal);
728 signal(SIGQUIT, cleanup_signal);
729 signal(SIGINT, cleanup_signal);
730 signal(SIGABRT, cleanup_signal);
732 if (send_request(&ctx) < 0) {
738 fd = socket_accept(socket_serv_fd);
742 if (socket_send_request(fd, &ctx)) {
745 if (socket_receive_result(fd, buf, sizeof(buf))) {
750 close(socket_serv_fd);
751 socket_cleanup(&ctx);
755 #define SOCKET_RESPONSE "socket:"
756 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
757 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
759 result += sizeof(SOCKET_RESPONSE) - 1;
761 if (!strcmp(result, "DENY")) {
763 } else if (!strcmp(result, "ALLOW")) {
766 LOGE("unknown response from Superuser Requestor: %s", result);