OSDN Git Service

Merge remote-tracking branch 'koush/master' into cm-11.0
[android-x86/external-koush-Superuser.git] / Superuser / jni / su / su.c
1 /*
2 ** Copyright 2010, Adam Shanks (@ChainsDD)
3 ** Copyright 2008, Zinx Verituse (@zinxv)
4 **
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
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
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.
16 */
17
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/uio.h>
21 #include <sys/un.h>
22 #include <sys/wait.h>
23 #include <sys/select.h>
24 #include <sys/time.h>
25 #include <unistd.h>
26 #include <limits.h>
27 #include <fcntl.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <getopt.h>
31 #include <stdint.h>
32 #include <pwd.h>
33 #include <sys/stat.h>
34 #include <stdarg.h>
35 #include <sys/types.h>
36
37 #include "su.h"
38 #include "utils.h"
39
40 extern int is_daemon;
41 extern int daemon_from_uid;
42 extern int daemon_from_pid;
43
44 unsigned get_shell_uid() {
45   struct passwd* ppwd = getpwnam("shell");
46   if (NULL == ppwd) {
47     return 2000;
48   }
49
50   return ppwd->pw_uid;
51 }
52
53 unsigned get_system_uid() {
54   struct passwd* ppwd = getpwnam("system");
55   if (NULL == ppwd) {
56     return 1000;
57   }
58
59   return ppwd->pw_uid;
60 }
61
62 unsigned get_radio_uid() {
63   struct passwd* ppwd = getpwnam("radio");
64   if (NULL == ppwd) {
65     return 1001;
66   }
67
68   return ppwd->pw_uid;
69 }
70
71 int fork_zero_fucks() {
72     int pid = fork();
73     if (pid) {
74         int status;
75         waitpid(pid, &status, 0);
76         return pid;
77     }
78     else {
79         if (pid = fork())
80             exit(0);
81         return 0;
82     }
83 }
84
85 void exec_log(int priority, const char* fmt, ...) {
86     static int log_fd = -1;
87     struct iovec vec[3];
88     va_list args;
89     char msg[PATH_MAX];
90
91     if (log_fd < 0) {
92         log_fd = open("/dev/log/main", O_WRONLY);
93         if (log_fd < 0) {
94             return;
95         }
96     }
97
98     va_start(args, fmt);
99     vsnprintf(msg, PATH_MAX, fmt, args);
100     va_end(args);
101
102     vec[0].iov_base   = (unsigned char *) &priority;
103     vec[0].iov_len    = 1;
104     vec[1].iov_base   = (void *) LOG_TAG;
105     vec[1].iov_len    = strlen(LOG_TAG) + 1;
106     vec[2].iov_base   = (void *) msg;
107     vec[2].iov_len    = strlen(msg) + 1;
108
109     writev(log_fd, vec, 3);
110 }
111
112 static int from_init(struct su_initiator *from) {
113     char path[PATH_MAX], exe[PATH_MAX];
114     char args[4096], *argv0, *argv_rest;
115     int fd;
116     ssize_t len;
117     int i;
118     int err;
119
120     from->uid = getuid();
121     from->pid = getppid();
122
123     /* Get the command line */
124     snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
125     fd = open(path, O_RDONLY);
126     if (fd < 0) {
127         PLOGE("Opening command line");
128         return -1;
129     }
130     len = read(fd, args, sizeof(args));
131     err = errno;
132     close(fd);
133     if (len < 0 || len == sizeof(args)) {
134         PLOGEV("Reading command line", err);
135         return -1;
136     }
137
138     argv0 = args;
139     argv_rest = NULL;
140     for (i = 0; i < len; i++) {
141         if (args[i] == '\0') {
142             if (!argv_rest) {
143                 argv_rest = &args[i+1];
144             } else {
145                 args[i] = ' ';
146             }
147         }
148     }
149     args[len] = '\0';
150
151     if (argv_rest) {
152         strncpy(from->args, argv_rest, sizeof(from->args));
153         from->args[sizeof(from->args)-1] = '\0';
154     } else {
155         from->args[0] = '\0';
156     }
157
158     /* If this isn't app_process, use the real path instead of argv[0] */
159     snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
160     len = readlink(path, exe, sizeof(exe));
161     if (len < 0) {
162         PLOGE("Getting exe path");
163         return -1;
164     }
165     exe[len] = '\0';
166     if (strcmp(exe, "/system/bin/app_process")) {
167         argv0 = exe;
168     }
169
170     strncpy(from->bin, argv0, sizeof(from->bin));
171     from->bin[sizeof(from->bin)-1] = '\0';
172
173     struct passwd *pw;
174     pw = getpwuid(from->uid);
175     if (pw && pw->pw_name) {
176         strncpy(from->name, pw->pw_name, sizeof(from->name));
177     }
178
179     if (is_daemon) {
180         from->uid = daemon_from_uid;
181         from->pid = daemon_from_pid;
182     }
183
184     return 0;
185 }
186
187 static int get_multiuser_mode() {
188     char *data;
189     char sdk_ver[PROPERTY_VALUE_MAX];
190
191     data = read_file("/system/build.prop");
192     get_property(data, sdk_ver, "ro.build.version.sdk", "0");
193     free(data);
194
195     int sdk = atoi(sdk_ver);
196     if (sdk < 17)
197         return MULTIUSER_MODE_NONE;
198
199     int ret = MULTIUSER_MODE_OWNER_ONLY;
200     char mode[12];
201     FILE *fp;
202     if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
203         fgets(mode, sizeof(mode), fp);
204         int last = strlen(mode) - 1;
205         if (mode[last] == '\n')
206             mode[last] = '\0';
207         if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
208             ret = MULTIUSER_MODE_USER;
209         } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
210             ret = MULTIUSER_MODE_OWNER_MANAGED;
211         }
212         else {
213             ret = MULTIUSER_MODE_OWNER_ONLY;
214         }
215         fclose(fp);
216     }
217     return ret;
218 }
219
220 static void read_options(struct su_context *ctx) {
221     ctx->user.multiuser_mode = get_multiuser_mode();
222 }
223
224 static void user_init(struct su_context *ctx) {
225     if (ctx->from.uid > 99999) {
226         ctx->user.android_user_id = ctx->from.uid / 100000;
227         if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
228             snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
229             snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
230         }
231     }
232 }
233
234 static void populate_environment(const struct su_context *ctx) {
235     struct passwd *pw;
236
237     if (ctx->to.keepenv)
238         return;
239
240     pw = getpwuid(ctx->to.uid);
241     if (pw) {
242         setenv("HOME", pw->pw_dir, 1);
243         if (ctx->to.shell)
244             setenv("SHELL", ctx->to.shell, 1);
245         else
246             setenv("SHELL", DEFAULT_SHELL, 1);
247         if (ctx->to.login || ctx->to.uid) {
248             setenv("USER", pw->pw_name, 1);
249             setenv("LOGNAME", pw->pw_name, 1);
250         }
251     }
252 }
253
254 void set_identity(unsigned int uid) {
255     /*
256      * Set effective uid back to root, otherwise setres[ug]id will fail
257      * if uid isn't root.
258      */
259     if (seteuid(0)) {
260         PLOGE("seteuid (root)");
261         exit(EXIT_FAILURE);
262     }
263     if (setresgid(uid, uid, uid)) {
264         PLOGE("setresgid (%u)", uid);
265         exit(EXIT_FAILURE);
266     }
267     if (setresuid(uid, uid, uid)) {
268         PLOGE("setresuid (%u)", uid);
269         exit(EXIT_FAILURE);
270     }
271 }
272
273 static void socket_cleanup(struct su_context *ctx) {
274     if (ctx && ctx->sock_path[0]) {
275         if (unlink(ctx->sock_path))
276             PLOGE("unlink (%s)", ctx->sock_path);
277         ctx->sock_path[0] = 0;
278     }
279 }
280
281 /*
282  * For use in signal handlers/atexit-function
283  * NOTE: su_ctx points to main's local variable.
284  *       It's OK due to the program uses exit(3), not return from main()
285  */
286 static struct su_context *su_ctx = NULL;
287
288 static void cleanup(void) {
289     socket_cleanup(su_ctx);
290 }
291
292 static void cleanup_signal(int sig) {
293     socket_cleanup(su_ctx);
294     exit(128 + sig);
295 }
296
297 static int socket_create_temp(char *path, size_t len) {
298     int fd;
299     struct sockaddr_un sun;
300
301     fd = socket(AF_LOCAL, SOCK_STREAM, 0);
302     if (fd < 0) {
303         PLOGE("socket");
304         return -1;
305     }
306     if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
307         PLOGE("fcntl FD_CLOEXEC");
308         goto err;
309     }
310
311     memset(&sun, 0, sizeof(sun));
312     sun.sun_family = AF_LOCAL;
313     snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
314     memset(sun.sun_path, 0, sizeof(sun.sun_path));
315     snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
316
317     /*
318      * Delete the socket to protect from situations when
319      * something bad occured previously and the kernel reused pid from that process.
320      * Small probability, isn't it.
321      */
322     unlink(sun.sun_path);
323
324     if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
325         PLOGE("bind");
326         goto err;
327     }
328
329     if (listen(fd, 1) < 0) {
330         PLOGE("listen");
331         goto err;
332     }
333
334     return fd;
335 err:
336     close(fd);
337     return -1;
338 }
339
340 static int socket_accept(int serv_fd) {
341     struct timeval tv;
342     fd_set fds;
343     int fd, rc;
344
345     /* Wait 20 seconds for a connection, then give up. */
346     tv.tv_sec = 20;
347     tv.tv_usec = 0;
348     FD_ZERO(&fds);
349     FD_SET(serv_fd, &fds);
350     do {
351         rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
352     } while (rc < 0 && errno == EINTR);
353     if (rc < 1) {
354         PLOGE("select");
355         return -1;
356     }
357
358     fd = accept(serv_fd, NULL, NULL);
359     if (fd < 0) {
360         PLOGE("accept");
361         return -1;
362     }
363
364     return fd;
365 }
366
367 static int socket_send_request(int fd, const struct su_context *ctx) {
368 #define write_data(fd, data, data_len)              \
369 do {                                                \
370     size_t __len = htonl(data_len);                 \
371     __len = write((fd), &__len, sizeof(__len));     \
372     if (__len != sizeof(__len)) {                   \
373         PLOGE("write(" #data ")");                  \
374         return -1;                                  \
375     }                                               \
376     __len = write((fd), data, data_len);            \
377     if (__len != data_len) {                        \
378         PLOGE("write(" #data ")");                  \
379         return -1;                                  \
380     }                                               \
381 } while (0)
382
383 #define write_string_data(fd, name, data)        \
384 do {                                        \
385     write_data(fd, name, strlen(name));     \
386     write_data(fd, data, strlen(data));     \
387 } while (0)
388
389 // stringify everything.
390 #define write_token(fd, name, data)         \
391 do {                                        \
392     char buf[16];                           \
393     snprintf(buf, sizeof(buf), "%d", data); \
394     write_string_data(fd, name, buf);            \
395 } while (0)
396
397     write_token(fd, "version", PROTO_VERSION);
398     write_token(fd, "binary.version", VERSION_CODE);
399     write_token(fd, "pid", ctx->from.pid);
400     write_string_data(fd, "from.name", ctx->from.name);
401     write_string_data(fd, "to.name", ctx->to.name);
402     write_token(fd, "from.uid", ctx->from.uid);
403     write_token(fd, "to.uid", ctx->to.uid);
404     write_string_data(fd, "from.bin", ctx->from.bin);
405     // TODO: Fix issue where not using -c does not result a in a command
406     write_string_data(fd, "command", get_command(&ctx->to));
407     write_token(fd, "eof", PROTO_VERSION);
408     return 0;
409 }
410
411 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
412     ssize_t len;
413
414     LOGV("waiting for user");
415     len = read(fd, result, result_len-1);
416     if (len < 0) {
417         PLOGE("read(result)");
418         return -1;
419     }
420     result[len] = '\0';
421
422     return 0;
423 }
424
425 static void usage(int status) {
426     FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
427
428     fprintf(stream,
429     "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
430     "Options:\n"
431     "  --daemon                      start the su daemon agent\n"
432     "  -c, --command COMMAND         pass COMMAND to the invoked shell\n"
433     "  -h, --help                    display this help message and exit\n"
434     "  -, -l, --login                pretend the shell to be a login shell\n"
435     "  -m, -p,\n"
436     "  --preserve-environment        do not change environment variables\n"
437     "  -s, --shell SHELL             use SHELL instead of the default " DEFAULT_SHELL "\n"
438     "  -u                            display the multiuser mode and exit\n"
439     "  -v, --version                 display version number and exit\n"
440     "  -V                            display version code and exit,\n"
441     "                                this is used almost exclusively by Superuser.apk\n");
442     exit(status);
443 }
444
445 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
446     char *cmd = get_command(&ctx->to);
447
448     int send_to_app = 1;
449
450     // no need to log if called by root
451     if (ctx->from.uid == AID_ROOT)
452         send_to_app = 0;
453
454     // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
455     if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
456         send_to_app = 0;
457
458     if (send_to_app)
459         send_result(ctx, DENY);
460
461     LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
462     fprintf(stderr, "%s\n", strerror(EACCES));
463     exit(EXIT_FAILURE);
464 }
465
466 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
467     char *arg0;
468     int argc, err;
469
470     umask(ctx->umask);
471     int send_to_app = 1;
472
473     // no need to log if called by root
474     if (ctx->from.uid == AID_ROOT)
475         send_to_app = 0;
476
477     // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
478     if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
479         send_to_app = 0;
480
481     if (send_to_app)
482         send_result(ctx, ALLOW);
483
484     char *binary;
485     argc = ctx->to.optind;
486     if (ctx->to.command) {
487         binary = ctx->to.shell;
488         ctx->to.argv[--argc] = ctx->to.command;
489         ctx->to.argv[--argc] = "-c";
490     }
491     else if (ctx->to.shell) {
492         binary = ctx->to.shell;
493     }
494     else {
495         if (ctx->to.argv[argc]) {
496             binary = ctx->to.argv[argc++];
497         }
498         else {
499             binary = DEFAULT_SHELL;
500         }
501     }
502
503     arg0 = strrchr (binary, '/');
504     arg0 = (arg0) ? arg0 + 1 : binary;
505     if (ctx->to.login) {
506         int s = strlen(arg0) + 2;
507         char *p = malloc(s);
508
509         if (!p)
510             exit(EXIT_FAILURE);
511
512         *p = '-';
513         strcpy(p + 1, arg0);
514         arg0 = p;
515     }
516
517     populate_environment(ctx);
518     set_identity(ctx->to.uid);
519
520 #define PARG(arg)                                    \
521     (argc + (arg) < ctx->to.argc) ? " " : "",                    \
522     (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
523
524     LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
525             ctx->from.uid, ctx->from.bin,
526             ctx->to.uid, get_command(&ctx->to), binary,
527             arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
528             (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
529
530     ctx->to.argv[--argc] = arg0;
531     execvp(binary, ctx->to.argv + argc);
532     err = errno;
533     PLOGE("exec");
534     fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
535     exit(EXIT_FAILURE);
536 }
537
538 /*
539  * CyanogenMod-specific behavior
540  *
541  * we can't simply use the property service, since we aren't launched from init
542  * and can't trust the location of the property workspace.
543  * Find the properties ourselves.
544  */
545 int access_disabled(const struct su_initiator *from) {
546 #ifndef SUPERUSER_EMBEDDED
547     return 0;
548 #else
549     char *data;
550     char build_type[PROPERTY_VALUE_MAX];
551     char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
552     size_t len;
553
554     data = read_file("/system/build.prop");
555     if (check_property(data, "ro.cm.version")) {
556         get_property(data, build_type, "ro.build.type", "");
557         free(data);
558
559         data = read_file("/default.prop");
560         get_property(data, debuggable, "ro.debuggable", "0");
561         free(data);
562         /* only allow su on debuggable builds */
563         if (strcmp("1", debuggable) != 0) {
564             LOGE("Root access is disabled on non-debug builds");
565             return 1;
566         }
567
568         data = read_file("/data/property/persist.sys.root_access");
569         if (data != NULL) {
570             len = strlen(data);
571             if (len >= PROPERTY_VALUE_MAX)
572                 memcpy(enabled, "1", 2);
573             else
574                 memcpy(enabled, data, len + 1);
575             free(data);
576         } else
577             memcpy(enabled, "1", 2);
578
579         /* enforce persist.sys.root_access on non-eng builds for apps */
580         if (strcmp("eng", build_type) != 0 &&
581                 from->uid != AID_SHELL && from->uid != AID_ROOT &&
582                 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
583             LOGE("Apps root access is disabled by system setting - "
584                  "enable it under settings -> developer options");
585             return 1;
586         }
587
588         /* disallow su in a shell if appropriate */
589         if (from->uid == AID_SHELL &&
590                 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
591             LOGE("Shell root access is disabled by a system setting - "
592                  "enable it under settings -> developer options");
593             return 1;
594         }
595
596     }
597     return 0;
598 #endif
599 }
600
601 static int get_api_version() {
602   char sdk_ver[PROPERTY_VALUE_MAX];
603   char *data = read_file("/system/build.prop");
604   get_property(data, sdk_ver, "ro.build.version.sdk", "0");
605   int ver = atoi(sdk_ver);
606   free(data);
607   return ver;
608 }
609
610 int main(int argc, char *argv[]) {
611     return su_main(argc, argv, 1);
612 }
613
614 int su_main(int argc, char *argv[], int need_client) {
615     // start up in daemon mode if prompted
616     if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
617         return run_daemon();
618     }
619
620     // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
621     /* The same list than GLibc at this point */
622     static const char* const unsec_vars[] = {
623         "GCONV_PATH",
624         "GETCONF_DIR",
625         "HOSTALIASES",
626         "LD_AUDIT",
627         "LD_DEBUG",
628         "LD_DEBUG_OUTPUT",
629         "LD_DYNAMIC_WEAK",
630         "LD_LIBRARY_PATH",
631         "LD_ORIGIN_PATH",
632         "LD_PRELOAD",
633         "LD_PROFILE",
634         "LD_SHOW_AUXV",
635         "LD_USE_LOAD_BIAS",
636         "LOCALDOMAIN",
637         "LOCPATH",
638         "MALLOC_TRACE",
639         "MALLOC_CHECK_",
640         "NIS_PATH",
641         "NLSPATH",
642         "RESOLV_HOST_CONF",
643         "RES_OPTIONS",
644         "TMPDIR",
645         "TZDIR",
646         "LD_AOUT_LIBRARY_PATH",
647         "LD_AOUT_PRELOAD",
648         // not listed in linker, used due to system() call
649         "IFS",
650     };
651     const char* const* cp   = unsec_vars;
652     const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
653     while (cp < endp) {
654         unsetenv(*cp);
655         cp++;
656     }
657
658     /*
659      * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
660      * This occurs on Android 4.0+
661      */
662     setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
663
664     LOGD("su invoked.");
665
666     struct su_context ctx = {
667         .from = {
668             .pid = -1,
669             .uid = 0,
670             .bin = "",
671             .args = "",
672             .name = "",
673         },
674         .to = {
675             .uid = AID_ROOT,
676             .login = 0,
677             .keepenv = 0,
678             .shell = NULL,
679             .command = NULL,
680             .argv = argv,
681             .argc = argc,
682             .optind = 0,
683             .name = "",
684         },
685         .user = {
686             .android_user_id = 0,
687             .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
688             .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
689             .base_path = REQUESTOR_DATA_PATH REQUESTOR
690         },
691     };
692     struct stat st;
693     int c, socket_serv_fd, fd;
694     char buf[64], *result;
695     policy_t dballow;
696     struct option long_opts[] = {
697         { "command",            required_argument,    NULL, 'c' },
698         { "help",            no_argument,        NULL, 'h' },
699         { "login",            no_argument,        NULL, 'l' },
700         { "preserve-environment",    no_argument,        NULL, 'p' },
701         { "shell",            required_argument,    NULL, 's' },
702         { "version",            no_argument,        NULL, 'v' },
703         { NULL, 0, NULL, 0 },
704     };
705
706     while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
707         switch(c) {
708         case 'c':
709             ctx.to.shell = DEFAULT_SHELL;
710             ctx.to.command = optarg;
711             break;
712         case 'h':
713             usage(EXIT_SUCCESS);
714             break;
715         case 'l':
716             ctx.to.login = 1;
717             break;
718         case 'm':
719         case 'p':
720             ctx.to.keepenv = 1;
721             break;
722         case 's':
723             ctx.to.shell = optarg;
724             break;
725         case 'V':
726             printf("%d\n", VERSION_CODE);
727             exit(EXIT_SUCCESS);
728         case 'v':
729             printf("%s\n", VERSION);
730             exit(EXIT_SUCCESS);
731         case 'u':
732             switch (get_multiuser_mode()) {
733             case MULTIUSER_MODE_USER:
734                 printf("%s\n", MULTIUSER_VALUE_USER);
735                 break;
736             case MULTIUSER_MODE_OWNER_MANAGED:
737                 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
738                 break;
739             case MULTIUSER_MODE_OWNER_ONLY:
740                 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
741                 break;
742             case MULTIUSER_MODE_NONE:
743                 printf("%s\n", MULTIUSER_VALUE_NONE);
744                 break;
745             }
746             exit(EXIT_SUCCESS);
747         default:
748             /* Bionic getopt_long doesn't terminate its error output by newline */
749             fprintf(stderr, "\n");
750             usage(2);
751         }
752     }
753
754     if (need_client) {
755         // attempt to use the daemon client if not root,
756         // or this is api 18 and adb shell (/data is not readable even as root)
757         // or just always use it on API 19+ (ART)
758         if ((geteuid() != AID_ROOT && getuid() != AID_ROOT) ||
759             (get_api_version() >= 18 && getuid() == AID_SHELL) ||
760             get_api_version() >= 19) {
761             // attempt to connect to daemon...
762             LOGD("starting daemon client %d %d", getuid(), geteuid());
763             return connect_daemon(argc, argv);
764         }
765     }
766
767     if (optind < argc && !strcmp(argv[optind], "-")) {
768         ctx.to.login = 1;
769         optind++;
770     }
771     /* username or uid */
772     if (optind < argc && strcmp(argv[optind], "--")) {
773         struct passwd *pw;
774         pw = getpwnam(argv[optind]);
775         if (!pw) {
776             char *endptr;
777
778             /* It seems we shouldn't do this at all */
779             errno = 0;
780             ctx.to.uid = strtoul(argv[optind], &endptr, 10);
781             if (errno || *endptr) {
782                 LOGE("Unknown id: %s\n", argv[optind]);
783                 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
784                 exit(EXIT_FAILURE);
785             }
786         } else {
787             ctx.to.uid = pw->pw_uid;
788             if (pw->pw_name)
789                 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
790         }
791         optind++;
792     }
793     if (optind < argc && !strcmp(argv[optind], "--")) {
794         optind++;
795     }
796     ctx.to.optind = optind;
797
798     su_ctx = &ctx;
799     if (from_init(&ctx.from) < 0) {
800         deny(&ctx);
801     }
802
803     read_options(&ctx);
804     user_init(&ctx);
805
806     // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
807     if (ctx.from.uid == AID_ROOT) {
808         LOGD("Allowing root/system/radio.");
809         allow(&ctx);
810     }
811
812     // verify superuser is installed
813     if (stat(ctx.user.base_path, &st) < 0) {
814         // send to market (disabled, because people are and think this is hijacking their su)
815         // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
816         //     silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
817         PLOGE("stat %s", ctx.user.base_path);
818         deny(&ctx);
819     }
820
821     // odd perms on superuser data dir
822     if (st.st_gid != st.st_uid) {
823         LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
824                 (int)st.st_uid, (int)st.st_gid);
825         deny(&ctx);
826     }
827
828     // always allow if this is the superuser uid
829     // superuser needs to be able to reenable itself when disabled...
830     if (ctx.from.uid == st.st_uid) {
831         allow(&ctx);
832     }
833
834     // check if superuser is disabled completely
835     if (access_disabled(&ctx.from)) {
836         LOGD("access_disabled");
837         deny(&ctx);
838     }
839
840     // autogrant shell at this point
841     if (ctx.from.uid == AID_SHELL) {
842         LOGD("Allowing shell.");
843         allow(&ctx);
844     }
845
846     // deny if this is a non owner request and owner mode only
847     if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
848         deny(&ctx);
849     }
850
851     ctx.umask = umask(027);
852
853     int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
854     if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
855         PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
856         deny(&ctx);
857     }
858
859     if (setgroups(0, NULL)) {
860         PLOGE("setgroups");
861         deny(&ctx);
862     }
863     if (setegid(st.st_gid)) {
864         PLOGE("setegid (%lu)", st.st_gid);
865         deny(&ctx);
866     }
867     if (seteuid(st.st_uid)) {
868         PLOGE("seteuid (%lu)", st.st_uid);
869         deny(&ctx);
870     }
871
872     dballow = database_check(&ctx);
873     switch (dballow) {
874         case INTERACTIVE:
875             break;
876         case ALLOW:
877             LOGD("db allowed");
878             allow(&ctx);    /* never returns */
879         case DENY:
880         default:
881             LOGD("db denied");
882             deny(&ctx);        /* never returns too */
883     }
884
885     socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
886     LOGD(ctx.sock_path);
887     if (socket_serv_fd < 0) {
888         deny(&ctx);
889     }
890
891     signal(SIGHUP, cleanup_signal);
892     signal(SIGPIPE, cleanup_signal);
893     signal(SIGTERM, cleanup_signal);
894     signal(SIGQUIT, cleanup_signal);
895     signal(SIGINT, cleanup_signal);
896     signal(SIGABRT, cleanup_signal);
897
898     if (send_request(&ctx) < 0) {
899         deny(&ctx);
900     }
901
902     atexit(cleanup);
903
904     fd = socket_accept(socket_serv_fd);
905     if (fd < 0) {
906         deny(&ctx);
907     }
908     if (socket_send_request(fd, &ctx)) {
909         deny(&ctx);
910     }
911     if (socket_receive_result(fd, buf, sizeof(buf))) {
912         deny(&ctx);
913     }
914
915     close(fd);
916     close(socket_serv_fd);
917     socket_cleanup(&ctx);
918
919     result = buf;
920
921 #define SOCKET_RESPONSE    "socket:"
922     if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
923         LOGW("SECURITY RISK: Requestor still receives credentials in intent");
924     else
925         result += sizeof(SOCKET_RESPONSE) - 1;
926
927     if (!strcmp(result, "DENY")) {
928         deny(&ctx);
929     } else if (!strcmp(result, "ALLOW")) {
930         allow(&ctx);
931     } else {
932         LOGE("unknown response from Superuser Requestor: %s", result);
933         deny(&ctx);
934     }
935 }