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>
41 struct passwd* ppwd = getpwnam("shell");
49 void exec_log(char *priority, char* logline) {
51 if ((pid = fork()) == 0) {
52 int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
54 int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
57 execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline);
62 void exec_loge(const char* fmt, ...) {
65 char logline[PATH_MAX];
67 vsnprintf(logline, PATH_MAX, fmt, args);
69 exec_log("e", logline);
72 void exec_logw(const char* fmt, ...) {
75 char logline[PATH_MAX];
77 vsnprintf(logline, PATH_MAX, fmt, args);
79 exec_log("w", logline);
82 void exec_logd(const char* fmt, ...) {
85 char logline[PATH_MAX];
87 vsnprintf(logline, PATH_MAX, fmt, args);
89 exec_log("d", logline);
92 static int from_init(struct su_initiator *from) {
93 char path[PATH_MAX], exe[PATH_MAX];
94 char args[4096], *argv0, *argv_rest;
100 from->uid = getuid();
101 from->pid = getppid();
103 /* Get the command line */
104 snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
105 fd = open(path, O_RDONLY);
107 PLOGE("Opening command line");
110 len = read(fd, args, sizeof(args));
113 if (len < 0 || len == sizeof(args)) {
114 PLOGEV("Reading command line", err);
120 for (i = 0; i < len; i++) {
121 if (args[i] == '\0') {
123 argv_rest = &args[i+1];
132 strncpy(from->args, argv_rest, sizeof(from->args));
133 from->args[sizeof(from->args)-1] = '\0';
135 from->args[0] = '\0';
138 /* If this isn't app_process, use the real path instead of argv[0] */
139 snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
140 len = readlink(path, exe, sizeof(exe));
142 PLOGE("Getting exe path");
146 if (strcmp(exe, "/system/bin/app_process")) {
150 strncpy(from->bin, argv0, sizeof(from->bin));
151 from->bin[sizeof(from->bin)-1] = '\0';
154 pw = getpwuid(from->uid);
155 if (pw && pw->pw_name) {
156 strncpy(from->name, pw->pw_name, sizeof(from->name));
162 static int get_multiuser_mode() {
164 char sdk_ver[PROPERTY_VALUE_MAX];
166 data = read_file("/system/build.prop");
167 get_property(data, sdk_ver, "ro.build.version.sdk", "0");
170 int sdk = atoi(sdk_ver);
172 return MULTIUSER_MODE_NONE;
174 int ret = MULTIUSER_MODE_OWNER_ONLY;
177 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
178 int last = strlen(mode) - 1;
179 if (mode[last] == '\n')
181 fgets(mode, sizeof(mode), fp);
182 LOGD("multiuser mode: %s", mode);
183 if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
184 ret = MULTIUSER_MODE_USER;
185 } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
186 ret = MULTIUSER_MODE_OWNER_MANAGED;
189 ret = MULTIUSER_MODE_OWNER_ONLY;
196 static void read_options(struct su_context *ctx) {
197 ctx->user.multiuser_mode = get_multiuser_mode();
200 static void user_init(struct su_context *ctx) {
201 if (ctx->from.uid > 99999) {
202 ctx->user.android_user_id = ctx->from.uid / 100000;
203 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
204 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
205 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
210 static void populate_environment(const struct su_context *ctx) {
216 pw = getpwuid(ctx->to.uid);
218 setenv("HOME", pw->pw_dir, 1);
219 setenv("SHELL", ctx->to.shell, 1);
220 if (ctx->to.login || ctx->to.uid) {
221 setenv("USER", pw->pw_name, 1);
222 setenv("LOGNAME", pw->pw_name, 1);
227 void set_identity(unsigned int uid) {
229 * Set effective uid back to root, otherwise setres[ug]id will fail
233 PLOGE("seteuid (root)");
236 if (setresgid(uid, uid, uid)) {
237 PLOGE("setresgid (%u)", uid);
240 if (setresuid(uid, uid, uid)) {
241 PLOGE("setresuid (%u)", uid);
246 static void socket_cleanup(struct su_context *ctx) {
247 if (ctx && ctx->sock_path[0]) {
248 if (unlink(ctx->sock_path))
249 PLOGE("unlink (%s)", ctx->sock_path);
250 ctx->sock_path[0] = 0;
255 * For use in signal handlers/atexit-function
256 * NOTE: su_ctx points to main's local variable.
257 * It's OK due to the program uses exit(3), not return from main()
259 static struct su_context *su_ctx = NULL;
261 static void cleanup(void) {
262 socket_cleanup(su_ctx);
265 static void cleanup_signal(int sig) {
266 socket_cleanup(su_ctx);
270 void sigchld_handler(int sig) {
271 child_cleanup(su_ctx);
275 static int socket_create_temp(char *path, size_t len) {
277 struct sockaddr_un sun;
279 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
284 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
285 PLOGE("fcntl FD_CLOEXEC");
289 memset(&sun, 0, sizeof(sun));
290 sun.sun_family = AF_LOCAL;
291 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
292 memset(sun.sun_path, 0, sizeof(sun.sun_path));
293 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
296 * Delete the socket to protect from situations when
297 * something bad occured previously and the kernel reused pid from that process.
298 * Small probability, isn't it.
300 unlink(sun.sun_path);
302 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
307 if (listen(fd, 1) < 0) {
318 static int socket_accept(int serv_fd) {
323 /* Wait 20 seconds for a connection, then give up. */
327 FD_SET(serv_fd, &fds);
330 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
331 } while (rc < 0 && errno == EINTR);
337 fd = accept(serv_fd, NULL, NULL);
346 static int socket_send_request(int fd, const struct su_context *ctx) {
347 #define write_data(fd, data, data_len) \
349 size_t __len = htonl(data_len); \
350 __len = write((fd), &__len, sizeof(__len)); \
351 if (__len != sizeof(__len)) { \
352 PLOGE("write(" #data ")"); \
355 __len = write((fd), data, data_len); \
356 if (__len != data_len) { \
357 PLOGE("write(" #data ")"); \
362 #define write_string(fd, name, data) \
364 write_data(fd, name, strlen(name)); \
365 write_data(fd, data, strlen(data)); \
368 // stringify everything.
369 #define write_token(fd, name, data) \
372 snprintf(buf, sizeof(buf), "%d", data); \
373 write_string(fd, name, buf); \
376 write_token(fd, "version", PROTO_VERSION);
377 write_token(fd, "pid", ctx->from.pid);
378 write_token(fd, "from.name", ctx->from.name);
379 write_token(fd, "to.name", ctx->to.name);
380 write_token(fd, "from.uid", ctx->from.uid);
381 write_token(fd, "to.uid", ctx->to.uid);
382 write_string(fd, "from.bin", ctx->from.bin);
383 write_string(fd, "command", get_command(&ctx->to));
384 write_token(fd, "eof", PROTO_VERSION);
388 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
391 LOGD("waiting for user");
392 len = read(fd, result, result_len-1);
394 PLOGE("read(result)");
402 static void usage(int status) {
403 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
406 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
408 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
409 " -h, --help display this help message and exit\n"
410 " -, -l, --login pretend the shell to be a login shell\n"
412 " --preserve-environment do not change environment variables\n"
413 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
414 " -u display the multiuser mode and exit\n"
415 " -v, --version display version number and exit\n"
416 " -V display version code and exit,\n"
417 " this is used almost exclusively by Superuser.apk\n");
421 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
422 char *cmd = get_command(&ctx->to);
424 // No send to UI denied requests for shell and root users (they are in the log)
425 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
426 send_result(ctx, DENY);
428 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
429 fprintf(stderr, "%s\n", strerror(EACCES));
433 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
438 // No send to UI accepted requests for shell and root users (they are in the log)
439 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
440 send_result(ctx, ALLOW);
443 arg0 = strrchr (ctx->to.shell, '/');
444 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
446 int s = strlen(arg0) + 2;
457 populate_environment(ctx);
458 set_identity(ctx->to.uid);
461 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
462 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
464 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
465 ctx->from.uid, ctx->from.bin,
466 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
467 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
468 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
470 argc = ctx->to.optind;
471 if (ctx->to.command) {
472 ctx->to.argv[--argc] = ctx->to.command;
473 ctx->to.argv[--argc] = "-c";
475 ctx->to.argv[--argc] = arg0;
476 execv(ctx->to.shell, ctx->to.argv + argc);
479 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
484 * CyanogenMod-specific behavior
486 * we can't simply use the property service, since we aren't launched from init
487 * and can't trust the location of the property workspace.
488 * Find the properties ourselves.
490 int access_disabled(const struct su_initiator *from) {
492 char build_type[PROPERTY_VALUE_MAX];
493 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
496 data = read_file("/system/build.prop");
497 if (check_property(data, "ro.cm.version")) {
498 get_property(data, build_type, "ro.build.type", "");
501 data = read_file("/default.prop");
502 get_property(data, debuggable, "ro.debuggable", "0");
504 /* only allow su on debuggable builds */
505 if (strcmp("1", debuggable) != 0) {
506 LOGE("Root access is disabled on non-debug builds");
510 data = read_file("/data/property/persist.sys.root_access");
513 if (len >= PROPERTY_VALUE_MAX)
514 memcpy(enabled, "1", 2);
516 memcpy(enabled, data, len + 1);
519 memcpy(enabled, "1", 2);
521 /* enforce persist.sys.root_access on non-eng builds for apps */
522 if (strcmp("eng", build_type) != 0 &&
523 from->uid != AID_SHELL && from->uid != AID_ROOT &&
524 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
525 LOGE("Apps root access is disabled by system setting - "
526 "enable it under settings -> developer options");
530 /* disallow su in a shell if appropriate */
531 if (from->uid == AID_SHELL &&
532 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
533 LOGE("Shell root access is disabled by a system setting - "
534 "enable it under settings -> developer options");
542 int main(int argc, char *argv[]) {
543 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
544 /* The same list than GLibc at this point */
545 static const char* const unsec_vars[] = {
569 "LD_AOUT_LIBRARY_PATH",
571 // not listed in linker, used due to system() call
574 const char* const* cp = unsec_vars;
575 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
582 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
583 * This occurs on Android 4.0+
585 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
589 struct su_context ctx = {
601 .shell = DEFAULT_SHELL,
609 .android_user_id = 0,
610 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
611 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
612 .base_path = REQUESTOR_DATA_PATH REQUESTOR
616 int c, socket_serv_fd, fd;
617 char buf[64], *result;
619 struct option long_opts[] = {
620 { "command", required_argument, NULL, 'c' },
621 { "help", no_argument, NULL, 'h' },
622 { "login", no_argument, NULL, 'l' },
623 { "preserve-environment", no_argument, NULL, 'p' },
624 { "shell", required_argument, NULL, 's' },
625 { "version", no_argument, NULL, 'v' },
626 { NULL, 0, NULL, 0 },
629 while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
632 ctx.to.command = optarg;
645 ctx.to.shell = optarg;
648 printf("%d\n", VERSION_CODE);
651 printf("%s\n", VERSION);
654 switch (get_multiuser_mode()) {
655 case MULTIUSER_MODE_USER:
656 printf("%s\n", MULTIUSER_VALUE_USER);
658 case MULTIUSER_MODE_OWNER_MANAGED:
659 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
661 case MULTIUSER_MODE_OWNER_ONLY:
662 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
664 case MULTIUSER_MODE_NONE:
665 printf("%s\n", MULTIUSER_VALUE_NONE);
670 /* Bionic getopt_long doesn't terminate its error output by newline */
671 fprintf(stderr, "\n");
675 if (optind < argc && !strcmp(argv[optind], "-")) {
679 /* username or uid */
680 if (optind < argc && strcmp(argv[optind], "--")) {
682 pw = getpwnam(argv[optind]);
686 /* It seems we shouldn't do this at all */
688 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
689 if (errno || *endptr) {
690 LOGE("Unknown id: %s\n", argv[optind]);
691 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
695 ctx.to.uid = pw->pw_uid;
697 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
701 if (optind < argc && !strcmp(argv[optind], "--")) {
704 ctx.to.optind = optind;
707 if (from_init(&ctx.from) < 0) {
714 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
718 if (access_disabled(&ctx.from)) {
719 LOGD("access_disabled");
723 ctx.umask = umask(027);
725 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL) {
726 LOGD("Allowing root/shell.");
730 if (stat(ctx.user.base_path, &st) < 0) {
731 PLOGE("stat %s", ctx.user.base_path);
735 if (st.st_gid != st.st_uid) {
736 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
737 (int)st.st_uid, (int)st.st_gid);
741 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
742 LOGD("mkdir: %d", ret);
743 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
744 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
748 if (setgroups(0, NULL)) {
752 if (setegid(st.st_gid)) {
753 PLOGE("setegid (%lu)", st.st_gid);
756 if (seteuid(st.st_uid)) {
757 PLOGE("seteuid (%lu)", st.st_uid);
761 dballow = database_check(&ctx);
767 allow(&ctx); /* never returns */
771 deny(&ctx); /* never returns too */
774 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
776 if (socket_serv_fd < 0) {
780 signal(SIGHUP, cleanup_signal);
781 signal(SIGPIPE, cleanup_signal);
782 signal(SIGTERM, cleanup_signal);
783 signal(SIGQUIT, cleanup_signal);
784 signal(SIGINT, cleanup_signal);
785 signal(SIGABRT, cleanup_signal);
787 if (send_request(&ctx) < 0) {
793 fd = socket_accept(socket_serv_fd);
797 if (socket_send_request(fd, &ctx)) {
800 if (socket_receive_result(fd, buf, sizeof(buf))) {
805 close(socket_serv_fd);
806 socket_cleanup(&ctx);
810 #define SOCKET_RESPONSE "socket:"
811 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
812 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
814 result += sizeof(SOCKET_RESPONSE) - 1;
816 if (!strcmp(result, "DENY")) {
818 } else if (!strcmp(result, "ALLOW")) {
821 LOGE("unknown response from Superuser Requestor: %s", result);