OSDN Git Service

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