OSDN Git Service

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