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>
35 #include <sys/endian.h>
41 extern int daemon_from_uid;
42 extern int daemon_from_pid;
44 unsigned get_shell_uid() {
45 struct passwd* ppwd = getpwnam("shell");
53 unsigned get_system_uid() {
54 struct passwd* ppwd = getpwnam("system");
62 unsigned get_radio_uid() {
63 struct passwd* ppwd = getpwnam("radio");
71 int fork_zero_fucks() {
75 waitpid(pid, &status, 0);
85 void exec_log(char *priority, char* logline) {
87 if ((pid = fork()) == 0) {
88 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
89 dup2(null, STDIN_FILENO);
90 dup2(null, STDOUT_FILENO);
91 dup2(null, STDERR_FILENO);
92 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline, NULL);
96 waitpid(pid, &status, 0);
99 void exec_loge(const char* fmt, ...) {
102 char logline[PATH_MAX];
104 vsnprintf(logline, PATH_MAX, fmt, args);
106 exec_log("e", logline);
109 void exec_logw(const char* fmt, ...) {
112 char logline[PATH_MAX];
114 vsnprintf(logline, PATH_MAX, fmt, args);
116 exec_log("w", logline);
119 void exec_logd(const char* fmt, ...) {
122 char logline[PATH_MAX];
124 vsnprintf(logline, PATH_MAX, fmt, args);
126 exec_log("d", logline);
129 static int from_init(struct su_initiator *from) {
130 char path[PATH_MAX], exe[PATH_MAX];
131 char args[4096], *argv0, *argv_rest;
137 from->uid = getuid();
138 from->pid = getppid();
141 from->uid = daemon_from_uid;
142 from->pid = daemon_from_pid;
145 /* Get the command line */
146 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
147 fd = open(path, O_RDONLY);
149 PLOGE("Opening command line");
152 len = read(fd, args, sizeof(args));
155 if (len < 0 || len == sizeof(args)) {
156 PLOGEV("Reading command line", err);
162 for (i = 0; i < len; i++) {
163 if (args[i] == '\0') {
165 argv_rest = &args[i+1];
174 strncpy(from->args, argv_rest, sizeof(from->args));
175 from->args[sizeof(from->args)-1] = '\0';
177 from->args[0] = '\0';
180 /* If this isn't app_process, use the real path instead of argv[0] */
181 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
182 len = readlink(path, exe, sizeof(exe));
184 PLOGE("Getting exe path");
188 if (strcmp(exe, "/system/bin/app_process")) {
192 strncpy(from->bin, argv0, sizeof(from->bin));
193 from->bin[sizeof(from->bin)-1] = '\0';
196 pw = getpwuid(from->uid);
197 if (pw && pw->pw_name) {
198 strncpy(from->name, pw->pw_name, sizeof(from->name));
204 static int get_multiuser_mode() {
206 char sdk_ver[PROPERTY_VALUE_MAX];
208 data = read_file("/system/build.prop");
209 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
212 int sdk = atoi(sdk_ver);
214 return MULTIUSER_MODE_NONE;
216 int ret = MULTIUSER_MODE_OWNER_ONLY;
219 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
220 fgets(mode, sizeof(mode), fp);
221 int last = strlen(mode) - 1;
222 if (mode[last] == '\n')
224 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
225 ret = MULTIUSER_MODE_USER;
226 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
227 ret = MULTIUSER_MODE_OWNER_MANAGED;
230 ret = MULTIUSER_MODE_OWNER_ONLY;
237 static void read_options(struct su_context *ctx) {
238 ctx->user.multiuser_mode = get_multiuser_mode();
241 static void user_init(struct su_context *ctx) {
242 if (ctx->from.uid > 99999) {
243 ctx->user.android_user_id = ctx->from.uid / 100000;
244 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
245 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
246 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
251 static void populate_environment(const struct su_context *ctx) {
257 pw = getpwuid(ctx->to.uid);
259 setenv("HOME", pw->pw_dir, 1);
261 setenv("SHELL", ctx->to.shell, 1);
263 setenv("SHELL", DEFAULT_SHELL, 1);
264 if (ctx->to.login || ctx->to.uid) {
265 setenv("USER", pw->pw_name, 1);
266 setenv("LOGNAME", pw->pw_name, 1);
271 void set_identity(unsigned int uid) {
273 * Set effective uid back to root, otherwise setres[ug]id will fail
277 PLOGE("seteuid (root)");
280 if (setresgid(uid, uid, uid)) {
281 PLOGE("setresgid (%u)", uid);
284 if (setresuid(uid, uid, uid)) {
285 PLOGE("setresuid (%u)", uid);
290 static void socket_cleanup(struct su_context *ctx) {
291 if (ctx && ctx->sock_path[0]) {
292 if (unlink(ctx->sock_path))
293 PLOGE("unlink (%s)", ctx->sock_path);
294 ctx->sock_path[0] = 0;
299 * For use in signal handlers/atexit-function
300 * NOTE: su_ctx points to main's local variable.
301 * It's OK due to the program uses exit(3), not return from main()
303 static struct su_context *su_ctx = NULL;
305 static void cleanup(void) {
306 socket_cleanup(su_ctx);
309 static void cleanup_signal(int sig) {
310 socket_cleanup(su_ctx);
314 static int socket_create_temp(char *path, size_t len) {
316 struct sockaddr_un sun;
318 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
323 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
324 PLOGE("fcntl FD_CLOEXEC");
328 memset(&sun, 0, sizeof(sun));
329 sun.sun_family = AF_LOCAL;
330 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
331 memset(sun.sun_path, 0, sizeof(sun.sun_path));
332 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
335 * Delete the socket to protect from situations when
336 * something bad occured previously and the kernel reused pid from that process.
337 * Small probability, isn't it.
339 unlink(sun.sun_path);
341 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
346 if (listen(fd, 1) < 0) {
357 static int socket_accept(int serv_fd) {
362 /* Wait 20 seconds for a connection, then give up. */
366 FD_SET(serv_fd, &fds);
368 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
369 } while (rc < 0 && errno == EINTR);
375 fd = accept(serv_fd, NULL, NULL);
384 static int socket_send_request(int fd, const struct su_context *ctx) {
385 #define write_data(fd, data, data_len) \
387 uint32_t __len = htonl(data_len); \
388 __len = write((fd), &__len, sizeof(__len)); \
389 if (__len != sizeof(__len)) { \
390 PLOGE("write(" #data ")"); \
393 __len = write((fd), data, data_len); \
394 if (__len != data_len) { \
395 PLOGE("write(" #data ")"); \
400 #define write_string_data(fd, name, data) \
402 write_data(fd, name, strlen(name)); \
403 write_data(fd, data, strlen(data)); \
406 // stringify everything.
407 #define write_token(fd, name, data) \
410 snprintf(buf, sizeof(buf), "%d", data); \
411 write_string_data(fd, name, buf); \
414 write_token(fd, "version", PROTO_VERSION);
415 write_token(fd, "binary.version", VERSION_CODE);
416 write_token(fd, "pid", ctx->from.pid);
417 write_string_data(fd, "from.name", ctx->from.name);
418 write_string_data(fd, "to.name", ctx->to.name);
419 write_token(fd, "from.uid", ctx->from.uid);
420 write_token(fd, "to.uid", ctx->to.uid);
421 write_string_data(fd, "from.bin", ctx->from.bin);
422 // TODO: Fix issue where not using -c does not result a in a command
423 write_string_data(fd, "command", get_command(&ctx->to));
424 write_token(fd, "eof", PROTO_VERSION);
428 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
431 LOGD("waiting for user");
432 len = read(fd, result, result_len-1);
434 PLOGE("read(result)");
442 static void usage(int status) {
443 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
446 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
448 " --daemon start the su daemon agent\n"
449 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
450 " -h, --help display this help message and exit\n"
451 " -, -l, --login pretend the shell to be a login shell\n"
453 " --preserve-environment do not change environment variables\n"
454 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
455 " -u display the multiuser mode and exit\n"
456 " -v, --version display version number and exit\n"
457 " -V display version code and exit,\n"
458 " this is used almost exclusively by Superuser.apk\n");
462 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
463 char *cmd = get_command(&ctx->to);
467 // no need to log if called by root
468 if (ctx->from.uid == AID_ROOT)
471 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
472 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
476 send_result(ctx, DENY);
478 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
479 fprintf(stderr, "%s\n", strerror(EACCES));
483 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
490 // no need to log if called by root
491 if (ctx->from.uid == AID_ROOT)
494 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
495 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
499 send_result(ctx, ALLOW);
502 argc = ctx->to.optind;
503 if (ctx->to.command) {
504 binary = ctx->to.shell;
505 ctx->to.argv[--argc] = ctx->to.command;
506 ctx->to.argv[--argc] = "-c";
508 else if (ctx->to.shell) {
509 binary = ctx->to.shell;
512 if (ctx->to.argv[argc]) {
513 binary = ctx->to.argv[argc++];
516 binary = DEFAULT_SHELL;
520 arg0 = strrchr (binary, '/');
521 arg0 = (arg0) ? arg0 + 1 : binary;
523 int s = strlen(arg0) + 2;
534 populate_environment(ctx);
535 set_identity(ctx->to.uid);
538 (argc + (arg) < ctx->to.argc) ? " " : "", \
539 (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
541 LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
542 ctx->from.uid, ctx->from.bin,
543 ctx->to.uid, get_command(&ctx->to), binary,
544 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
545 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
547 ctx->to.argv[--argc] = arg0;
548 execvp(binary, ctx->to.argv + argc);
551 fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
556 * CyanogenMod-specific behavior
558 * we can't simply use the property service, since we aren't launched from init
559 * and can't trust the location of the property workspace.
560 * Find the properties ourselves.
562 int access_disabled(const struct su_initiator *from) {
563 #ifndef SUPERUSER_EMBEDDED
567 char build_type[PROPERTY_VALUE_MAX];
568 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
571 data = read_file("/system/build.prop");
572 if (check_property(data, "ro.cm.version")) {
573 get_property(data, build_type, "ro.build.type", "");
576 data = read_file("/default.prop");
577 get_property(data, debuggable, "ro.debuggable", "0");
579 /* only allow su on debuggable builds */
580 if (strcmp("1", debuggable) != 0) {
581 LOGE("Root access is disabled on non-debug builds");
585 data = read_file("/data/property/persist.sys.root_access");
588 if (len >= PROPERTY_VALUE_MAX)
589 memcpy(enabled, "0", 2);
591 memcpy(enabled, data, len + 1);
594 memcpy(enabled, "0", 2);
596 /* enforce persist.sys.root_access on non-eng builds for apps */
597 if (strcmp("eng", build_type) != 0 &&
598 from->uid != AID_SHELL && from->uid != AID_ROOT &&
599 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
600 LOGE("Apps root access is disabled by system setting - "
601 "enable it under settings -> developer options");
605 /* disallow su in a shell if appropriate */
606 if (from->uid == AID_SHELL &&
607 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
608 LOGE("Shell root access is disabled by a system setting - "
609 "enable it under settings -> developer options");
618 static int get_api_version() {
619 char sdk_ver[PROPERTY_VALUE_MAX];
620 char *data = read_file("/system/build.prop");
621 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
622 int ver = atoi(sdk_ver);
627 static void fork_for_samsung(void)
629 // Samsung CONFIG_SEC_RESTRICT_SETUID wants the parent process to have
630 // EUID 0, or else our setresuid() calls will be denied. So make sure
631 // all such syscalls are executed by a child process.
644 exit(WEXITSTATUS(rv));
649 int main(int argc, char *argv[]) {
650 return su_main(argc, argv, 1);
653 int su_main(int argc, char *argv[], int need_client) {
654 // start up in daemon mode if prompted
655 if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
659 int ppid = getppid();
662 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
663 /* The same list than GLibc at this point */
664 static const char* const unsec_vars[] = {
688 "LD_AOUT_LIBRARY_PATH",
690 // not listed in linker, used due to system() call
693 const char* const* cp = unsec_vars;
694 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
702 struct su_context ctx = {
722 .android_user_id = 0,
723 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
724 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
725 .base_path = REQUESTOR_DATA_PATH REQUESTOR
729 int c, socket_serv_fd, fd;
730 char buf[64], *result;
732 struct option long_opts[] = {
733 { "command", required_argument, NULL, 'c' },
734 { "help", no_argument, NULL, 'h' },
735 { "login", no_argument, NULL, 'l' },
736 { "preserve-environment", no_argument, NULL, 'p' },
737 { "shell", required_argument, NULL, 's' },
738 { "version", no_argument, NULL, 'v' },
739 { NULL, 0, NULL, 0 },
742 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
745 ctx.to.shell = DEFAULT_SHELL;
746 ctx.to.command = optarg;
759 ctx.to.shell = optarg;
762 printf("%d\n", VERSION_CODE);
765 printf("%s\n", VERSION);
768 switch (get_multiuser_mode()) {
769 case MULTIUSER_MODE_USER:
770 printf("%s\n", MULTIUSER_VALUE_USER);
772 case MULTIUSER_MODE_OWNER_MANAGED:
773 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
775 case MULTIUSER_MODE_OWNER_ONLY:
776 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
778 case MULTIUSER_MODE_NONE:
779 printf("%s\n", MULTIUSER_VALUE_NONE);
784 /* Bionic getopt_long doesn't terminate its error output by newline */
785 fprintf(stderr, "\n");
791 // attempt to use the daemon client if not root,
792 // or this is api 18 and adb shell (/data is not readable even as root)
793 // or just always use it on API 19+ (ART)
794 if ((geteuid() != AID_ROOT && getuid() != AID_ROOT) ||
795 (get_api_version() >= 18 && getuid() == AID_SHELL) ||
796 get_api_version() >= 19) {
797 // attempt to connect to daemon...
798 LOGD("starting daemon client %d %d", getuid(), geteuid());
799 return connect_daemon(argc, argv, ppid);
803 if (optind < argc && !strcmp(argv[optind], "-")) {
807 /* username or uid */
808 if (optind < argc && strcmp(argv[optind], "--")) {
810 pw = getpwnam(argv[optind]);
814 /* It seems we shouldn't do this at all */
816 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
817 if (errno || *endptr) {
818 LOGE("Unknown id: %s\n", argv[optind]);
819 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
823 ctx.to.uid = pw->pw_uid;
825 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
829 if (optind < argc && !strcmp(argv[optind], "--")) {
832 ctx.to.optind = optind;
835 if (from_init(&ctx.from) < 0) {
842 // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
843 if (ctx.from.uid == AID_ROOT) {
844 LOGD("Allowing root/system/radio.");
848 // verify superuser is installed
849 if (stat(ctx.user.base_path, &st) < 0) {
850 // send to market (disabled, because people are and think this is hijacking their su)
851 // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
852 // silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
853 PLOGE("stat %s", ctx.user.base_path);
857 // odd perms on superuser data dir
858 if (st.st_gid != st.st_uid) {
859 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
860 (int)st.st_uid, (int)st.st_gid);
864 // always allow if this is the superuser uid
865 // superuser needs to be able to reenable itself when disabled...
866 if (ctx.from.uid == st.st_uid) {
870 // check if superuser is disabled completely
871 if (access_disabled(&ctx.from)) {
872 LOGD("access_disabled");
876 // autogrant shell at this point
877 if (ctx.from.uid == AID_SHELL) {
878 LOGD("Allowing shell.");
882 // deny if this is a non owner request and owner mode only
883 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
887 ctx.umask = umask(027);
889 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
890 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
891 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
895 if (setgroups(0, NULL)) {
899 if (setegid(st.st_gid)) {
900 PLOGE("setegid (%lu)", st.st_gid);
903 if (seteuid(st.st_uid)) {
904 PLOGE("seteuid (%lu)", st.st_uid);
908 dballow = database_check(&ctx);
914 allow(&ctx); /* never returns */
918 deny(&ctx); /* never returns too */
921 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
923 if (socket_serv_fd < 0) {
927 signal(SIGHUP, cleanup_signal);
928 signal(SIGPIPE, cleanup_signal);
929 signal(SIGTERM, cleanup_signal);
930 signal(SIGQUIT, cleanup_signal);
931 signal(SIGINT, cleanup_signal);
932 signal(SIGABRT, cleanup_signal);
934 if (send_request(&ctx) < 0) {
940 fd = socket_accept(socket_serv_fd);
944 if (socket_send_request(fd, &ctx)) {
947 if (socket_receive_result(fd, buf, sizeof(buf))) {
952 close(socket_serv_fd);
953 socket_cleanup(&ctx);
957 #define SOCKET_RESPONSE "socket:"
958 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
959 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
961 result += sizeof(SOCKET_RESPONSE) - 1;
963 if (!strcmp(result, "DENY")) {
965 } else if (!strcmp(result, "ALLOW")) {
968 LOGE("unknown response from Superuser Requestor: %s", result);