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 extern int daemon_from_uid;
41 extern int daemon_from_pid;
43 unsigned get_shell_uid() {
44 struct passwd* ppwd = getpwnam("shell");
52 unsigned get_system_uid() {
53 struct passwd* ppwd = getpwnam("system");
61 unsigned get_radio_uid() {
62 struct passwd* ppwd = getpwnam("radio");
70 void exec_log(char *priority, char* logline) {
72 if ((pid = fork()) == 0) {
73 int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
74 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
78 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline, NULL);
83 void exec_loge(const char* fmt, ...) {
86 char logline[PATH_MAX];
88 vsnprintf(logline, PATH_MAX, fmt, args);
90 exec_log("e", logline);
93 void exec_logw(const char* fmt, ...) {
96 char logline[PATH_MAX];
98 vsnprintf(logline, PATH_MAX, fmt, args);
100 exec_log("w", logline);
103 void exec_logd(const char* fmt, ...) {
106 char logline[PATH_MAX];
108 vsnprintf(logline, PATH_MAX, fmt, args);
110 exec_log("d", logline);
113 static int from_init(struct su_initiator *from) {
114 char path[PATH_MAX], exe[PATH_MAX];
115 char args[4096], *argv0, *argv_rest;
121 from->uid = getuid();
122 from->pid = getppid();
124 /* Get the command line */
125 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
126 fd = open(path, O_RDONLY);
128 PLOGE("Opening command line");
131 len = read(fd, args, sizeof(args));
134 if (len < 0 || len == sizeof(args)) {
135 PLOGEV("Reading command line", err);
141 for (i = 0; i < len; i++) {
142 if (args[i] == '\0') {
144 argv_rest = &args[i+1];
153 strncpy(from->args, argv_rest, sizeof(from->args));
154 from->args[sizeof(from->args)-1] = '\0';
156 from->args[0] = '\0';
159 /* If this isn't app_process, use the real path instead of argv[0] */
160 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
161 len = readlink(path, exe, sizeof(exe));
163 PLOGE("Getting exe path");
167 if (strcmp(exe, "/system/bin/app_process")) {
171 strncpy(from->bin, argv0, sizeof(from->bin));
172 from->bin[sizeof(from->bin)-1] = '\0';
175 pw = getpwuid(from->uid);
176 if (pw && pw->pw_name) {
177 strncpy(from->name, pw->pw_name, sizeof(from->name));
181 from->uid = daemon_from_uid;
182 from->pid = daemon_from_pid;
188 static int get_multiuser_mode() {
190 char sdk_ver[PROPERTY_VALUE_MAX];
192 data = read_file("/system/build.prop");
193 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
196 int sdk = atoi(sdk_ver);
198 return MULTIUSER_MODE_NONE;
200 int ret = MULTIUSER_MODE_OWNER_ONLY;
203 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
204 fgets(mode, sizeof(mode), fp);
205 int last = strlen(mode) - 1;
206 if (mode[last] == '\n')
208 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
209 ret = MULTIUSER_MODE_USER;
210 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
211 ret = MULTIUSER_MODE_OWNER_MANAGED;
214 ret = MULTIUSER_MODE_OWNER_ONLY;
221 static void read_options(struct su_context *ctx) {
222 ctx->user.multiuser_mode = get_multiuser_mode();
225 static void user_init(struct su_context *ctx) {
226 if (ctx->from.uid > 99999) {
227 ctx->user.android_user_id = ctx->from.uid / 100000;
228 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
229 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
230 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
235 static void populate_environment(const struct su_context *ctx) {
241 pw = getpwuid(ctx->to.uid);
243 setenv("HOME", pw->pw_dir, 1);
245 setenv("SHELL", ctx->to.shell, 1);
247 setenv("SHELL", DEFAULT_SHELL, 1);
248 if (ctx->to.login || ctx->to.uid) {
249 setenv("USER", pw->pw_name, 1);
250 setenv("LOGNAME", pw->pw_name, 1);
255 void set_identity(unsigned int uid) {
257 * Set effective uid back to root, otherwise setres[ug]id will fail
261 PLOGE("seteuid (root)");
264 if (setresgid(uid, uid, uid)) {
265 PLOGE("setresgid (%u)", uid);
268 if (setresuid(uid, uid, uid)) {
269 PLOGE("setresuid (%u)", uid);
274 static void socket_cleanup(struct su_context *ctx) {
275 if (ctx && ctx->sock_path[0]) {
276 if (unlink(ctx->sock_path))
277 PLOGE("unlink (%s)", ctx->sock_path);
278 ctx->sock_path[0] = 0;
283 * For use in signal handlers/atexit-function
284 * NOTE: su_ctx points to main's local variable.
285 * It's OK due to the program uses exit(3), not return from main()
287 static struct su_context *su_ctx = NULL;
289 static void cleanup(void) {
290 socket_cleanup(su_ctx);
293 static void cleanup_signal(int sig) {
294 socket_cleanup(su_ctx);
298 static int socket_create_temp(char *path, size_t len) {
300 struct sockaddr_un sun;
302 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
307 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
308 PLOGE("fcntl FD_CLOEXEC");
312 memset(&sun, 0, sizeof(sun));
313 sun.sun_family = AF_LOCAL;
314 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
315 memset(sun.sun_path, 0, sizeof(sun.sun_path));
316 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
319 * Delete the socket to protect from situations when
320 * something bad occured previously and the kernel reused pid from that process.
321 * Small probability, isn't it.
323 unlink(sun.sun_path);
325 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
330 if (listen(fd, 1) < 0) {
341 static int socket_accept(int serv_fd) {
346 /* Wait 20 seconds for a connection, then give up. */
350 FD_SET(serv_fd, &fds);
352 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
353 } while (rc < 0 && errno == EINTR);
359 fd = accept(serv_fd, NULL, NULL);
368 static int socket_send_request(int fd, const struct su_context *ctx) {
369 #define write_data(fd, data, data_len) \
371 size_t __len = htonl(data_len); \
372 __len = write((fd), &__len, sizeof(__len)); \
373 if (__len != sizeof(__len)) { \
374 PLOGE("write(" #data ")"); \
377 __len = write((fd), data, data_len); \
378 if (__len != data_len) { \
379 PLOGE("write(" #data ")"); \
384 #define write_string_data(fd, name, data) \
386 write_data(fd, name, strlen(name)); \
387 write_data(fd, data, strlen(data)); \
390 // stringify everything.
391 #define write_token(fd, name, data) \
394 snprintf(buf, sizeof(buf), "%d", data); \
395 write_string_data(fd, name, buf); \
398 write_token(fd, "version", PROTO_VERSION);
399 write_token(fd, "binary.version", VERSION_CODE);
400 write_token(fd, "pid", ctx->from.pid);
401 write_string_data(fd, "from.name", ctx->from.name);
402 write_string_data(fd, "to.name", ctx->to.name);
403 write_token(fd, "from.uid", ctx->from.uid);
404 write_token(fd, "to.uid", ctx->to.uid);
405 write_string_data(fd, "from.bin", ctx->from.bin);
406 // TODO: Fix issue where not using -c does not result a in a command
407 write_string_data(fd, "command", get_command(&ctx->to));
408 write_token(fd, "eof", PROTO_VERSION);
412 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
415 LOGD("waiting for user");
416 len = read(fd, result, result_len-1);
418 PLOGE("read(result)");
426 static void usage(int status) {
427 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
430 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
432 " --daemon start the su daemon agent\n"
433 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
434 " -h, --help display this help message and exit\n"
435 " -, -l, --login pretend the shell to be a login shell\n"
437 " --preserve-environment do not change environment variables\n"
438 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
439 " -u display the multiuser mode and exit\n"
440 " -v, --version display version number and exit\n"
441 " -V display version code and exit,\n"
442 " this is used almost exclusively by Superuser.apk\n");
446 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
447 char *cmd = get_command(&ctx->to);
451 // no need to log if called by root
452 if (ctx->from.uid == AID_ROOT)
455 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
456 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
460 send_result(ctx, DENY);
462 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
463 fprintf(stderr, "%s\n", strerror(EACCES));
467 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
474 // no need to log if called by root
475 if (ctx->from.uid == AID_ROOT)
478 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
479 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
483 send_result(ctx, ALLOW);
486 argc = ctx->to.optind;
487 if (ctx->to.command) {
488 binary = ctx->to.shell;
489 ctx->to.argv[--argc] = ctx->to.command;
490 ctx->to.argv[--argc] = "-c";
492 else if (ctx->to.shell) {
493 binary = ctx->to.shell;
496 if (ctx->to.argv[argc]) {
497 binary = ctx->to.argv[argc++];
500 binary = DEFAULT_SHELL;
504 arg0 = strrchr (binary, '/');
505 arg0 = (arg0) ? arg0 + 1 : binary;
507 int s = strlen(arg0) + 2;
518 populate_environment(ctx);
519 set_identity(ctx->to.uid);
522 (argc + (arg) < ctx->to.argc) ? " " : "", \
523 (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
525 LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
526 ctx->from.uid, ctx->from.bin,
527 ctx->to.uid, get_command(&ctx->to), binary,
528 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
529 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
531 ctx->to.argv[--argc] = arg0;
532 execvp(binary, ctx->to.argv + argc);
535 fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
540 * CyanogenMod-specific behavior
542 * we can't simply use the property service, since we aren't launched from init
543 * and can't trust the location of the property workspace.
544 * Find the properties ourselves.
546 int access_disabled(const struct su_initiator *from) {
548 char build_type[PROPERTY_VALUE_MAX];
549 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
552 data = read_file("/system/build.prop");
553 if (check_property(data, "ro.cm.version")) {
554 get_property(data, build_type, "ro.build.type", "");
557 data = read_file("/default.prop");
558 get_property(data, debuggable, "ro.debuggable", "0");
560 /* only allow su on debuggable builds */
561 if (strcmp("1", debuggable) != 0) {
562 LOGE("Root access is disabled on non-debug builds");
566 data = read_file("/data/property/persist.sys.root_access");
569 if (len >= PROPERTY_VALUE_MAX)
570 memcpy(enabled, "1", 2);
572 memcpy(enabled, data, len + 1);
575 memcpy(enabled, "1", 2);
577 /* enforce persist.sys.root_access on non-eng builds for apps */
578 if (strcmp("eng", build_type) != 0 &&
579 from->uid != AID_SHELL && from->uid != AID_ROOT &&
580 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
581 LOGE("Apps root access is disabled by system setting - "
582 "enable it under settings -> developer options");
586 /* disallow su in a shell if appropriate */
587 if (from->uid == AID_SHELL &&
588 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
589 LOGE("Shell root access is disabled by a system setting - "
590 "enable it under settings -> developer options");
598 int main(int argc, char *argv[]) {
599 // start up in daemon mode if prompted
600 if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
604 if (geteuid() != AID_ROOT && getuid() != AID_ROOT) {
605 // attempt to connect to daemon...
606 LOGD("starting daemon client %d %d", getuid(), geteuid());
607 return connect_daemon(argc, argv);
610 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
611 /* The same list than GLibc at this point */
612 static const char* const unsec_vars[] = {
636 "LD_AOUT_LIBRARY_PATH",
638 // not listed in linker, used due to system() call
641 const char* const* cp = unsec_vars;
642 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
649 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
650 * This occurs on Android 4.0+
652 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
656 struct su_context ctx = {
676 .android_user_id = 0,
677 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
678 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
679 .base_path = REQUESTOR_DATA_PATH REQUESTOR
683 int c, socket_serv_fd, fd;
684 char buf[64], *result;
686 struct option long_opts[] = {
687 { "command", required_argument, NULL, 'c' },
688 { "help", no_argument, NULL, 'h' },
689 { "login", no_argument, NULL, 'l' },
690 { "preserve-environment", no_argument, NULL, 'p' },
691 { "shell", required_argument, NULL, 's' },
692 { "version", no_argument, NULL, 'v' },
693 { NULL, 0, NULL, 0 },
696 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
699 ctx.to.shell = DEFAULT_SHELL;
700 ctx.to.command = optarg;
713 ctx.to.shell = optarg;
716 printf("%d\n", VERSION_CODE);
719 printf("%s\n", VERSION);
722 switch (get_multiuser_mode()) {
723 case MULTIUSER_MODE_USER:
724 printf("%s\n", MULTIUSER_VALUE_USER);
726 case MULTIUSER_MODE_OWNER_MANAGED:
727 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
729 case MULTIUSER_MODE_OWNER_ONLY:
730 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
732 case MULTIUSER_MODE_NONE:
733 printf("%s\n", MULTIUSER_VALUE_NONE);
738 /* Bionic getopt_long doesn't terminate its error output by newline */
739 fprintf(stderr, "\n");
743 if (optind < argc && !strcmp(argv[optind], "-")) {
747 /* username or uid */
748 if (optind < argc && strcmp(argv[optind], "--")) {
750 pw = getpwnam(argv[optind]);
754 /* It seems we shouldn't do this at all */
756 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
757 if (errno || *endptr) {
758 LOGE("Unknown id: %s\n", argv[optind]);
759 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
763 ctx.to.uid = pw->pw_uid;
765 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
769 if (optind < argc && !strcmp(argv[optind], "--")) {
772 ctx.to.optind = optind;
775 if (from_init(&ctx.from) < 0) {
782 // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
783 if (ctx.from.uid == AID_ROOT) {
784 LOGD("Allowing root/system/radio.");
788 // verify superuser is installed
789 if (stat(ctx.user.base_path, &st) < 0) {
790 // send to market (disabled, because people are and think this is hijacking their su)
791 // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
792 // silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
793 PLOGE("stat %s", ctx.user.base_path);
797 // odd perms on superuser data dir
798 if (st.st_gid != st.st_uid) {
799 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
800 (int)st.st_uid, (int)st.st_gid);
804 // always allow if this is the superuser uid
805 // superuser needs to be able to reenable itself when disabled...
806 if (ctx.from.uid == st.st_uid) {
810 // check if superuser is disabled completely
811 if (access_disabled(&ctx.from)) {
812 LOGD("access_disabled");
816 // autogrant shell at this point
817 if (ctx.from.uid == AID_SHELL) {
818 LOGD("Allowing shell.");
822 // deny if this is a non owner request and owner mode only
823 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
827 ctx.umask = umask(027);
829 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
830 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
831 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
835 if (setgroups(0, NULL)) {
839 if (setegid(st.st_gid)) {
840 PLOGE("setegid (%lu)", st.st_gid);
843 if (seteuid(st.st_uid)) {
844 PLOGE("seteuid (%lu)", st.st_uid);
848 dballow = database_check(&ctx);
854 allow(&ctx); /* never returns */
858 deny(&ctx); /* never returns too */
861 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
863 if (socket_serv_fd < 0) {
867 signal(SIGHUP, cleanup_signal);
868 signal(SIGPIPE, cleanup_signal);
869 signal(SIGTERM, cleanup_signal);
870 signal(SIGQUIT, cleanup_signal);
871 signal(SIGINT, cleanup_signal);
872 signal(SIGABRT, cleanup_signal);
874 if (send_request(&ctx) < 0) {
880 fd = socket_accept(socket_serv_fd);
884 if (socket_send_request(fd, &ctx)) {
887 if (socket_receive_result(fd, buf, sizeof(buf))) {
892 close(socket_serv_fd);
893 socket_cleanup(&ctx);
897 #define SOCKET_RESPONSE "socket:"
898 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
899 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
901 result += sizeof(SOCKET_RESPONSE) - 1;
903 if (!strcmp(result, "DENY")) {
905 } else if (!strcmp(result, "ALLOW")) {
908 LOGE("unknown response from Superuser Requestor: %s", result);