OSDN Git Service

Merge remote-tracking branch 'ygorigor/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         int last = strlen(mode) - 1;
178         if (mode[last] == '\n')
179             mode[last] = '\0';
180         fgets(mode, sizeof(mode), fp);
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, "pid", ctx->from.pid);
370     write_string(fd, "from.name", ctx->from.name);
371     write_string(fd, "to.name", ctx->to.name);
372     write_token(fd, "from.uid", ctx->from.uid);
373     write_token(fd, "to.uid", ctx->to.uid);
374     write_string(fd, "from.bin", ctx->from.bin);
375     write_string(fd, "command", get_command(&ctx->to));
376     write_token(fd, "eof", PROTO_VERSION);
377     return 0;
378 }
379
380 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
381     ssize_t len;
382     
383     LOGD("waiting for user");
384     len = read(fd, result, result_len-1);
385     if (len < 0) {
386         PLOGE("read(result)");
387         return -1;
388     }
389     result[len] = '\0';
390
391     return 0;
392 }
393
394 static void usage(int status) {
395     FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
396
397     fprintf(stream,
398     "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
399     "Options:\n"
400     "  -c, --command COMMAND         pass COMMAND to the invoked shell\n"
401     "  -h, --help                    display this help message and exit\n"
402     "  -, -l, --login                pretend the shell to be a login shell\n"
403     "  -m, -p,\n"
404     "  --preserve-environment        do not change environment variables\n"
405     "  -s, --shell SHELL             use SHELL instead of the default " DEFAULT_SHELL "\n"
406     "  -u                            display the multiuser mode and exit\n"
407     "  -v, --version                 display version number and exit\n"
408     "  -V                            display version code and exit,\n"
409     "                                this is used almost exclusively by Superuser.apk\n");
410     exit(status);
411 }
412
413 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
414     char *cmd = get_command(&ctx->to);
415
416     // No send to UI denied requests for shell and root users (they are in the log)
417     // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
418         send_result(ctx, DENY);
419     // }
420     LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
421     fprintf(stderr, "%s\n", strerror(EACCES));
422     exit(EXIT_FAILURE);
423 }
424
425 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
426     char *arg0;
427     int argc, err;
428
429     umask(ctx->umask);
430     // No send to UI accepted requests for shell and root users (they are in the log)
431     // if( ctx->from.uid != AID_SHELL && ctx->from.uid != AID_ROOT ) {
432         send_result(ctx, ALLOW);
433     // }
434
435     arg0 = strrchr (ctx->to.shell, '/');
436     arg0 = (arg0) ? arg0 + 1 : ctx->to.shell;
437     if (ctx->to.login) {
438         int s = strlen(arg0) + 2;
439         char *p = malloc(s);
440
441         if (!p)
442             exit(EXIT_FAILURE);
443
444         *p = '-';
445         strcpy(p + 1, arg0);
446         arg0 = p;
447     }
448
449     populate_environment(ctx);
450     set_identity(ctx->to.uid);
451
452 #define PARG(arg)                                    \
453     (ctx->to.optind + (arg) < ctx->to.argc) ? " " : "",                    \
454     (ctx->to.optind + (arg) < ctx->to.argc) ? ctx->to.argv[ctx->to.optind + (arg)] : ""
455
456     LOGD("%u %s executing %u %s using shell %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
457             ctx->from.uid, ctx->from.bin,
458             ctx->to.uid, get_command(&ctx->to), ctx->to.shell,
459             arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
460             (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
461
462     argc = ctx->to.optind;
463     if (ctx->to.command) {
464         ctx->to.argv[--argc] = ctx->to.command;
465         ctx->to.argv[--argc] = "-c";
466     }
467     ctx->to.argv[--argc] = arg0;
468     execv(ctx->to.shell, ctx->to.argv + argc);
469     err = errno;
470     PLOGE("exec");
471     fprintf(stderr, "Cannot execute %s: %s\n", ctx->to.shell, strerror(err));
472     exit(EXIT_FAILURE);
473 }
474
475 /*
476  * CyanogenMod-specific behavior
477  *
478  * we can't simply use the property service, since we aren't launched from init
479  * and can't trust the location of the property workspace.
480  * Find the properties ourselves.
481  */
482 int access_disabled(const struct su_initiator *from) {
483     char *data;
484     char build_type[PROPERTY_VALUE_MAX];
485     char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
486     size_t len;
487
488     data = read_file("/system/build.prop");
489     if (check_property(data, "ro.cm.version")) {
490         get_property(data, build_type, "ro.build.type", "");
491         free(data);
492
493         data = read_file("/default.prop");
494         get_property(data, debuggable, "ro.debuggable", "0");
495         free(data);
496         /* only allow su on debuggable builds */
497         if (strcmp("1", debuggable) != 0) {
498             LOGE("Root access is disabled on non-debug builds");
499             return 1;
500         }
501
502         data = read_file("/data/property/persist.sys.root_access");
503         if (data != NULL) {
504             len = strlen(data);
505             if (len >= PROPERTY_VALUE_MAX)
506                 memcpy(enabled, "1", 2);
507             else
508                 memcpy(enabled, data, len + 1);
509             free(data);
510         } else
511             memcpy(enabled, "1", 2);
512
513         /* enforce persist.sys.root_access on non-eng builds for apps */
514         if (strcmp("eng", build_type) != 0 &&
515                 from->uid != AID_SHELL && from->uid != AID_ROOT &&
516                 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
517             LOGE("Apps root access is disabled by system setting - "
518                  "enable it under settings -> developer options");
519             return 1;
520         }
521
522         /* disallow su in a shell if appropriate */
523         if (from->uid == AID_SHELL &&
524                 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
525             LOGE("Shell root access is disabled by a system setting - "
526                  "enable it under settings -> developer options");
527             return 1;
528         }
529         
530     }
531     return 0;
532 }
533
534 int main(int argc, char *argv[]) {
535     // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
536     /* The same list than GLibc at this point */
537     static const char* const unsec_vars[] = {
538         "GCONV_PATH",
539         "GETCONF_DIR",
540         "HOSTALIASES",
541         "LD_AUDIT",
542         "LD_DEBUG",
543         "LD_DEBUG_OUTPUT",
544         "LD_DYNAMIC_WEAK",
545         "LD_LIBRARY_PATH",
546         "LD_ORIGIN_PATH",
547         "LD_PRELOAD",
548         "LD_PROFILE",
549         "LD_SHOW_AUXV",
550         "LD_USE_LOAD_BIAS",
551         "LOCALDOMAIN",
552         "LOCPATH",
553         "MALLOC_TRACE",
554         "MALLOC_CHECK_",
555         "NIS_PATH",
556         "NLSPATH",
557         "RESOLV_HOST_CONF",
558         "RES_OPTIONS",
559         "TMPDIR",
560         "TZDIR",
561         "LD_AOUT_LIBRARY_PATH",
562         "LD_AOUT_PRELOAD",
563         // not listed in linker, used due to system() call
564         "IFS",
565     };
566     const char* const* cp   = unsec_vars;
567     const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
568     while (cp < endp) {
569         unsetenv(*cp);
570         cp++;
571     }
572
573     /*
574      * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
575      * This occurs on Android 4.0+
576      */
577     setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
578
579     LOGD("su invoked.");
580
581     struct su_context ctx = {
582         .from = {
583             .pid = -1,
584             .uid = 0,
585             .bin = "",
586             .args = "",
587             .name = "",
588         },
589         .to = {
590             .uid = AID_ROOT,
591             .login = 0,
592             .keepenv = 0,
593             .shell = DEFAULT_SHELL,
594             .command = NULL,
595             .argv = argv,
596             .argc = argc,
597             .optind = 0,
598             .name = "",
599         },
600         .user = {
601             .android_user_id = 0,
602             .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
603             .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
604             .base_path = REQUESTOR_DATA_PATH REQUESTOR
605         },
606     };
607     struct stat st;
608     int c, socket_serv_fd, fd;
609     char buf[64], *result;
610     policy_t dballow;
611     struct option long_opts[] = {
612         { "command",            required_argument,    NULL, 'c' },
613         { "help",            no_argument,        NULL, 'h' },
614         { "login",            no_argument,        NULL, 'l' },
615         { "preserve-environment",    no_argument,        NULL, 'p' },
616         { "shell",            required_argument,    NULL, 's' },
617         { "version",            no_argument,        NULL, 'v' },
618         { NULL, 0, NULL, 0 },
619     };
620
621     while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
622         switch(c) {
623         case 'c':
624             ctx.to.command = optarg;
625             break;
626         case 'h':
627             usage(EXIT_SUCCESS);
628             break;
629         case 'l':
630             ctx.to.login = 1;
631             break;
632         case 'm':
633         case 'p':
634             ctx.to.keepenv = 1;
635             break;
636         case 's':
637             ctx.to.shell = optarg;
638             break;
639         case 'V':
640             printf("%d\n", VERSION_CODE);
641             exit(EXIT_SUCCESS);
642         case 'v':
643             printf("%s\n", VERSION);
644             exit(EXIT_SUCCESS);
645         case 'u':
646             switch (get_multiuser_mode()) {
647             case MULTIUSER_MODE_USER:
648                 printf("%s\n", MULTIUSER_VALUE_USER);
649                 break;
650             case MULTIUSER_MODE_OWNER_MANAGED:
651                 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
652                 break;
653             case MULTIUSER_MODE_OWNER_ONLY:
654                 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
655                 break;
656             case MULTIUSER_MODE_NONE:
657                 printf("%s\n", MULTIUSER_VALUE_NONE);
658                 break;
659             }
660             exit(EXIT_SUCCESS);
661         default:
662             /* Bionic getopt_long doesn't terminate its error output by newline */
663             fprintf(stderr, "\n");
664             usage(2);
665         }
666     }
667     if (optind < argc && !strcmp(argv[optind], "-")) {
668         ctx.to.login = 1;
669         optind++;
670     }
671     /* username or uid */
672     if (optind < argc && strcmp(argv[optind], "--")) {
673         struct passwd *pw;
674         pw = getpwnam(argv[optind]);
675         if (!pw) {
676             char *endptr;
677
678             /* It seems we shouldn't do this at all */
679             errno = 0;
680             ctx.to.uid = strtoul(argv[optind], &endptr, 10);
681             if (errno || *endptr) {
682                 LOGE("Unknown id: %s\n", argv[optind]);
683                 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
684                 exit(EXIT_FAILURE);
685             }
686         } else {
687             ctx.to.uid = pw->pw_uid;
688             if (pw->pw_name)
689                 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
690         }
691         optind++;
692     }
693     if (optind < argc && !strcmp(argv[optind], "--")) {
694         optind++;
695     }
696     ctx.to.optind = optind;
697
698     su_ctx = &ctx;
699     if (from_init(&ctx.from) < 0) {
700         deny(&ctx);
701     }
702         
703     read_options(&ctx);
704     user_init(&ctx);
705     
706     if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
707         deny(&ctx);
708     }
709
710     if (access_disabled(&ctx.from)) {
711         LOGD("access_disabled");
712         deny(&ctx);
713     }
714
715     ctx.umask = umask(027);
716
717     if (ctx.from.uid == AID_ROOT || ctx.from.uid == AID_SHELL) {
718         LOGD("Allowing root/shell.");
719         allow(&ctx);
720     }
721
722     if (stat(ctx.user.base_path, &st) < 0) {
723         PLOGE("stat %s", ctx.user.base_path);
724         deny(&ctx);
725     }
726
727     if (st.st_gid != st.st_uid) {
728         LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
729                 (int)st.st_uid, (int)st.st_gid);
730         deny(&ctx);
731     }
732
733     int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
734     if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
735         PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
736         deny(&ctx);
737     }
738
739     if (setgroups(0, NULL)) {
740         PLOGE("setgroups");
741         deny(&ctx);
742     }
743     if (setegid(st.st_gid)) {
744         PLOGE("setegid (%lu)", st.st_gid);
745         deny(&ctx);
746     }
747     if (seteuid(st.st_uid)) {
748         PLOGE("seteuid (%lu)", st.st_uid);
749         deny(&ctx);
750     }
751
752     dballow = database_check(&ctx);
753     switch (dballow) {
754         case INTERACTIVE:
755             break;
756         case ALLOW:
757             LOGD("db allowed");
758             allow(&ctx);    /* never returns */
759         case DENY:
760         default:
761             LOGD("db denied");
762             deny(&ctx);        /* never returns too */
763     }
764     
765     socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
766     LOGD(ctx.sock_path);
767     if (socket_serv_fd < 0) {
768         deny(&ctx);
769     }
770
771     signal(SIGHUP, cleanup_signal);
772     signal(SIGPIPE, cleanup_signal);
773     signal(SIGTERM, cleanup_signal);
774     signal(SIGQUIT, cleanup_signal);
775     signal(SIGINT, cleanup_signal);
776     signal(SIGABRT, cleanup_signal);
777
778     if (send_request(&ctx) < 0) {
779         deny(&ctx);
780     }
781
782     atexit(cleanup);
783
784     fd = socket_accept(socket_serv_fd);
785     if (fd < 0) {
786         deny(&ctx);
787     }
788     if (socket_send_request(fd, &ctx)) {
789         deny(&ctx);
790     }
791     if (socket_receive_result(fd, buf, sizeof(buf))) {
792         deny(&ctx);
793     }
794
795     close(fd);
796     close(socket_serv_fd);
797     socket_cleanup(&ctx);
798
799     result = buf;
800
801 #define SOCKET_RESPONSE    "socket:"
802     if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
803         LOGW("SECURITY RISK: Requestor still receives credentials in intent");
804     else
805         result += sizeof(SOCKET_RESPONSE) - 1;
806
807     if (!strcmp(result, "DENY")) {
808         deny(&ctx);
809     } else if (!strcmp(result, "ALLOW")) {
810         allow(&ctx);
811     } else {
812         LOGE("unknown response from Superuser Requestor: %s", result);
813         deny(&ctx);
814     }
815 }