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>
39 unsigned get_shell_uid() {
40 struct passwd* ppwd = getpwnam("shell");
48 void exec_log(char *priority, char* logline) {
50 if ((pid = fork()) == 0) {
51 int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
53 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
56 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline);
61 void exec_loge(const char* fmt, ...) {
64 char logline[PATH_MAX];
66 vsnprintf(logline, PATH_MAX, fmt, args);
68 exec_log("e", logline);
71 void exec_logw(const char* fmt, ...) {
74 char logline[PATH_MAX];
76 vsnprintf(logline, PATH_MAX, fmt, args);
78 exec_log("w", logline);
81 void exec_logd(const char* fmt, ...) {
84 char logline[PATH_MAX];
86 vsnprintf(logline, PATH_MAX, fmt, args);
88 exec_log("d", logline);
91 static int from_init(struct su_initiator *from) {
92 char path[PATH_MAX], exe[PATH_MAX];
93 char args[4096], *argv0, *argv_rest;
100 from->pid = getppid();
102 /* Get the command line */
103 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
104 fd = open(path, O_RDONLY);
106 PLOGE("Opening command line");
109 len = read(fd, args, sizeof(args));
112 if (len < 0 || len == sizeof(args)) {
113 PLOGEV("Reading command line", err);
119 for (i = 0; i < len; i++) {
120 if (args[i] == '\0') {
122 argv_rest = &args[i+1];
131 strncpy(from->args, argv_rest, sizeof(from->args));
132 from->args[sizeof(from->args)-1] = '\0';
134 from->args[0] = '\0';
137 /* If this isn't app_process, use the real path instead of argv[0] */
138 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
139 len = readlink(path, exe, sizeof(exe));
141 PLOGE("Getting exe path");
145 if (strcmp(exe, "/system/bin/app_process")) {
149 strncpy(from->bin, argv0, sizeof(from->bin));
150 from->bin[sizeof(from->bin)-1] = '\0';
153 pw = getpwuid(from->uid);
154 if (pw && pw->pw_name) {
155 strncpy(from->name, pw->pw_name, sizeof(from->name));
161 static int get_multiuser_mode() {
163 char sdk_ver[PROPERTY_VALUE_MAX];
165 data = read_file("/system/build.prop");
166 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
169 int sdk = atoi(sdk_ver);
171 return MULTIUSER_MODE_NONE;
173 int ret = MULTIUSER_MODE_OWNER_ONLY;
176 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
177 int last = strlen(mode) - 1;
178 if (mode[last] == '\n')
180 fgets(mode, sizeof(mode), fp);
181 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
182 ret = MULTIUSER_MODE_USER;
183 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
184 ret = MULTIUSER_MODE_OWNER_MANAGED;
187 ret = MULTIUSER_MODE_OWNER_ONLY;
194 static void read_options(struct su_context *ctx) {
195 ctx->user.multiuser_mode = get_multiuser_mode();
198 static void user_init(struct su_context *ctx) {
199 if (ctx->from.uid > 99999) {
200 ctx->user.android_user_id = ctx->from.uid / 100000;
201 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
202 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
203 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
208 static void populate_environment(const struct su_context *ctx) {
214 pw = getpwuid(ctx->to.uid);
216 setenv("HOME", pw->pw_dir, 1);
217 setenv("SHELL", ctx->to.shell, 1);
218 if (ctx->to.login || ctx->to.uid) {
219 setenv("USER", pw->pw_name, 1);
220 setenv("LOGNAME", pw->pw_name, 1);
225 void set_identity(unsigned int uid) {
227 * Set effective uid back to root, otherwise setres[ug]id will fail
231 PLOGE("seteuid (root)");
234 if (setresgid(uid, uid, uid)) {
235 PLOGE("setresgid (%u)", uid);
238 if (setresuid(uid, uid, uid)) {
239 PLOGE("setresuid (%u)", uid);
244 static void socket_cleanup(struct su_context *ctx) {
245 if (ctx && ctx->sock_path[0]) {
246 if (unlink(ctx->sock_path))
247 PLOGE("unlink (%s)", ctx->sock_path);
248 ctx->sock_path[0] = 0;
253 * For use in signal handlers/atexit-function
254 * NOTE: su_ctx points to main's local variable.
255 * It's OK due to the program uses exit(3), not return from main()
257 static struct su_context *su_ctx = NULL;
259 static void cleanup(void) {
260 socket_cleanup(su_ctx);
263 static void cleanup_signal(int sig) {
264 socket_cleanup(su_ctx);
268 static int socket_create_temp(char *path, size_t len) {
270 struct sockaddr_un sun;
272 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
277 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
278 PLOGE("fcntl FD_CLOEXEC");
282 memset(&sun, 0, sizeof(sun));
283 sun.sun_family = AF_LOCAL;
284 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
285 memset(sun.sun_path, 0, sizeof(sun.sun_path));
286 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
289 * Delete the socket to protect from situations when
290 * something bad occured previously and the kernel reused pid from that process.
291 * Small probability, isn't it.
293 unlink(sun.sun_path);
295 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
300 if (listen(fd, 1) < 0) {
311 static int socket_accept(int serv_fd) {
316 /* Wait 20 seconds for a connection, then give up. */
320 FD_SET(serv_fd, &fds);
322 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
323 } while (rc < 0 && errno == EINTR);
329 fd = accept(serv_fd, NULL, NULL);
338 static int socket_send_request(int fd, const struct su_context *ctx) {
339 #define write_data(fd, data, data_len) \
341 size_t __len = htonl(data_len); \
342 __len = write((fd), &__len, sizeof(__len)); \
343 if (__len != sizeof(__len)) { \
344 PLOGE("write(" #data ")"); \
347 __len = write((fd), data, data_len); \
348 if (__len != data_len) { \
349 PLOGE("write(" #data ")"); \
354 #define write_string(fd, name, data) \
356 write_data(fd, name, strlen(name)); \
357 write_data(fd, data, strlen(data)); \
360 // stringify everything.
361 #define write_token(fd, name, data) \
364 snprintf(buf, sizeof(buf), "%d", data); \
365 write_string(fd, name, buf); \
368 write_token(fd, "version", PROTO_VERSION);
369 write_token(fd, "pid", ctx->from.pid);
370 write_string(fd, "from.name", ctx->from.name);
371 write_string(fd, "to.name", ctx->to.name);
372 write_token(fd, "from.uid", ctx->from.uid);
373 write_token(fd, "to.uid", ctx->to.uid);
374 write_string(fd, "from.bin", ctx->from.bin);
375 write_string(fd, "command", get_command(&ctx->to));
376 write_token(fd, "eof", PROTO_VERSION);
380 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
383 LOGD("waiting for user");
384 len = read(fd, result, result_len-1);
386 PLOGE("read(result)");
394 static void usage(int status) {
395 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
398 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
400 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
401 " -h, --help display this help message and exit\n"
402 " -, -l, --login pretend the shell to be a login shell\n"
404 " --preserve-environment do not change environment variables\n"
405 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
406 " -u display the multiuser mode and exit\n"
407 " -v, --version display version number and exit\n"
408 " -V display version code and exit,\n"
409 " this is used almost exclusively by Superuser.apk\n");
413 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
414 char *cmd = get_command(&ctx->to);
416 // No send to UI denied requests for shell and root users (they are in the log)
417 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
418 send_result(ctx, DENY);
420 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
421 fprintf(stderr, "%s\n", strerror(EACCES));
425 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
430 // No send to UI accepted requests for shell and root users (they are in the log)
431 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
432 send_result(ctx, ALLOW);
435 arg0 = strrchr (ctx->to.shell, '/');
436 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
438 int s = strlen(arg0) + 2;
449 populate_environment(ctx);
450 set_identity(ctx->to.uid);
453 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
454 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
456 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
457 ctx->from.uid, ctx->from.bin,
458 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
459 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
460 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
462 argc = ctx->to.optind;
463 if (ctx->to.command) {
464 ctx->to.argv[--argc] = ctx->to.command;
465 ctx->to.argv[--argc] = "-c";
467 ctx->to.argv[--argc] = arg0;
468 execv(ctx->to.shell, ctx->to.argv + argc);
471 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
476 * CyanogenMod-specific behavior
478 * we can't simply use the property service, since we aren't launched from init
479 * and can't trust the location of the property workspace.
480 * Find the properties ourselves.
482 int access_disabled(const struct su_initiator *from) {
484 char build_type[PROPERTY_VALUE_MAX];
485 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
488 data = read_file("/system/build.prop");
489 if (check_property(data, "ro.cm.version")) {
490 get_property(data, build_type, "ro.build.type", "");
493 data = read_file("/default.prop");
494 get_property(data, debuggable, "ro.debuggable", "0");
496 /* only allow su on debuggable builds */
497 if (strcmp("1", debuggable) != 0) {
498 LOGE("Root access is disabled on non-debug builds");
502 data = read_file("/data/property/persist.sys.root_access");
505 if (len >= PROPERTY_VALUE_MAX)
506 memcpy(enabled, "1", 2);
508 memcpy(enabled, data, len + 1);
511 memcpy(enabled, "1", 2);
513 /* enforce persist.sys.root_access on non-eng builds for apps */
514 if (strcmp("eng", build_type) != 0 &&
515 from->uid != AID_SHELL && from->uid != AID_ROOT &&
516 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
517 LOGE("Apps root access is disabled by system setting - "
518 "enable it under settings -> developer options");
522 /* disallow su in a shell if appropriate */
523 if (from->uid == AID_SHELL &&
524 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
525 LOGE("Shell root access is disabled by a system setting - "
526 "enable it under settings -> developer options");
534 int main(int argc, char *argv[]) {
535 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
536 /* The same list than GLibc at this point */
537 static const char* const unsec_vars[] = {
561 "LD_AOUT_LIBRARY_PATH",
563 // not listed in linker, used due to system() call
566 const char* const* cp = unsec_vars;
567 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
574 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
575 * This occurs on Android 4.0+
577 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
581 struct su_context ctx = {
593 .shell = DEFAULT_SHELL,
601 .android_user_id = 0,
602 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
603 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
604 .base_path = REQUESTOR_DATA_PATH REQUESTOR
608 int c, socket_serv_fd, fd;
609 char buf[64], *result;
611 struct option long_opts[] = {
612 { "command", required_argument, NULL, 'c' },
613 { "help", no_argument, NULL, 'h' },
614 { "login", no_argument, NULL, 'l' },
615 { "preserve-environment", no_argument, NULL, 'p' },
616 { "shell", required_argument, NULL, 's' },
617 { "version", no_argument, NULL, 'v' },
618 { NULL, 0, NULL, 0 },
621 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
624 ctx.to.command = optarg;
637 ctx.to.shell = optarg;
640 printf("%d\n", VERSION_CODE);
643 printf("%s\n", VERSION);
646 switch (get_multiuser_mode()) {
647 case MULTIUSER_MODE_USER:
648 printf("%s\n", MULTIUSER_VALUE_USER);
650 case MULTIUSER_MODE_OWNER_MANAGED:
651 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
653 case MULTIUSER_MODE_OWNER_ONLY:
654 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
656 case MULTIUSER_MODE_NONE:
657 printf("%s\n", MULTIUSER_VALUE_NONE);
662 /* Bionic getopt_long doesn't terminate its error output by newline */
663 fprintf(stderr, "\n");
667 if (optind < argc && !strcmp(argv[optind], "-")) {
671 /* username or uid */
672 if (optind < argc && strcmp(argv[optind], "--")) {
674 pw = getpwnam(argv[optind]);
678 /* It seems we shouldn't do this at all */
680 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
681 if (errno || *endptr) {
682 LOGE("Unknown id: %s\n", argv[optind]);
683 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
687 ctx.to.uid = pw->pw_uid;
689 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
693 if (optind < argc && !strcmp(argv[optind], "--")) {
696 ctx.to.optind = optind;
699 if (from_init(&ctx.from) < 0) {
706 // verify superuser is installed
707 if (stat(ctx.user.base_path, &st) < 0) {
709 if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
710 silent_run("am start -d market://details?id=" JAVA_PACKAGE_NAME);
711 PLOGE("stat %s", ctx.user.base_path);
715 // odd perms on superuser data dir
716 if (st.st_gid != st.st_uid) {
717 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
718 (int)st.st_uid, (int)st.st_gid);
722 // always allow if this is the superuser uid
723 // superuser needs to be able to reenable itself when disabled...
724 if (ctx.from.uid == st.st_uid) {
728 // check if superuser is disabled completely
729 if (access_disabled(&ctx.from)) {
730 LOGD("access_disabled");
734 // deny if this is a non owner request and owner mode only
735 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
739 ctx.umask = umask(027);
741 // TODO: customizable behavior for shell? It can currently be toggled via settings.
742 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL) {
743 LOGD("Allowing root/shell.");
747 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
748 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
749 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
753 if (setgroups(0, NULL)) {
757 if (setegid(st.st_gid)) {
758 PLOGE("setegid (%lu)", st.st_gid);
761 if (seteuid(st.st_uid)) {
762 PLOGE("seteuid (%lu)", st.st_uid);
766 dballow = database_check(&ctx);
772 allow(&ctx); /* never returns */
776 deny(&ctx); /* never returns too */
779 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
781 if (socket_serv_fd < 0) {
785 signal(SIGHUP, cleanup_signal);
786 signal(SIGPIPE, cleanup_signal);
787 signal(SIGTERM, cleanup_signal);
788 signal(SIGQUIT, cleanup_signal);
789 signal(SIGINT, cleanup_signal);
790 signal(SIGABRT, cleanup_signal);
792 if (send_request(&ctx) < 0) {
798 fd = socket_accept(socket_serv_fd);
802 if (socket_send_request(fd, &ctx)) {
805 if (socket_receive_result(fd, buf, sizeof(buf))) {
810 close(socket_serv_fd);
811 socket_cleanup(&ctx);
815 #define SOCKET_RESPONSE "socket:"
816 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
817 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
819 result += sizeof(SOCKET_RESPONSE) - 1;
821 if (!strcmp(result, "DENY")) {
823 } else if (!strcmp(result, "ALLOW")) {
826 LOGE("unknown response from Superuser Requestor: %s", result);