1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define TRACE_TAG TRACE_ADB
18 
19 #include "sysdeps.h"
20 
21 #include <errno.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 
26 #include "adb.h"
27 #include "adb_auth.h"
28 #include "adb_listeners.h"
29 #include "transport.h"
30 
31 #include <base/stringprintf.h>
32 
33 #if !ADB_HOST
34 #include <getopt.h>
35 #include <sys/prctl.h>
36 
37 #include "cutils/properties.h"
38 #include "private/android_filesystem_config.h"
39 #include "selinux/selinux.h"
40 
41 #include "qemu_tracing.h"
42 #endif
43 
adb_cleanup(void)44 static void adb_cleanup(void)
45 {
46     usb_cleanup();
47 }
48 
49 #if defined(_WIN32)
ctrlc_handler(DWORD type)50 static BOOL WINAPI ctrlc_handler(DWORD type)
51 {
52     exit(STATUS_CONTROL_C_EXIT);
53     return TRUE;
54 }
55 #endif
56 
57 #if ADB_HOST
58 #ifdef WORKAROUND_BUG6558362
59 #include <sched.h>
60 #define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
adb_set_affinity(void)61 void adb_set_affinity(void)
62 {
63    cpu_set_t cpu_set;
64    const char* cpunum_str = getenv(AFFINITY_ENVVAR);
65    char* strtol_res;
66    int cpu_num;
67 
68    if (!cpunum_str || !*cpunum_str)
69        return;
70    cpu_num = strtol(cpunum_str, &strtol_res, 0);
71    if (*strtol_res != '\0')
72      fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
73 
74    sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
75    D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
76    CPU_ZERO(&cpu_set);
77    CPU_SET(cpu_num, &cpu_set);
78    sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
79    sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
80    D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
81 }
82 #endif
83 #else /* ADB_HOST */
84 static const char *root_seclabel = NULL;
85 
drop_capabilities_bounding_set_if_needed()86 static void drop_capabilities_bounding_set_if_needed() {
87 #ifdef ALLOW_ADBD_ROOT
88     char value[PROPERTY_VALUE_MAX];
89     property_get("ro.debuggable", value, "");
90     if (strcmp(value, "1") == 0) {
91         return;
92     }
93 #endif
94     int i;
95     for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
96         if (i == CAP_SETUID || i == CAP_SETGID) {
97             // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
98             continue;
99         }
100         int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
101 
102         // Some kernels don't have file capabilities compiled in, and
103         // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
104         // die when we see such misconfigured kernels.
105         if ((err < 0) && (errno != EINVAL)) {
106             exit(1);
107         }
108     }
109 }
110 
should_drop_privileges()111 static bool should_drop_privileges() {
112 #if defined(ALLOW_ADBD_ROOT)
113     char value[PROPERTY_VALUE_MAX];
114 
115     // The emulator is never secure, so don't drop privileges there.
116     // TODO: this seems like a bug --- shouldn't the emulator behave like a device?
117     property_get("ro.kernel.qemu", value, "");
118     if (strcmp(value, "1") == 0) {
119         return false;
120     }
121 
122     // The properties that affect `adb root` and `adb unroot` are ro.secure and
123     // ro.debuggable. In this context the names don't make the expected behavior
124     // particularly obvious.
125     //
126     // ro.debuggable:
127     //   Allowed to become root, but not necessarily the default. Set to 1 on
128     //   eng and userdebug builds.
129     //
130     // ro.secure:
131     //   Drop privileges by default. Set to 1 on userdebug and user builds.
132     property_get("ro.secure", value, "1");
133     bool ro_secure = (strcmp(value, "1") == 0);
134 
135     property_get("ro.debuggable", value, "");
136     bool ro_debuggable = (strcmp(value, "1") == 0);
137 
138     // Drop privileges if ro.secure is set...
139     bool drop = ro_secure;
140 
141     property_get("service.adb.root", value, "");
142     bool adb_root = (strcmp(value, "1") == 0);
143     bool adb_unroot = (strcmp(value, "0") == 0);
144 
145     // ...except "adb root" lets you keep privileges in a debuggable build.
146     if (ro_debuggable && adb_root) {
147         drop = false;
148     }
149 
150     // ...and "adb unroot" lets you explicitly drop privileges.
151     if (adb_unroot) {
152         drop = true;
153     }
154 
155     return drop;
156 #else
157     return true; // "adb root" not allowed, always drop privileges.
158 #endif /* ALLOW_ADBD_ROOT */
159 }
160 #endif /* ADB_HOST */
161 
start_logging(void)162 void start_logging(void)
163 {
164 #if defined(_WIN32)
165     char    temp[ MAX_PATH ];
166     FILE*   fnul;
167     FILE*   flog;
168 
169     GetTempPath( sizeof(temp) - 8, temp );
170     strcat( temp, "adb.log" );
171 
172     /* Win32 specific redirections */
173     fnul = fopen( "NUL", "rt" );
174     if (fnul != NULL)
175         stdin[0] = fnul[0];
176 
177     flog = fopen( temp, "at" );
178     if (flog == NULL)
179         flog = fnul;
180 
181     setvbuf( flog, NULL, _IONBF, 0 );
182 
183     stdout[0] = flog[0];
184     stderr[0] = flog[0];
185     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
186 #else
187     int fd;
188 
189     fd = unix_open("/dev/null", O_RDONLY);
190     dup2(fd, 0);
191     adb_close(fd);
192 
193     fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
194     if(fd < 0) {
195         fd = unix_open("/dev/null", O_WRONLY);
196     }
197     dup2(fd, 1);
198     dup2(fd, 2);
199     adb_close(fd);
200     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
201 #endif
202 }
203 
adb_main(int is_daemon,int server_port)204 int adb_main(int is_daemon, int server_port)
205 {
206 #if !ADB_HOST
207     int port;
208     char value[PROPERTY_VALUE_MAX];
209 
210     umask(000);
211 #endif
212 
213     atexit(adb_cleanup);
214 #if defined(_WIN32)
215     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
216 #else
217     // No SIGCHLD. Let the service subproc handle its children.
218     signal(SIGPIPE, SIG_IGN);
219 #endif
220 
221     init_transport_registration();
222 
223 #if ADB_HOST
224     HOST = 1;
225 
226 #ifdef WORKAROUND_BUG6558362
227     if(is_daemon) adb_set_affinity();
228 #endif
229     usb_init();
230     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
231     adb_auth_init();
232 
233     std::string local_name = android::base::StringPrintf("tcp:%d", server_port);
234     if (install_listener(local_name, "*smartsocket*", NULL, 0)) {
235         exit(1);
236     }
237 #else
238     // We need to call this even if auth isn't enabled because the file
239     // descriptor will always be open.
240     adbd_cloexec_auth_socket();
241 
242     if (ALLOW_ADBD_NO_AUTH && property_get_bool("ro.adb.secure", 0) == 0) {
243         auth_required = false;
244     }
245 
246     adbd_auth_init();
247 
248     // Our external storage path may be different than apps, since
249     // we aren't able to bind mount after dropping root.
250     const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
251     if (NULL != adb_external_storage) {
252         setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
253     } else {
254         D("Warning: ADB_EXTERNAL_STORAGE is not set.  Leaving EXTERNAL_STORAGE"
255           " unchanged.\n");
256     }
257 
258     /* add extra groups:
259     ** AID_ADB to access the USB driver
260     ** AID_LOG to read system logs (adb logcat)
261     ** AID_INPUT to diagnose input issues (getevent)
262     ** AID_INET to diagnose network issues (ping)
263     ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
264     ** AID_SDCARD_R to allow reading from the SD card
265     ** AID_SDCARD_RW to allow writing to the SD card
266     ** AID_NET_BW_STATS to read out qtaguid statistics
267     */
268     gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_NET_BT,
269                        AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
270                        AID_NET_BW_STATS };
271     if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
272         exit(1);
273     }
274 
275     /* don't listen on a port (default 5037) if running in secure mode */
276     /* don't run as root if we are running in secure mode */
277     if (should_drop_privileges()) {
278         drop_capabilities_bounding_set_if_needed();
279 
280         /* then switch user and group to "shell" */
281         if (setgid(AID_SHELL) != 0) {
282             exit(1);
283         }
284         if (setuid(AID_SHELL) != 0) {
285             exit(1);
286         }
287 
288         D("Local port disabled\n");
289     } else {
290         if ((root_seclabel != NULL) && (is_selinux_enabled() > 0)) {
291             // b/12587913: fix setcon to allow const pointers
292             if (setcon((char *)root_seclabel) < 0) {
293                 exit(1);
294             }
295         }
296         std::string local_name = android::base::StringPrintf("tcp:%d", server_port);
297         if (install_listener(local_name, "*smartsocket*", NULL, 0)) {
298             exit(1);
299         }
300     }
301 
302     int usb = 0;
303     if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
304         // listen on USB
305         usb_init();
306         usb = 1;
307     }
308 
309     // If one of these properties is set, also listen on that port
310     // If one of the properties isn't set and we couldn't listen on usb,
311     // listen on the default port.
312     property_get("service.adb.tcp.port", value, "");
313     if (!value[0]) {
314         property_get("persist.adb.tcp.port", value, "");
315     }
316     if (sscanf(value, "%d", &port) == 1 && port > 0) {
317         printf("using port=%d\n", port);
318         // listen on TCP port specified by service.adb.tcp.port property
319         local_init(port);
320     } else if (!usb) {
321         // listen on default port
322         local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
323     }
324 
325     D("adb_main(): pre init_jdwp()\n");
326     init_jdwp();
327     D("adb_main(): post init_jdwp()\n");
328 #endif
329 
330     if (is_daemon)
331     {
332         // inform our parent that we are up and running.
333 #if defined(_WIN32)
334         DWORD  count;
335         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
336 #else
337         fprintf(stderr, "OK\n");
338 #endif
339         start_logging();
340     }
341     D("Event loop starting\n");
342 
343     fdevent_loop();
344 
345     usb_cleanup();
346 
347     return 0;
348 }
349 
350 #if !ADB_HOST
close_stdin()351 void close_stdin() {
352     int fd = unix_open("/dev/null", O_RDONLY);
353     if (fd == -1) {
354         perror("failed to open /dev/null, stdin will remain open");
355         return;
356     }
357     dup2(fd, 0);
358     adb_close(fd);
359 }
360 #endif
361 
362 // TODO(danalbert): Split this file up into adb_main.cpp and adbd_main.cpp.
main(int argc,char ** argv)363 int main(int argc, char **argv) {
364 #if ADB_HOST
365     // adb client/server
366     adb_sysdeps_init();
367     adb_trace_init();
368     D("Handling commandline()\n");
369     return adb_commandline(argc - 1, const_cast<const char**>(argv + 1));
370 #else
371     // adbd
372     while (true) {
373         static struct option opts[] = {
374             {"root_seclabel", required_argument, nullptr, 's'},
375             {"device_banner", required_argument, nullptr, 'b'},
376             {"version", no_argument, nullptr, 'v'},
377         };
378 
379         int option_index = 0;
380         int c = getopt_long(argc, argv, "", opts, &option_index);
381         if (c == -1)
382             break;
383         switch (c) {
384         case 's':
385             root_seclabel = optarg;
386             break;
387         case 'b':
388             adb_device_banner = optarg;
389             break;
390         case 'v':
391             printf("Android Debug Bridge Daemon version %d.%d.%d %s\n",
392                    ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION,
393                    ADB_REVISION);
394             return 0;
395         default:
396             break;
397         }
398     }
399 
400     close_stdin();
401 
402     adb_trace_init();
403 
404     /* If adbd runs inside the emulator this will enable adb tracing via
405      * adb-debug qemud service in the emulator. */
406     adb_qemu_trace_init();
407 
408     D("Handling main()\n");
409     return adb_main(0, DEFAULT_ADB_PORT);
410 #endif
411 }
412