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 void read_options(struct su_context *ctx) {
165 if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
166 fgets(mode, sizeof(mode), fp);
167 LOGD("multiuser mode: %s", mode);
168 if (strcmp(mode, "user\n") == 0) {
169 ctx->user.multiuser_mode = MULTIUSER_MODE_USER;
170 } else if (strcmp(mode, "owner\n") == 0) {
171 ctx->user.multiuser_mode = MULTIUSER_MODE_OWNER;
177 static void user_init(struct su_context *ctx) {
178 if (ctx->from.uid > 99999) {
179 ctx->user.android_user_id = ctx->from.uid / 100000;
180 if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
181 snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
182 snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
187 static void populate_environment(const struct su_context *ctx) {
193 pw = getpwuid(ctx->to.uid);
195 setenv("HOME", pw->pw_dir, 1);
196 setenv("SHELL", ctx->to.shell, 1);
197 if (ctx->to.login || ctx->to.uid) {
198 setenv("USER", pw->pw_name, 1);
199 setenv("LOGNAME", pw->pw_name, 1);
204 void set_identity(unsigned int uid) {
206 * Set effective uid back to root, otherwise setres[ug]id will fail
210 PLOGE("seteuid (root)");
213 if (setresgid(uid, uid, uid)) {
214 PLOGE("setresgid (%u)", uid);
217 if (setresuid(uid, uid, uid)) {
218 PLOGE("setresuid (%u)", uid);
223 static void socket_cleanup(struct su_context *ctx) {
224 if (ctx && ctx->sock_path[0]) {
225 if (unlink(ctx->sock_path))
226 PLOGE("unlink (%s)", ctx->sock_path);
227 ctx->sock_path[0] = 0;
232 * For use in signal handlers/atexit-function
233 * NOTE: su_ctx points to main's local variable.
234 * It's OK due to the program uses exit(3), not return from main()
236 static struct su_context *su_ctx = NULL;
238 static void cleanup(void) {
239 socket_cleanup(su_ctx);
242 static void cleanup_signal(int sig) {
243 socket_cleanup(su_ctx);
247 void sigchld_handler(int sig) {
248 child_cleanup(su_ctx);
252 static int socket_create_temp(char *path, size_t len) {
254 struct sockaddr_un sun;
256 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
261 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
262 PLOGE("fcntl FD_CLOEXEC");
266 memset(&sun, 0, sizeof(sun));
267 sun.sun_family = AF_LOCAL;
268 snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
269 memset(sun.sun_path, 0, sizeof(sun.sun_path));
270 snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
273 * Delete the socket to protect from situations when
274 * something bad occured previously and the kernel reused pid from that process.
275 * Small probability, isn't it.
277 unlink(sun.sun_path);
279 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
284 if (listen(fd, 1) < 0) {
295 static int socket_accept(int serv_fd) {
300 /* Wait 20 seconds for a connection, then give up. */
304 FD_SET(serv_fd, &fds);
307 rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
308 } while (rc < 0 && errno == EINTR);
314 fd = accept(serv_fd, NULL, NULL);
323 static int socket_send_request(int fd, const struct su_context *ctx) {
324 #define write_data(fd, data, data_len) \
326 size_t __len = htonl(data_len); \
327 __len = write((fd), &__len, sizeof(__len)); \
328 if (__len != sizeof(__len)) { \
329 PLOGE("write(" #data ")"); \
332 __len = write((fd), data, data_len); \
333 if (__len != data_len) { \
334 PLOGE("write(" #data ")"); \
339 #define write_string(fd, name, data) \
341 write_data(fd, name, strlen(name)); \
342 write_data(fd, data, strlen(data)); \
345 // stringify everything.
346 #define write_token(fd, name, data) \
349 snprintf(buf, sizeof(buf), "%d", data); \
350 write_string(fd, name, buf); \
353 write_token(fd, "version", PROTO_VERSION);
354 write_token(fd, "from.name", ctx->from.name);
355 write_token(fd, "to.name", ctx->to.name);
356 write_token(fd, "from.uid", ctx->from.uid);
357 write_token(fd, "to.uid", ctx->to.uid);
358 write_string(fd, "from.bin", ctx->from.bin);
359 write_string(fd, "command", get_command(&ctx->to));
360 write_token(fd, "eof", PROTO_VERSION);
364 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
367 LOGD("waiting for user");
368 len = read(fd, result, result_len-1);
370 PLOGE("read(result)");
378 static void usage(int status) {
379 FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
382 "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
384 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
385 " -h, --help display this help message and exit\n"
386 " -, -l, --login pretend the shell to be a login shell\n"
388 " --preserve-environment do not change environment variables\n"
389 " -s, --shell SHELL use SHELL instead of the default " DEFAULT_SHELL "\n"
390 " -v, --version display version number and exit\n"
391 " -V display version code and exit,\n"
392 " this is used almost exclusively by Superuser.apk\n");
396 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
397 char *cmd = get_command(&ctx->to);
399 // No send to UI denied requests for shell and root users (they are in the log)
400 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
401 send_result(ctx, DENY);
403 LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
404 fprintf(stderr, "%s\n", strerror(EACCES));
408 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
413 // No send to UI accepted requests for shell and root users (they are in the log)
414 // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
415 send_result(ctx, ALLOW);
418 arg0 = strrchr (ctx->to.shell, '/');
419 arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
421 int s = strlen(arg0) + 2;
432 populate_environment(ctx);
433 set_identity(ctx->to.uid);
436 (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "", \
437 (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
439 LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
440 ctx->from.uid, ctx->from.bin,
441 ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
442 arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
443 (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
445 argc = ctx->to.optind;
446 if (ctx->to.command) {
447 ctx->to.argv[--argc] = ctx->to.command;
448 ctx->to.argv[--argc] = "-c";
450 ctx->to.argv[--argc] = arg0;
451 execv(ctx->to.shell, ctx->to.argv + argc);
454 fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
459 * CyanogenMod-specific behavior
461 * we can't simply use the property service, since we aren't launched from init
462 * and can't trust the location of the property workspace.
463 * Find the properties ourselves.
465 int access_disabled(const struct su_initiator *from) {
467 char build_type[PROPERTY_VALUE_MAX];
468 char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
471 data = read_file("/system/build.prop");
472 if (check_property(data, "ro.cm.version")) {
473 get_property(data, build_type, "ro.build.type", "");
476 data = read_file("/default.prop");
477 get_property(data, debuggable, "ro.debuggable", "0");
479 /* only allow su on debuggable builds */
480 if (strcmp("1", debuggable) != 0) {
481 LOGE("Root access is disabled on non-debug builds");
485 data = read_file("/data/property/persist.sys.root_access");
488 if (len >= PROPERTY_VALUE_MAX)
489 memcpy(enabled, "1", 2);
491 memcpy(enabled, data, len + 1);
494 memcpy(enabled, "1", 2);
496 /* enforce persist.sys.root_access on non-eng builds for apps */
497 if (strcmp("eng", build_type) != 0 &&
498 from->uid != AID_SHELL && from->uid != AID_ROOT &&
499 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
500 LOGE("Apps root access is disabled by system setting - "
501 "enable it under settings -> developer options");
505 /* disallow su in a shell if appropriate */
506 if (from->uid == AID_SHELL &&
507 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
508 LOGE("Shell root access is disabled by a system setting - "
509 "enable it under settings -> developer options");
517 int main(int argc, char *argv[]) {
518 // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
519 /* The same list than GLibc at this point */
520 static const char* const unsec_vars[] = {
544 "LD_AOUT_LIBRARY_PATH",
546 // not listed in linker, used due to system() call
549 const char* const* cp = unsec_vars;
550 const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
557 * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
558 * This occurs on Android 4.0+
560 setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
564 struct su_context ctx = {
576 .shell = DEFAULT_SHELL,
584 .android_user_id = 0,
585 .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
586 .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
587 .base_path = REQUESTOR_DATA_PATH REQUESTOR
591 int c, socket_serv_fd, fd;
592 char buf[64], *result;
594 struct option long_opts[] = {
595 { "command", required_argument, NULL, 'c' },
596 { "help", no_argument, NULL, 'h' },
597 { "login", no_argument, NULL, 'l' },
598 { "preserve-environment", no_argument, NULL, 'p' },
599 { "shell", required_argument, NULL, 's' },
600 { "version", no_argument, NULL, 'v' },
601 { NULL, 0, NULL, 0 },
604 while ((c = getopt_long(argc, argv, "+c:hlmps:Vv", long_opts, NULL)) != -1) {
607 ctx.to.command = optarg;
620 ctx.to.shell = optarg;
623 printf("%d\n", VERSION_CODE);
626 printf("%s\n", VERSION);
629 /* Bionic getopt_long doesn't terminate its error output by newline */
630 fprintf(stderr, "\n");
634 if (optind < argc && !strcmp(argv[optind], "-")) {
638 /* username or uid */
639 if (optind < argc && strcmp(argv[optind], "--")) {
641 pw = getpwnam(argv[optind]);
645 /* It seems we shouldn't do this at all */
647 ctx.to.uid = strtoul(argv[optind], &endptr, 10);
648 if (errno || *endptr) {
649 LOGE("Unknown id: %s\n", argv[optind]);
650 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
654 ctx.to.uid = pw->pw_uid;
656 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
660 if (optind < argc && !strcmp(argv[optind], "--")) {
663 ctx.to.optind = optind;
666 if (from_init(&ctx.from) < 0) {
673 if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
674 LOGD("multiuser mode: owner only");
678 if (access_disabled(&ctx.from)) {
679 LOGD("access_disabled");
683 ctx.umask = umask(027);
685 if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL) {
686 LOGD("Allowing root/shell.");
690 if (stat(ctx.user.base_path, &st) < 0) {
691 PLOGE("stat %s", ctx.user.base_path);
695 if (st.st_gid != st.st_uid) {
696 LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
697 (int)st.st_uid, (int)st.st_gid);
701 int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
702 LOGD("mkdir: %d", ret);
703 if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
704 PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
708 if (setgroups(0, NULL)) {
712 if (setegid(st.st_gid)) {
713 PLOGE("setegid (%lu)", st.st_gid);
716 if (seteuid(st.st_uid)) {
717 PLOGE("seteuid (%lu)", st.st_uid);
721 dballow = database_check(&ctx);
727 allow(&ctx); /* never returns */
731 deny(&ctx); /* never returns too */
734 socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
736 if (socket_serv_fd < 0) {
740 signal(SIGHUP, cleanup_signal);
741 signal(SIGPIPE, cleanup_signal);
742 signal(SIGTERM, cleanup_signal);
743 signal(SIGQUIT, cleanup_signal);
744 signal(SIGINT, cleanup_signal);
745 signal(SIGABRT, cleanup_signal);
747 if (send_request(&ctx) < 0) {
753 fd = socket_accept(socket_serv_fd);
757 if (socket_send_request(fd, &ctx)) {
760 if (socket_receive_result(fd, buf, sizeof(buf))) {
765 close(socket_serv_fd);
766 socket_cleanup(&ctx);
770 #define SOCKET_RESPONSE "socket:"
771 if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
772 LOGW("SECURITY RISK: Requestor still receives credentials in intent");
774 result += sizeof(SOCKET_RESPONSE) - 1;
776 if (!strcmp(result, "DENY")) {
778 } else if (!strcmp(result, "ALLOW")) {
781 LOGE("unknown response from Superuser Requestor: %s", result);