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>
40 struct passwd* ppwd = getpwnam("shell");
48 void exec_log(char *priority, char* logline) {
50 if ((pid = fork()) == 0) {
51 int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
53 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
56 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline);
61 void exec_loge(const char* fmt, ...) {
64 char logline[PATH_MAX];
66 vsnprintf(logline, PATH_MAX, fmt, args);
68 exec_log("e", logline);
71 void exec_logw(const char* fmt, ...) {
74 char logline[PATH_MAX];
76 vsnprintf(logline, PATH_MAX, fmt, args);
78 exec_log("w", logline);
81 void exec_logd(const char* fmt, ...) {
84 char logline[PATH_MAX];
86 vsnprintf(logline, PATH_MAX, fmt, args);
88 exec_log("d", logline);
91 static int from_init(struct su_initiator *from) {
92 char path[PATH_MAX], exe[PATH_MAX];
93 char args[4096], *argv0, *argv_rest;
100 from->pid = getppid();
102 /* Get the command line */
103 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
104 fd = open(path, O_RDONLY);
106 PLOGE("Opening command line");
109 len = read(fd, args, sizeof(args));
112 if (len < 0 || len == sizeof(args)) {
113 PLOGEV("Reading command line", err);
119 for (i = 0; i < len; i++) {
120 if (args[i] == '\0') {
122 argv_rest = &args[i+1];
131 strncpy(from->args, argv_rest, sizeof(from->args));
132 from->args[sizeof(from->args)-1] = '\0';
134 from->args[0] = '\0';
137 /* If this isn't app_process, use the real path instead of argv[0] */
138 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
139 len = readlink(path, exe, sizeof(exe));
141 PLOGE("Getting exe path");
145 if (strcmp(exe, "/system/bin/app_process")) {
149 strncpy(from->bin, argv0, sizeof(from->bin));
150 from->bin[sizeof(from->bin)-1] = '\0';
153 pw = getpwuid(from->uid);
154 if (pw && pw->pw_name) {
155 strncpy(from->name, pw->pw_name, sizeof(from->name));
161 static int get_multiuser_mode() {
163 char sdk_ver[PROPERTY_VALUE_MAX];
165 data = read_file("/system/build.prop");
166 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
169 int sdk = atoi(sdk_ver);
171 return MULTIUSER_MODE_NONE;
173 int ret = MULTIUSER_MODE_OWNER_ONLY;
176 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
177 int last = strlen(mode) - 1;
178 if (mode[last] == '\n')
180 fgets(mode, sizeof(mode), fp);
181 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
182 ret = MULTIUSER_MODE_USER;
183 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
184 ret = MULTIUSER_MODE_OWNER_MANAGED;
187 ret = MULTIUSER_MODE_OWNER_ONLY;
194 static void read_options(struct su_context *ctx) {
195 ctx->user.multiuser_mode = get_multiuser_mode();
198 static void user_init(struct su_context *ctx) {
199 if (ctx->from.uid > 99999) {
200 ctx->user.android_user_id = ctx->from.uid / 100000;
201 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
202 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
203 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
208 static void populate_environment(const struct su_context *ctx) {
214 pw = getpwuid(ctx->to.uid);
216 setenv("HOME", pw->pw_dir, 1);
217 setenv("SHELL", ctx->to.shell, 1);
218 if (ctx->to.login || ctx->to.uid) {
219 setenv("USER", pw->pw_name, 1);
220 setenv("LOGNAME", pw->pw_name, 1);
225 void set_identity(unsigned int uid) {
227 * Set effective uid back to root, otherwise setres[ug]id will fail
231 PLOGE("seteuid (root)");
234 if (setresgid(uid, uid, uid)) {
235 PLOGE("setresgid (%u)", uid);
238 if (setresuid(uid, uid, uid)) {
239 PLOGE("setresuid (%u)", uid);
244 static void socket_cleanup(struct su_context *ctx) {
245 if (ctx && ctx->sock_path[0]) {
246 if (unlink(ctx->sock_path))
247 PLOGE("unlink (%s)", ctx->sock_path);
248 ctx->sock_path[0] = 0;
253 * For use in signal handlers/atexit-function
254 * NOTE: su_ctx points to main's local variable.
255 * It's OK due to the program uses exit(3), not return from main()
257 static struct su_context *su_ctx = NULL;
259 static void cleanup(void) {
260 socket_cleanup(su_ctx);
263 static void cleanup_signal(int sig) {
264 socket_cleanup(su_ctx);
268 void sigchld_handler(int sig) {
269 child_cleanup(su_ctx);
273 static int socket_create_temp(char *path, size_t len) {
275 struct sockaddr_un sun;
277 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
282 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
283 PLOGE("fcntl FD_CLOEXEC");
287 memset(&sun, 0, sizeof(sun));
288 sun.sun_family = AF_LOCAL;
289 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
290 memset(sun.sun_path, 0, sizeof(sun.sun_path));
291 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
294 * Delete the socket to protect from situations when
295 * something bad occured previously and the kernel reused pid from that process.
296 * Small probability, isn't it.
298 unlink(sun.sun_path);
300 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
305 if (listen(fd, 1) < 0) {
316 static int socket_accept(int serv_fd) {
321 /* Wait 20 seconds for a connection, then give up. */
325 FD_SET(serv_fd, &fds);
327 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
328 } while (rc < 0 && errno == EINTR);
334 fd = accept(serv_fd, NULL, NULL);
343 static int socket_send_request(int fd, const struct su_context *ctx) {
344 #define write_data(fd, data, data_len) \
346 size_t __len = htonl(data_len); \
347 __len = write((fd), &__len, sizeof(__len)); \
348 if (__len != sizeof(__len)) { \
349 PLOGE("write(" #data ")"); \
352 __len = write((fd), data, data_len); \
353 if (__len != data_len) { \
354 PLOGE("write(" #data ")"); \
359 #define write_string(fd, name, data) \
361 write_data(fd, name, strlen(name)); \
362 write_data(fd, data, strlen(data)); \
365 // stringify everything.
366 #define write_token(fd, name, data) \
369 snprintf(buf, sizeof(buf), "%d", data); \
370 write_string(fd, name, buf); \
373 write_token(fd, "version", PROTO_VERSION);
374 write_token(fd, "pid", ctx->from.pid);
375 write_token(fd, "from.name", ctx->from.name);
376 write_token(fd, "to.name", ctx->to.name);
377 write_token(fd, "from.uid", ctx->from.uid);
378 write_token(fd, "to.uid", ctx->to.uid);
379 write_string(fd, "from.bin", ctx->from.bin);
380 write_string(fd, "command", get_command(&ctx->to));
381 write_token(fd, "eof", PROTO_VERSION);
385 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
388 LOGD("waiting for user");
389 len = read(fd, result, result_len-1);
391 PLOGE("read(result)");
399 static void usage(int status) {
400 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
403 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
405 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
406 " -h, --help display this help message and exit\n"
407 " -, -l, --login pretend the shell to be a login shell\n"
409 " --preserve-environment do not change environment variables\n"
410 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
411 " -u display the multiuser mode and exit\n"
412 " -v, --version display version number and exit\n"
413 " -V display version code and exit,\n"
414 " this is used almost exclusively by Superuser.apk\n");
418 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
419 char *cmd = get_command(&ctx->to);
421 // No send to UI denied requests for shell and root users (they are in the log)
422 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
423 send_result(ctx, DENY);
425 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
426 fprintf(stderr, "%s\n", strerror(EACCES));
430 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
435 // No send to UI accepted requests for shell and root users (they are in the log)
436 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
437 send_result(ctx, ALLOW);
440 arg0 = strrchr (ctx->to.shell, '/');
441 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
443 int s = strlen(arg0) + 2;
454 populate_environment(ctx);
455 set_identity(ctx->to.uid);
458 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
459 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
461 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
462 ctx->from.uid, ctx->from.bin,
463 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
464 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
465 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
467 argc = ctx->to.optind;
468 if (ctx->to.command) {
469 ctx->to.argv[--argc] = ctx->to.command;
470 ctx->to.argv[--argc] = "-c";
472 ctx->to.argv[--argc] = arg0;
473 execv(ctx->to.shell, ctx->to.argv + argc);
476 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
481 * CyanogenMod-specific behavior
483 * we can't simply use the property service, since we aren't launched from init
484 * and can't trust the location of the property workspace.
485 * Find the properties ourselves.
487 int access_disabled(const struct su_initiator *from) {
489 char build_type[PROPERTY_VALUE_MAX];
490 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
493 data = read_file("/system/build.prop");
494 if (check_property(data, "ro.cm.version")) {
495 get_property(data, build_type, "ro.build.type", "");
498 data = read_file("/default.prop");
499 get_property(data, debuggable, "ro.debuggable", "0");
501 /* only allow su on debuggable builds */
502 if (strcmp("1", debuggable) != 0) {
503 LOGE("Root access is disabled on non-debug builds");
507 data = read_file("/data/property/persist.sys.root_access");
510 if (len >= PROPERTY_VALUE_MAX)
511 memcpy(enabled, "1", 2);
513 memcpy(enabled, data, len + 1);
516 memcpy(enabled, "1", 2);
518 /* enforce persist.sys.root_access on non-eng builds for apps */
519 if (strcmp("eng", build_type) != 0 &&
520 from->uid != AID_SHELL && from->uid != AID_ROOT &&
521 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
522 LOGE("Apps root access is disabled by system setting - "
523 "enable it under settings -> developer options");
527 /* disallow su in a shell if appropriate */
528 if (from->uid == AID_SHELL &&
529 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
530 LOGE("Shell root access is disabled by a system setting - "
531 "enable it under settings -> developer options");
539 int main(int argc, char *argv[]) {
540 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
541 /* The same list than GLibc at this point */
542 static const char* const unsec_vars[] = {
566 "LD_AOUT_LIBRARY_PATH",
568 // not listed in linker, used due to system() call
571 const char* const* cp = unsec_vars;
572 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
579 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
580 * This occurs on Android 4.0+
582 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
586 struct su_context ctx = {
598 .shell = DEFAULT_SHELL,
606 .android_user_id = 0,
607 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
608 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
609 .base_path = REQUESTOR_DATA_PATH REQUESTOR
613 int c, socket_serv_fd, fd;
614 char buf[64], *result;
616 struct option long_opts[] = {
617 { "command", required_argument, NULL, 'c' },
618 { "help", no_argument, NULL, 'h' },
619 { "login", no_argument, NULL, 'l' },
620 { "preserve-environment", no_argument, NULL, 'p' },
621 { "shell", required_argument, NULL, 's' },
622 { "version", no_argument, NULL, 'v' },
623 { NULL, 0, NULL, 0 },
626 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
629 ctx.to.command = optarg;
642 ctx.to.shell = optarg;
645 printf("%d\n", VERSION_CODE);
648 printf("%s\n", VERSION);
651 switch (get_multiuser_mode()) {
652 case MULTIUSER_MODE_USER:
653 printf("%s\n", MULTIUSER_VALUE_USER);
655 case MULTIUSER_MODE_OWNER_MANAGED:
656 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
658 case MULTIUSER_MODE_OWNER_ONLY:
659 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
661 case MULTIUSER_MODE_NONE:
662 printf("%s\n", MULTIUSER_VALUE_NONE);
667 /* Bionic getopt_long doesn't terminate its error output by newline */
668 fprintf(stderr, "\n");
672 if (optind < argc && !strcmp(argv[optind], "-")) {
676 /* username or uid */
677 if (optind < argc && strcmp(argv[optind], "--")) {
679 pw = getpwnam(argv[optind]);
683 /* It seems we shouldn't do this at all */
685 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
686 if (errno || *endptr) {
687 LOGE("Unknown id: %s\n", argv[optind]);
688 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
692 ctx.to.uid = pw->pw_uid;
694 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
698 if (optind < argc && !strcmp(argv[optind], "--")) {
701 ctx.to.optind = optind;
704 if (from_init(&ctx.from) < 0) {
711 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
715 if (access_disabled(&ctx.from)) {
716 LOGD("access_disabled");
720 ctx.umask = umask(027);
722 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL) {
723 LOGD("Allowing root/shell.");
727 if (stat(ctx.user.base_path, &st) < 0) {
728 PLOGE("stat %s", ctx.user.base_path);
732 if (st.st_gid != st.st_uid) {
733 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
734 (int)st.st_uid, (int)st.st_gid);
738 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
739 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
740 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
744 if (setgroups(0, NULL)) {
748 if (setegid(st.st_gid)) {
749 PLOGE("setegid (%lu)", st.st_gid);
752 if (seteuid(st.st_uid)) {
753 PLOGE("seteuid (%lu)", st.st_uid);
757 dballow = database_check(&ctx);
763 allow(&ctx); /* never returns */
767 deny(&ctx); /* never returns too */
770 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
772 if (socket_serv_fd < 0) {
776 signal(SIGHUP, cleanup_signal);
777 signal(SIGPIPE, cleanup_signal);
778 signal(SIGTERM, cleanup_signal);
779 signal(SIGQUIT, cleanup_signal);
780 signal(SIGINT, cleanup_signal);
781 signal(SIGABRT, cleanup_signal);
783 if (send_request(&ctx) < 0) {
789 fd = socket_accept(socket_serv_fd);
793 if (socket_send_request(fd, &ctx)) {
796 if (socket_receive_result(fd, buf, sizeof(buf))) {
801 close(socket_serv_fd);
802 socket_cleanup(&ctx);
806 #define SOCKET_RESPONSE "socket:"
807 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
808 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
810 result += sizeof(SOCKET_RESPONSE) - 1;
812 if (!strcmp(result, "DENY")) {
814 } else if (!strcmp(result, "ALLOW")) {
817 LOGE("unknown response from Superuser Requestor: %s", result);