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 int fork_zero_fucks() {
74 waitpid(pid, &status, 0);
84 void exec_log(char *priority, char* logline) {
86 if ((pid = fork()) == 0) {
87 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
88 dup2(null, STDIN_FILENO);
89 dup2(null, STDOUT_FILENO);
90 dup2(null, STDERR_FILENO);
91 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline, NULL);
95 waitpid(pid, &status, 0);
98 void exec_loge(const char* fmt, ...) {
101 char logline[PATH_MAX];
103 vsnprintf(logline, PATH_MAX, fmt, args);
105 exec_log("e", logline);
108 void exec_logw(const char* fmt, ...) {
111 char logline[PATH_MAX];
113 vsnprintf(logline, PATH_MAX, fmt, args);
115 exec_log("w", logline);
118 void exec_logd(const char* fmt, ...) {
121 char logline[PATH_MAX];
123 vsnprintf(logline, PATH_MAX, fmt, args);
125 exec_log("d", logline);
128 static int from_init(struct su_initiator *from) {
129 char path[PATH_MAX], exe[PATH_MAX];
130 char args[4096], *argv0, *argv_rest;
136 from->uid = getuid();
137 from->pid = getppid();
139 /* Get the command line */
140 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
141 fd = open(path, O_RDONLY);
143 PLOGE("Opening command line");
146 len = read(fd, args, sizeof(args));
149 if (len < 0 || len == sizeof(args)) {
150 PLOGEV("Reading command line", err);
156 for (i = 0; i < len; i++) {
157 if (args[i] == '\0') {
159 argv_rest = &args[i+1];
168 strncpy(from->args, argv_rest, sizeof(from->args));
169 from->args[sizeof(from->args)-1] = '\0';
171 from->args[0] = '\0';
174 /* If this isn't app_process, use the real path instead of argv[0] */
175 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
176 len = readlink(path, exe, sizeof(exe));
178 PLOGE("Getting exe path");
182 if (strcmp(exe, "/system/bin/app_process")) {
186 strncpy(from->bin, argv0, sizeof(from->bin));
187 from->bin[sizeof(from->bin)-1] = '\0';
190 pw = getpwuid(from->uid);
191 if (pw && pw->pw_name) {
192 strncpy(from->name, pw->pw_name, sizeof(from->name));
196 from->uid = daemon_from_uid;
197 from->pid = daemon_from_pid;
203 static int get_multiuser_mode() {
205 char sdk_ver[PROPERTY_VALUE_MAX];
207 data = read_file("/system/build.prop");
208 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
211 int sdk = atoi(sdk_ver);
213 return MULTIUSER_MODE_NONE;
215 int ret = MULTIUSER_MODE_OWNER_ONLY;
218 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
219 fgets(mode, sizeof(mode), fp);
220 int last = strlen(mode) - 1;
221 if (mode[last] == '\n')
223 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
224 ret = MULTIUSER_MODE_USER;
225 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
226 ret = MULTIUSER_MODE_OWNER_MANAGED;
229 ret = MULTIUSER_MODE_OWNER_ONLY;
236 static void read_options(struct su_context *ctx) {
237 ctx->user.multiuser_mode = get_multiuser_mode();
240 static void user_init(struct su_context *ctx) {
241 if (ctx->from.uid > 99999) {
242 ctx->user.android_user_id = ctx->from.uid / 100000;
243 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
244 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
245 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
250 static void populate_environment(const struct su_context *ctx) {
256 pw = getpwuid(ctx->to.uid);
258 setenv("HOME", pw->pw_dir, 1);
260 setenv("SHELL", ctx->to.shell, 1);
262 setenv("SHELL", DEFAULT_SHELL, 1);
263 if (ctx->to.login || ctx->to.uid) {
264 setenv("USER", pw->pw_name, 1);
265 setenv("LOGNAME", pw->pw_name, 1);
270 void set_identity(unsigned int uid) {
272 * Set effective uid back to root, otherwise setres[ug]id will fail
276 PLOGE("seteuid (root)");
279 if (setresgid(uid, uid, uid)) {
280 PLOGE("setresgid (%u)", uid);
283 if (setresuid(uid, uid, uid)) {
284 PLOGE("setresuid (%u)", uid);
289 static void socket_cleanup(struct su_context *ctx) {
290 if (ctx && ctx->sock_path[0]) {
291 if (unlink(ctx->sock_path))
292 PLOGE("unlink (%s)", ctx->sock_path);
293 ctx->sock_path[0] = 0;
298 * For use in signal handlers/atexit-function
299 * NOTE: su_ctx points to main's local variable.
300 * It's OK due to the program uses exit(3), not return from main()
302 static struct su_context *su_ctx = NULL;
304 static void cleanup(void) {
305 socket_cleanup(su_ctx);
308 static void cleanup_signal(int sig) {
309 socket_cleanup(su_ctx);
313 static int socket_create_temp(char *path, size_t len) {
315 struct sockaddr_un sun;
317 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
322 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
323 PLOGE("fcntl FD_CLOEXEC");
327 memset(&sun, 0, sizeof(sun));
328 sun.sun_family = AF_LOCAL;
329 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
330 memset(sun.sun_path, 0, sizeof(sun.sun_path));
331 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
334 * Delete the socket to protect from situations when
335 * something bad occured previously and the kernel reused pid from that process.
336 * Small probability, isn't it.
338 unlink(sun.sun_path);
340 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
345 if (listen(fd, 1) < 0) {
356 static int socket_accept(int serv_fd) {
361 /* Wait 20 seconds for a connection, then give up. */
365 FD_SET(serv_fd, &fds);
367 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
368 } while (rc < 0 && errno == EINTR);
374 fd = accept(serv_fd, NULL, NULL);
383 static int socket_send_request(int fd, const struct su_context *ctx) {
384 #define write_data(fd, data, data_len) \
386 size_t __len = htonl(data_len); \
387 __len = write((fd), &__len, sizeof(__len)); \
388 if (__len != sizeof(__len)) { \
389 PLOGE("write(" #data ")"); \
392 __len = write((fd), data, data_len); \
393 if (__len != data_len) { \
394 PLOGE("write(" #data ")"); \
399 #define write_string_data(fd, name, data) \
401 write_data(fd, name, strlen(name)); \
402 write_data(fd, data, strlen(data)); \
405 // stringify everything.
406 #define write_token(fd, name, data) \
409 snprintf(buf, sizeof(buf), "%d", data); \
410 write_string_data(fd, name, buf); \
413 write_token(fd, "version", PROTO_VERSION);
414 write_token(fd, "binary.version", VERSION_CODE);
415 write_token(fd, "pid", ctx->from.pid);
416 write_string_data(fd, "from.name", ctx->from.name);
417 write_string_data(fd, "to.name", ctx->to.name);
418 write_token(fd, "from.uid", ctx->from.uid);
419 write_token(fd, "to.uid", ctx->to.uid);
420 write_string_data(fd, "from.bin", ctx->from.bin);
421 // TODO: Fix issue where not using -c does not result a in a command
422 write_string_data(fd, "command", get_command(&ctx->to));
423 write_token(fd, "eof", PROTO_VERSION);
427 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
430 LOGD("waiting for user");
431 len = read(fd, result, result_len-1);
433 PLOGE("read(result)");
441 static void usage(int status) {
442 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
445 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
447 " --daemon start the su daemon agent\n"
448 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
449 " -h, --help display this help message and exit\n"
450 " -, -l, --login pretend the shell to be a login shell\n"
452 " --preserve-environment do not change environment variables\n"
453 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
454 " -u display the multiuser mode and exit\n"
455 " -v, --version display version number and exit\n"
456 " -V display version code and exit,\n"
457 " this is used almost exclusively by Superuser.apk\n");
461 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
462 char *cmd = get_command(&ctx->to);
466 // no need to log if called by root
467 if (ctx->from.uid == AID_ROOT)
470 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
471 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
475 send_result(ctx, DENY);
477 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
478 fprintf(stderr, "%s\n", strerror(EACCES));
482 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
489 // no need to log if called by root
490 if (ctx->from.uid == AID_ROOT)
493 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
494 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
498 send_result(ctx, ALLOW);
501 argc = ctx->to.optind;
502 if (ctx->to.command) {
503 binary = ctx->to.shell;
504 ctx->to.argv[--argc] = ctx->to.command;
505 ctx->to.argv[--argc] = "-c";
507 else if (ctx->to.shell) {
508 binary = ctx->to.shell;
511 if (ctx->to.argv[argc]) {
512 binary = ctx->to.argv[argc++];
515 binary = DEFAULT_SHELL;
519 arg0 = strrchr (binary, '/');
520 arg0 = (arg0) ? arg0 + 1 : binary;
522 int s = strlen(arg0) + 2;
533 populate_environment(ctx);
534 set_identity(ctx->to.uid);
537 (argc + (arg) < ctx->to.argc) ? " " : "", \
538 (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
540 LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
541 ctx->from.uid, ctx->from.bin,
542 ctx->to.uid, get_command(&ctx->to), binary,
543 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
544 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
546 ctx->to.argv[--argc] = arg0;
547 execvp(binary, ctx->to.argv + argc);
550 fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
555 * CyanogenMod-specific behavior
557 * we can't simply use the property service, since we aren't launched from init
558 * and can't trust the location of the property workspace.
559 * Find the properties ourselves.
561 int access_disabled(const struct su_initiator *from) {
562 #ifndef SUPERUSER_EMBEDDED
566 char build_type[PROPERTY_VALUE_MAX];
567 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
570 data = read_file("/system/build.prop");
571 if (check_property(data, "ro.cm.version")) {
572 get_property(data, build_type, "ro.build.type", "");
575 data = read_file("/default.prop");
576 get_property(data, debuggable, "ro.debuggable", "0");
578 /* only allow su on debuggable builds */
579 if (strcmp("1", debuggable) != 0) {
580 LOGE("Root access is disabled on non-debug builds");
584 data = read_file("/data/property/persist.sys.root_access");
587 if (len >= PROPERTY_VALUE_MAX)
588 memcpy(enabled, "1", 2);
590 memcpy(enabled, data, len + 1);
593 memcpy(enabled, "1", 2);
595 /* enforce persist.sys.root_access on non-eng builds for apps */
596 if (strcmp("eng", build_type) != 0 &&
597 from->uid != AID_SHELL && from->uid != AID_ROOT &&
598 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
599 LOGE("Apps root access is disabled by system setting - "
600 "enable it under settings -> developer options");
604 /* disallow su in a shell if appropriate */
605 if (from->uid == AID_SHELL &&
606 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
607 LOGE("Shell root access is disabled by a system setting - "
608 "enable it under settings -> developer options");
617 static int is_api_18() {
618 char sdk_ver[PROPERTY_VALUE_MAX];
619 char *data = read_file("/system/build.prop");
620 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
621 int ver = atoi(sdk_ver);
626 int main(int argc, char *argv[]) {
627 // start up in daemon mode if prompted
628 if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
632 // attempt to use the daemon client if not root,
633 // or this is api 18 and adb shell (/data is not readable even as root)
635 if (geteuid() != AID_ROOT || getuid() != AID_ROOT) {
636 // attempt to connect to daemon...
637 LOGD("starting daemon client %d %d", getuid(), geteuid());
638 return connect_daemon(argc, argv);
642 LOGD("skipping daemon client %d %d", getuid(), geteuid());
644 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
645 /* The same list than GLibc at this point */
646 static const char* const unsec_vars[] = {
670 "LD_AOUT_LIBRARY_PATH",
672 // not listed in linker, used due to system() call
675 const char* const* cp = unsec_vars;
676 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
683 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
684 * This occurs on Android 4.0+
686 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
690 struct su_context ctx = {
710 .android_user_id = 0,
711 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
712 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
713 .base_path = REQUESTOR_DATA_PATH REQUESTOR
717 int c, socket_serv_fd, fd;
718 char buf[64], *result;
720 struct option long_opts[] = {
721 { "command", required_argument, NULL, 'c' },
722 { "help", no_argument, NULL, 'h' },
723 { "login", no_argument, NULL, 'l' },
724 { "preserve-environment", no_argument, NULL, 'p' },
725 { "shell", required_argument, NULL, 's' },
726 { "version", no_argument, NULL, 'v' },
727 { NULL, 0, NULL, 0 },
730 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
733 ctx.to.shell = DEFAULT_SHELL;
734 ctx.to.command = optarg;
747 ctx.to.shell = optarg;
750 printf("%d\n", VERSION_CODE);
753 printf("%s\n", VERSION);
756 switch (get_multiuser_mode()) {
757 case MULTIUSER_MODE_USER:
758 printf("%s\n", MULTIUSER_VALUE_USER);
760 case MULTIUSER_MODE_OWNER_MANAGED:
761 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
763 case MULTIUSER_MODE_OWNER_ONLY:
764 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
766 case MULTIUSER_MODE_NONE:
767 printf("%s\n", MULTIUSER_VALUE_NONE);
772 /* Bionic getopt_long doesn't terminate its error output by newline */
773 fprintf(stderr, "\n");
777 if (optind < argc && !strcmp(argv[optind], "-")) {
781 /* username or uid */
782 if (optind < argc && strcmp(argv[optind], "--")) {
784 pw = getpwnam(argv[optind]);
788 /* It seems we shouldn't do this at all */
790 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
791 if (errno || *endptr) {
792 LOGE("Unknown id: %s\n", argv[optind]);
793 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
797 ctx.to.uid = pw->pw_uid;
799 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
803 if (optind < argc && !strcmp(argv[optind], "--")) {
806 ctx.to.optind = optind;
809 if (from_init(&ctx.from) < 0) {
816 // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
817 if (ctx.from.uid == AID_ROOT) {
818 LOGD("Allowing root/system/radio.");
822 // verify superuser is installed
823 if (stat(ctx.user.base_path, &st) < 0) {
824 // send to market (disabled, because people are and think this is hijacking their su)
825 // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
826 // silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
827 PLOGE("stat %s", ctx.user.base_path);
831 // odd perms on superuser data dir
832 if (st.st_gid != st.st_uid) {
833 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
834 (int)st.st_uid, (int)st.st_gid);
838 // always allow if this is the superuser uid
839 // superuser needs to be able to reenable itself when disabled...
840 if (ctx.from.uid == st.st_uid) {
844 // check if superuser is disabled completely
845 if (access_disabled(&ctx.from)) {
846 LOGD("access_disabled");
850 // autogrant shell at this point
851 if (ctx.from.uid == AID_SHELL) {
852 LOGD("Allowing shell.");
856 // deny if this is a non owner request and owner mode only
857 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
861 ctx.umask = umask(027);
863 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
864 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
865 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
869 if (setgroups(0, NULL)) {
873 if (setegid(st.st_gid)) {
874 PLOGE("setegid (%lu)", st.st_gid);
877 if (seteuid(st.st_uid)) {
878 PLOGE("seteuid (%lu)", st.st_uid);
882 dballow = database_check(&ctx);
888 allow(&ctx); /* never returns */
892 deny(&ctx); /* never returns too */
895 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
897 if (socket_serv_fd < 0) {
901 signal(SIGHUP, cleanup_signal);
902 signal(SIGPIPE, cleanup_signal);
903 signal(SIGTERM, cleanup_signal);
904 signal(SIGQUIT, cleanup_signal);
905 signal(SIGINT, cleanup_signal);
906 signal(SIGABRT, cleanup_signal);
908 if (send_request(&ctx) < 0) {
914 fd = socket_accept(socket_serv_fd);
918 if (socket_send_request(fd, &ctx)) {
921 if (socket_receive_result(fd, buf, sizeof(buf))) {
926 close(socket_serv_fd);
927 socket_cleanup(&ctx);
931 #define SOCKET_RESPONSE "socket:"
932 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
933 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
935 result += sizeof(SOCKET_RESPONSE) - 1;
937 if (!strcmp(result, "DENY")) {
939 } else if (!strcmp(result, "ALLOW")) {
942 LOGE("unknown response from Superuser Requestor: %s", result);