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) {
85 if (fork_zero_fucks() == 0) {
86 int zero = open("/dev/zero", O_RDONLY);
87 int null = open("/dev/null", O_WRONLY);
88 dup2(zero, 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);
96 void exec_loge(const char* fmt, ...) {
99 char logline[PATH_MAX];
101 vsnprintf(logline, PATH_MAX, fmt, args);
103 exec_log("e", logline);
106 void exec_logw(const char* fmt, ...) {
109 char logline[PATH_MAX];
111 vsnprintf(logline, PATH_MAX, fmt, args);
113 exec_log("w", logline);
116 void exec_logd(const char* fmt, ...) {
119 char logline[PATH_MAX];
121 vsnprintf(logline, PATH_MAX, fmt, args);
123 exec_log("d", logline);
126 static int from_init(struct su_initiator *from) {
127 char path[PATH_MAX], exe[PATH_MAX];
128 char args[4096], *argv0, *argv_rest;
134 from->uid = getuid();
135 from->pid = getppid();
137 /* Get the command line */
138 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
139 fd = open(path, O_RDONLY);
141 PLOGE("Opening command line");
144 len = read(fd, args, sizeof(args));
147 if (len < 0 || len == sizeof(args)) {
148 PLOGEV("Reading command line", err);
154 for (i = 0; i < len; i++) {
155 if (args[i] == '\0') {
157 argv_rest = &args[i+1];
166 strncpy(from->args, argv_rest, sizeof(from->args));
167 from->args[sizeof(from->args)-1] = '\0';
169 from->args[0] = '\0';
172 /* If this isn't app_process, use the real path instead of argv[0] */
173 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
174 len = readlink(path, exe, sizeof(exe));
176 PLOGE("Getting exe path");
180 if (strcmp(exe, "/system/bin/app_process")) {
184 strncpy(from->bin, argv0, sizeof(from->bin));
185 from->bin[sizeof(from->bin)-1] = '\0';
188 pw = getpwuid(from->uid);
189 if (pw && pw->pw_name) {
190 strncpy(from->name, pw->pw_name, sizeof(from->name));
194 from->uid = daemon_from_uid;
195 from->pid = daemon_from_pid;
201 static int get_multiuser_mode() {
203 char sdk_ver[PROPERTY_VALUE_MAX];
205 data = read_file("/system/build.prop");
206 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
209 int sdk = atoi(sdk_ver);
211 return MULTIUSER_MODE_NONE;
213 int ret = MULTIUSER_MODE_OWNER_ONLY;
216 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
217 fgets(mode, sizeof(mode), fp);
218 int last = strlen(mode) - 1;
219 if (mode[last] == '\n')
221 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
222 ret = MULTIUSER_MODE_USER;
223 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
224 ret = MULTIUSER_MODE_OWNER_MANAGED;
227 ret = MULTIUSER_MODE_OWNER_ONLY;
234 static void read_options(struct su_context *ctx) {
235 ctx->user.multiuser_mode = get_multiuser_mode();
238 static void user_init(struct su_context *ctx) {
239 if (ctx->from.uid > 99999) {
240 ctx->user.android_user_id = ctx->from.uid / 100000;
241 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
242 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
243 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
248 static void populate_environment(const struct su_context *ctx) {
254 pw = getpwuid(ctx->to.uid);
256 setenv("HOME", pw->pw_dir, 1);
258 setenv("SHELL", ctx->to.shell, 1);
260 setenv("SHELL", DEFAULT_SHELL, 1);
261 if (ctx->to.login || ctx->to.uid) {
262 setenv("USER", pw->pw_name, 1);
263 setenv("LOGNAME", pw->pw_name, 1);
268 void set_identity(unsigned int uid) {
270 * Set effective uid back to root, otherwise setres[ug]id will fail
274 PLOGE("seteuid (root)");
277 if (setresgid(uid, uid, uid)) {
278 PLOGE("setresgid (%u)", uid);
281 if (setresuid(uid, uid, uid)) {
282 PLOGE("setresuid (%u)", uid);
287 static void socket_cleanup(struct su_context *ctx) {
288 if (ctx && ctx->sock_path[0]) {
289 if (unlink(ctx->sock_path))
290 PLOGE("unlink (%s)", ctx->sock_path);
291 ctx->sock_path[0] = 0;
296 * For use in signal handlers/atexit-function
297 * NOTE: su_ctx points to main's local variable.
298 * It's OK due to the program uses exit(3), not return from main()
300 static struct su_context *su_ctx = NULL;
302 static void cleanup(void) {
303 socket_cleanup(su_ctx);
306 static void cleanup_signal(int sig) {
307 socket_cleanup(su_ctx);
311 static int socket_create_temp(char *path, size_t len) {
313 struct sockaddr_un sun;
315 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
320 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
321 PLOGE("fcntl FD_CLOEXEC");
325 memset(&sun, 0, sizeof(sun));
326 sun.sun_family = AF_LOCAL;
327 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
328 memset(sun.sun_path, 0, sizeof(sun.sun_path));
329 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
332 * Delete the socket to protect from situations when
333 * something bad occured previously and the kernel reused pid from that process.
334 * Small probability, isn't it.
336 unlink(sun.sun_path);
338 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
343 if (listen(fd, 1) < 0) {
354 static int socket_accept(int serv_fd) {
359 /* Wait 20 seconds for a connection, then give up. */
363 FD_SET(serv_fd, &fds);
365 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
366 } while (rc < 0 && errno == EINTR);
372 fd = accept(serv_fd, NULL, NULL);
381 static int socket_send_request(int fd, const struct su_context *ctx) {
382 #define write_data(fd, data, data_len) \
384 size_t __len = htonl(data_len); \
385 __len = write((fd), &__len, sizeof(__len)); \
386 if (__len != sizeof(__len)) { \
387 PLOGE("write(" #data ")"); \
390 __len = write((fd), data, data_len); \
391 if (__len != data_len) { \
392 PLOGE("write(" #data ")"); \
397 #define write_string_data(fd, name, data) \
399 write_data(fd, name, strlen(name)); \
400 write_data(fd, data, strlen(data)); \
403 // stringify everything.
404 #define write_token(fd, name, data) \
407 snprintf(buf, sizeof(buf), "%d", data); \
408 write_string_data(fd, name, buf); \
411 write_token(fd, "version", PROTO_VERSION);
412 write_token(fd, "binary.version", VERSION_CODE);
413 write_token(fd, "pid", ctx->from.pid);
414 write_string_data(fd, "from.name", ctx->from.name);
415 write_string_data(fd, "to.name", ctx->to.name);
416 write_token(fd, "from.uid", ctx->from.uid);
417 write_token(fd, "to.uid", ctx->to.uid);
418 write_string_data(fd, "from.bin", ctx->from.bin);
419 // TODO: Fix issue where not using -c does not result a in a command
420 write_string_data(fd, "command", get_command(&ctx->to));
421 write_token(fd, "eof", PROTO_VERSION);
425 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
428 LOGD("waiting for user");
429 len = read(fd, result, result_len-1);
431 PLOGE("read(result)");
439 static void usage(int status) {
440 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
443 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
445 " --daemon start the su daemon agent\n"
446 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
447 " -h, --help display this help message and exit\n"
448 " -, -l, --login pretend the shell to be a login shell\n"
450 " --preserve-environment do not change environment variables\n"
451 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
452 " -u display the multiuser mode and exit\n"
453 " -v, --version display version number and exit\n"
454 " -V display version code and exit,\n"
455 " this is used almost exclusively by Superuser.apk\n");
459 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
460 char *cmd = get_command(&ctx->to);
464 // no need to log if called by root
465 if (ctx->from.uid == AID_ROOT)
468 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
469 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
473 send_result(ctx, DENY);
475 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
476 fprintf(stderr, "%s\n", strerror(EACCES));
480 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
487 // no need to log if called by root
488 if (ctx->from.uid == AID_ROOT)
491 // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
492 if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
496 send_result(ctx, ALLOW);
499 argc = ctx->to.optind;
500 if (ctx->to.command) {
501 binary = ctx->to.shell;
502 ctx->to.argv[--argc] = ctx->to.command;
503 ctx->to.argv[--argc] = "-c";
505 else if (ctx->to.shell) {
506 binary = ctx->to.shell;
509 if (ctx->to.argv[argc]) {
510 binary = ctx->to.argv[argc++];
513 binary = DEFAULT_SHELL;
517 arg0 = strrchr (binary, '/');
518 arg0 = (arg0) ? arg0 + 1 : binary;
520 int s = strlen(arg0) + 2;
531 populate_environment(ctx);
532 set_identity(ctx->to.uid);
535 (argc + (arg) < ctx->to.argc) ? " " : "", \
536 (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
538 LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
539 ctx->from.uid, ctx->from.bin,
540 ctx->to.uid, get_command(&ctx->to), binary,
541 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
542 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
544 ctx->to.argv[--argc] = arg0;
545 execvp(binary, ctx->to.argv + argc);
548 fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
553 * CyanogenMod-specific behavior
555 * we can't simply use the property service, since we aren't launched from init
556 * and can't trust the location of the property workspace.
557 * Find the properties ourselves.
559 int access_disabled(const struct su_initiator *from) {
561 char build_type[PROPERTY_VALUE_MAX];
562 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
565 data = read_file("/system/build.prop");
566 if (check_property(data, "ro.cm.version")) {
567 get_property(data, build_type, "ro.build.type", "");
570 data = read_file("/default.prop");
571 get_property(data, debuggable, "ro.debuggable", "0");
573 /* only allow su on debuggable builds */
574 if (strcmp("1", debuggable) != 0) {
575 LOGE("Root access is disabled on non-debug builds");
579 data = read_file("/data/property/persist.sys.root_access");
582 if (len >= PROPERTY_VALUE_MAX)
583 memcpy(enabled, "1", 2);
585 memcpy(enabled, data, len + 1);
588 memcpy(enabled, "1", 2);
590 /* enforce persist.sys.root_access on non-eng builds for apps */
591 if (strcmp("eng", build_type) != 0 &&
592 from->uid != AID_SHELL && from->uid != AID_ROOT &&
593 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
594 LOGE("Apps root access is disabled by system setting - "
595 "enable it under settings -> developer options");
599 /* disallow su in a shell if appropriate */
600 if (from->uid == AID_SHELL &&
601 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
602 LOGE("Shell root access is disabled by a system setting - "
603 "enable it under settings -> developer options");
611 int main(int argc, char *argv[]) {
612 // start up in daemon mode if prompted
613 if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
617 if (geteuid() != AID_ROOT && getuid() != AID_ROOT) {
618 // attempt to connect to daemon...
619 LOGD("starting daemon client %d %d", getuid(), geteuid());
620 return connect_daemon(argc, argv);
623 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
624 /* The same list than GLibc at this point */
625 static const char* const unsec_vars[] = {
649 "LD_AOUT_LIBRARY_PATH",
651 // not listed in linker, used due to system() call
654 const char* const* cp = unsec_vars;
655 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
662 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
663 * This occurs on Android 4.0+
665 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
669 struct su_context ctx = {
689 .android_user_id = 0,
690 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
691 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
692 .base_path = REQUESTOR_DATA_PATH REQUESTOR
696 int c, socket_serv_fd, fd;
697 char buf[64], *result;
699 struct option long_opts[] = {
700 { "command", required_argument, NULL, 'c' },
701 { "help", no_argument, NULL, 'h' },
702 { "login", no_argument, NULL, 'l' },
703 { "preserve-environment", no_argument, NULL, 'p' },
704 { "shell", required_argument, NULL, 's' },
705 { "version", no_argument, NULL, 'v' },
706 { NULL, 0, NULL, 0 },
709 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
712 ctx.to.shell = DEFAULT_SHELL;
713 ctx.to.command = optarg;
726 ctx.to.shell = optarg;
729 printf("%d\n", VERSION_CODE);
732 printf("%s\n", VERSION);
735 switch (get_multiuser_mode()) {
736 case MULTIUSER_MODE_USER:
737 printf("%s\n", MULTIUSER_VALUE_USER);
739 case MULTIUSER_MODE_OWNER_MANAGED:
740 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
742 case MULTIUSER_MODE_OWNER_ONLY:
743 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
745 case MULTIUSER_MODE_NONE:
746 printf("%s\n", MULTIUSER_VALUE_NONE);
751 /* Bionic getopt_long doesn't terminate its error output by newline */
752 fprintf(stderr, "\n");
756 if (optind < argc && !strcmp(argv[optind], "-")) {
760 /* username or uid */
761 if (optind < argc && strcmp(argv[optind], "--")) {
763 pw = getpwnam(argv[optind]);
767 /* It seems we shouldn't do this at all */
769 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
770 if (errno || *endptr) {
771 LOGE("Unknown id: %s\n", argv[optind]);
772 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
776 ctx.to.uid = pw->pw_uid;
778 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
782 if (optind < argc && !strcmp(argv[optind], "--")) {
785 ctx.to.optind = optind;
788 if (from_init(&ctx.from) < 0) {
795 // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
796 if (ctx.from.uid == AID_ROOT) {
797 LOGD("Allowing root/system/radio.");
801 // verify superuser is installed
802 if (stat(ctx.user.base_path, &st) < 0) {
803 // send to market (disabled, because people are and think this is hijacking their su)
804 // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
805 // silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
806 PLOGE("stat %s", ctx.user.base_path);
810 // odd perms on superuser data dir
811 if (st.st_gid != st.st_uid) {
812 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
813 (int)st.st_uid, (int)st.st_gid);
817 // always allow if this is the superuser uid
818 // superuser needs to be able to reenable itself when disabled...
819 if (ctx.from.uid == st.st_uid) {
823 // check if superuser is disabled completely
824 if (access_disabled(&ctx.from)) {
825 LOGD("access_disabled");
829 // autogrant shell at this point
830 if (ctx.from.uid == AID_SHELL) {
831 LOGD("Allowing shell.");
835 // deny if this is a non owner request and owner mode only
836 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
840 ctx.umask = umask(027);
842 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
843 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
844 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
848 if (setgroups(0, NULL)) {
852 if (setegid(st.st_gid)) {
853 PLOGE("setegid (%lu)", st.st_gid);
856 if (seteuid(st.st_uid)) {
857 PLOGE("seteuid (%lu)", st.st_uid);
861 dballow = database_check(&ctx);
867 allow(&ctx); /* never returns */
871 deny(&ctx); /* never returns too */
874 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
876 if (socket_serv_fd < 0) {
880 signal(SIGHUP, cleanup_signal);
881 signal(SIGPIPE, cleanup_signal);
882 signal(SIGTERM, cleanup_signal);
883 signal(SIGQUIT, cleanup_signal);
884 signal(SIGINT, cleanup_signal);
885 signal(SIGABRT, cleanup_signal);
887 if (send_request(&ctx) < 0) {
893 fd = socket_accept(socket_serv_fd);
897 if (socket_send_request(fd, &ctx)) {
900 if (socket_receive_result(fd, buf, sizeof(buf))) {
905 close(socket_serv_fd);
906 socket_cleanup(&ctx);
910 #define SOCKET_RESPONSE "socket:"
911 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
912 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
914 result += sizeof(SOCKET_RESPONSE) - 1;
916 if (!strcmp(result, "DENY")) {
918 } else if (!strcmp(result, "ALLOW")) {
921 LOGE("unknown response from Superuser Requestor: %s", result);