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->user.multiuser_mode != MULTIUSER_MODE_NONE) {
243 ctx->user.android_user_id = ctx->from.uid / 100000;
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);
249 static void populate_environment(const struct su_context *ctx) {
255 pw = getpwuid(ctx->to.uid);
257 setenv("HOME", pw->pw_dir, 1);
259 setenv("SHELL", ctx->to.shell, 1);
261 setenv("SHELL", DEFAULT_SHELL, 1);
262 if (ctx->to.login || ctx->to.uid) {
263 setenv("USER", pw->pw_name, 1);
264 setenv("LOGNAME", pw->pw_name, 1);
269 void set_identity(unsigned int uid) {
271 * Set effective uid back to root, otherwise setres[ug]id will fail
275 PLOGE("seteuid (root)");
278 if (setresgid(uid, uid, uid)) {
279 PLOGE("setresgid (%u)", uid);
282 if (setresuid(uid, uid, uid)) {
283 PLOGE("setresuid (%u)", uid);
288 static void socket_cleanup(struct su_context *ctx) {
289 if (ctx && ctx->sock_path[0]) {
290 if (unlink(ctx->sock_path))
291 PLOGE("unlink (%s)", ctx->sock_path);
292 ctx->sock_path[0] = 0;
297 * For use in signal handlers/atexit-function
298 * NOTE: su_ctx points to main's local variable.
299 * It's OK due to the program uses exit(3), not return from main()
301 static struct su_context *su_ctx = NULL;
303 static void cleanup(void) {
304 socket_cleanup(su_ctx);
307 static void cleanup_signal(int sig) {
308 socket_cleanup(su_ctx);
312 static int socket_create_temp(char *path, size_t len) {
314 struct sockaddr_un sun;
316 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
321 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
322 PLOGE("fcntl FD_CLOEXEC");
326 memset(&sun, 0, sizeof(sun));
327 sun.sun_family = AF_LOCAL;
328 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
329 memset(sun.sun_path, 0, sizeof(sun.sun_path));
330 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
333 * Delete the socket to protect from situations when
334 * something bad occured previously and the kernel reused pid from that process.
335 * Small probability, isn't it.
337 unlink(sun.sun_path);
339 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
344 if (listen(fd, 1) < 0) {
355 static int socket_accept(int serv_fd) {
360 /* Wait 20 seconds for a connection, then give up. */
364 FD_SET(serv_fd, &fds);
366 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
367 } while (rc < 0 && errno == EINTR);
373 fd = accept(serv_fd, NULL, NULL);
382 static int socket_send_request(int fd, const struct su_context *ctx) {
383 #define write_data(fd, data, data_len) \
385 uint32_t __len = htonl(data_len); \
386 __len = write((fd), &__len, sizeof(__len)); \
387 if (__len != sizeof(__len)) { \
388 PLOGE("write(" #data ")"); \
391 __len = write((fd), data, data_len); \
392 if (__len != data_len) { \
393 PLOGE("write(" #data ")"); \
398 #define write_string_data(fd, name, data) \
400 write_data(fd, name, strlen(name)); \
401 write_data(fd, data, strlen(data)); \
404 // stringify everything.
405 #define write_token(fd, name, data) \
408 snprintf(buf, sizeof(buf), "%d", data); \
409 write_string_data(fd, name, buf); \
412 write_token(fd, "version", PROTO_VERSION);
413 write_token(fd, "binary.version", VERSION_CODE);
414 write_token(fd, "pid", ctx->from.pid);
415 write_string_data(fd, "from.name", ctx->from.name);
416 write_string_data(fd, "to.name", ctx->to.name);
417 write_token(fd, "from.uid", ctx->from.uid);
418 write_token(fd, "to.uid", ctx->to.uid);
419 write_string_data(fd, "from.bin", ctx->from.bin);
420 // TODO: Fix issue where not using -c does not result a in a command
421 write_string_data(fd, "command", get_command(&ctx->to));
422 write_token(fd, "eof", PROTO_VERSION);
426 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
429 LOGD("waiting for user");
430 len = read(fd, result, result_len-1);
432 PLOGE("read(result)");
440 static void usage(int status) {
441 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
444 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
446 " --daemon start the su daemon agent\n"
447 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
448 " -h, --help display this help message and exit\n"
449 " -, -l, --login pretend the shell to be a login shell\n"
451 " --preserve-environment do not change environment variables\n"
452 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
453 " -u display the multiuser mode and exit\n"
454 " -v, --version display version number and exit\n"
455 " -V display version code and exit,\n"
456 " this is used almost exclusively by Superuser.apk\n");
460 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
461 char *cmd = get_command(&ctx->to);
465 // no need to log if called by root
466 if (ctx->from.uid == AID_ROOT)
469 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
470 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
474 send_result(ctx, DENY);
476 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
477 fprintf(stderr, "%s\n", strerror(EACCES));
481 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
488 // no need to log if called by root
489 if (ctx->from.uid == AID_ROOT)
492 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
493 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
497 send_result(ctx, ALLOW);
500 argc = ctx->to.optind;
501 if (ctx->to.command) {
502 binary = ctx->to.shell;
503 ctx->to.argv[--argc] = ctx->to.command;
504 ctx->to.argv[--argc] = "-c";
506 else if (ctx->to.shell) {
507 binary = ctx->to.shell;
510 if (ctx->to.argv[argc]) {
511 binary = ctx->to.argv[argc++];
514 binary = DEFAULT_SHELL;
518 arg0 = strrchr (binary, '/');
519 arg0 = (arg0) ? arg0 + 1 : binary;
521 int s = strlen(arg0) + 2;
532 populate_environment(ctx);
533 set_identity(ctx->to.uid);
536 (argc + (arg) < ctx->to.argc) ? " " : "", \
537 (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
539 LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
540 ctx->from.uid, ctx->from.bin,
541 ctx->to.uid, get_command(&ctx->to), binary,
542 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
543 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
545 ctx->to.argv[--argc] = arg0;
546 execvp(binary, ctx->to.argv + argc);
549 fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
554 * CyanogenMod-specific behavior
556 * we can't simply use the property service, since we aren't launched from init
557 * and can't trust the location of the property workspace.
558 * Find the properties ourselves.
560 int access_disabled(const struct su_initiator *from) {
561 #ifndef SUPERUSER_EMBEDDED
565 char build_type[PROPERTY_VALUE_MAX];
566 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
569 data = read_file("/system/build.prop");
570 if (check_property(data, "ro.cm.version")) {
571 get_property(data, build_type, "ro.build.type", "");
574 data = read_file("/default.prop");
575 get_property(data, debuggable, "ro.debuggable", "0");
577 /* only allow su on debuggable builds */
578 if (strcmp("1", debuggable) != 0) {
579 LOGE("Root access is disabled on non-debug builds");
583 data = read_file("/data/property/persist.sys.root_access");
586 if (len >= PROPERTY_VALUE_MAX)
587 memcpy(enabled, "0", 2);
589 memcpy(enabled, data, len + 1);
592 memcpy(enabled, "0", 2);
594 /* enforce persist.sys.root_access on non-eng builds for apps */
595 if (strcmp("eng", build_type) != 0 &&
596 from->uid != AID_SHELL && from->uid != AID_ROOT &&
597 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
598 LOGE("Apps root access is disabled by system setting - "
599 "enable it under settings -> developer options");
603 /* disallow su in a shell if appropriate */
604 if (from->uid == AID_SHELL &&
605 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
606 LOGE("Shell root access is disabled by a system setting - "
607 "enable it under settings -> developer options");
616 static int get_api_version() {
617 char sdk_ver[PROPERTY_VALUE_MAX];
618 char *data = read_file("/system/build.prop");
619 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
620 int ver = atoi(sdk_ver);
625 static void fork_for_samsung(void)
627 // Samsung CONFIG_SEC_RESTRICT_SETUID wants the parent process to have
628 // EUID 0, or else our setresuid() calls will be denied. So make sure
629 // all such syscalls are executed by a child process.
642 exit(WEXITSTATUS(rv));
647 int main(int argc, char *argv[]) {
648 return su_main(argc, argv, 1);
651 int su_main(int argc, char *argv[], int need_client) {
652 // start up in daemon mode if prompted
653 if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
657 int ppid = getppid();
660 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
661 /* The same list than GLibc at this point */
662 static const char* const unsec_vars[] = {
686 "LD_AOUT_LIBRARY_PATH",
688 // not listed in linker, used due to system() call
691 const char* const* cp = unsec_vars;
692 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
700 struct su_context ctx = {
720 .android_user_id = 0,
721 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
722 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
723 .base_path = REQUESTOR_DATA_PATH REQUESTOR
727 int c, socket_serv_fd, fd;
728 char buf[64], *result;
730 struct option long_opts[] = {
731 { "command", required_argument, NULL, 'c' },
732 { "help", no_argument, NULL, 'h' },
733 { "login", no_argument, NULL, 'l' },
734 { "preserve-environment", no_argument, NULL, 'p' },
735 { "shell", required_argument, NULL, 's' },
736 { "version", no_argument, NULL, 'v' },
737 { NULL, 0, NULL, 0 },
740 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
743 ctx.to.shell = DEFAULT_SHELL;
744 ctx.to.command = optarg;
757 ctx.to.shell = optarg;
760 printf("%d\n", VERSION_CODE);
763 printf("%s\n", VERSION);
766 switch (get_multiuser_mode()) {
767 case MULTIUSER_MODE_USER:
768 printf("%s\n", MULTIUSER_VALUE_USER);
770 case MULTIUSER_MODE_OWNER_MANAGED:
771 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
773 case MULTIUSER_MODE_OWNER_ONLY:
774 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
776 case MULTIUSER_MODE_NONE:
777 printf("%s\n", MULTIUSER_VALUE_NONE);
782 /* Bionic getopt_long doesn't terminate its error output by newline */
783 fprintf(stderr, "\n");
789 // attempt to use the daemon client if not root,
790 // or this is api 18 and adb shell (/data is not readable even as root)
791 // or just always use it on API 19+ (ART)
792 if ((geteuid() != AID_ROOT && getuid() != AID_ROOT) ||
793 (get_api_version() >= 18 && getuid() == AID_SHELL) ||
794 get_api_version() >= 19) {
795 // attempt to connect to daemon...
796 LOGD("starting daemon client %d %d", getuid(), geteuid());
797 return connect_daemon(argc, argv, ppid);
801 if (optind < argc && !strcmp(argv[optind], "-")) {
805 /* username or uid */
806 if (optind < argc && strcmp(argv[optind], "--")) {
808 pw = getpwnam(argv[optind]);
812 /* It seems we shouldn't do this at all */
814 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
815 if (errno || *endptr) {
816 LOGE("Unknown id: %s\n", argv[optind]);
817 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
821 ctx.to.uid = pw->pw_uid;
823 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
827 if (optind < argc && !strcmp(argv[optind], "--")) {
830 ctx.to.optind = optind;
833 if (from_init(&ctx.from) < 0) {
840 // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
841 if (ctx.from.uid == AID_ROOT) {
842 LOGD("Allowing root/system/radio.");
846 // verify superuser is installed
847 if (stat(ctx.user.base_path, &st) < 0) {
848 // send to market (disabled, because people are and think this is hijacking their su)
849 // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
850 // silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
851 PLOGE("stat %s", ctx.user.base_path);
855 // odd perms on superuser data dir
856 if (st.st_gid != st.st_uid) {
857 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
858 (int)st.st_uid, (int)st.st_gid);
862 // always allow if this is the superuser uid
863 // superuser needs to be able to reenable itself when disabled...
864 if (ctx.from.uid == st.st_uid) {
868 // check if superuser is disabled completely
869 if (access_disabled(&ctx.from)) {
870 LOGD("access_disabled");
874 // autogrant shell at this point
875 if (ctx.from.uid == AID_SHELL) {
876 LOGD("Allowing shell.");
880 // deny if this is a non owner request and owner mode only
881 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
885 ctx.umask = umask(027);
887 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
888 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
889 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
893 if (setgroups(0, NULL)) {
897 if (setegid(st.st_gid)) {
898 PLOGE("setegid (%lu)", st.st_gid);
901 if (seteuid(st.st_uid)) {
902 PLOGE("seteuid (%lu)", st.st_uid);
906 dballow = database_check(&ctx);
912 allow(&ctx); /* never returns */
916 deny(&ctx); /* never returns too */
919 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
921 if (socket_serv_fd < 0) {
925 signal(SIGHUP, cleanup_signal);
926 signal(SIGPIPE, cleanup_signal);
927 signal(SIGTERM, cleanup_signal);
928 signal(SIGQUIT, cleanup_signal);
929 signal(SIGINT, cleanup_signal);
930 signal(SIGABRT, cleanup_signal);
932 if (send_request(&ctx) < 0) {
938 fd = socket_accept(socket_serv_fd);
942 if (socket_send_request(fd, &ctx)) {
945 if (socket_receive_result(fd, buf, sizeof(buf))) {
950 close(socket_serv_fd);
951 socket_cleanup(&ctx);
955 #define SOCKET_RESPONSE "socket:"
956 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
957 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
959 result += sizeof(SOCKET_RESPONSE) - 1;
961 if (!strcmp(result, "DENY")) {
963 } else if (!strcmp(result, "ALLOW")) {
966 LOGE("unknown response from Superuser Requestor: %s", result);