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 ADB
18 
19 #include "sysdeps.h"
20 
21 #include <errno.h>
22 #include <getopt.h>
23 #include <malloc.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <sys/capability.h>
28 #include <sys/prctl.h>
29 
30 #include <memory>
31 #include <vector>
32 
33 #include <android-base/logging.h>
34 #include <android-base/macros.h>
35 #include <android-base/properties.h>
36 #include <android-base/stringprintf.h>
37 #include <android-base/strings.h>
38 
39 #if defined(__ANDROID__)
40 #include <libminijail.h>
41 #include <log/log_properties.h>
42 #include <scoped_minijail.h>
43 
44 #include <private/android_filesystem_config.h>
45 #include "selinux/android.h"
46 #endif
47 
48 #include "adb.h"
49 #include "adb_auth.h"
50 #include "adb_listeners.h"
51 #include "adb_utils.h"
52 #include "adb_wifi.h"
53 #include "socket_spec.h"
54 #include "tradeinmode.h"
55 #include "transport.h"
56 
57 #include "daemon/jdwp_service.h"
58 #include "daemon/mdns.h"
59 #include "daemon/transport_daemon.h"
60 #include "daemon/watchdog.h"
61 
62 #if defined(__ANDROID__)
63 static const char* root_seclabel = nullptr;
64 static const char* tim_seclabel = nullptr;
65 
should_drop_privileges()66 static bool should_drop_privileges() {
67     // The properties that affect `adb root` and `adb unroot` are ro.secure and
68     // ro.debuggable. In this context the names don't make the expected behavior
69     // particularly obvious.
70     //
71     // ro.debuggable:
72     //   Allowed to become root, but not necessarily the default. Set to 1 on
73     //   eng and userdebug builds.
74     //
75     // ro.secure:
76     //   Drop privileges by default. Set to 1 on userdebug and user builds.
77     bool ro_secure = android::base::GetBoolProperty("ro.secure", true);
78     bool ro_debuggable = __android_log_is_debuggable();
79 
80     // Drop privileges if ro.secure is set...
81     bool drop = ro_secure;
82 
83     // ... except "adb root" lets you keep privileges in a debuggable build.
84     std::string prop = android::base::GetProperty("service.adb.root", "");
85     bool adb_root = (prop == "1");
86     bool adb_unroot = (prop == "0");
87     if (ro_debuggable && adb_root) {
88         drop = false;
89     }
90     // ... and "adb unroot" lets you explicitly drop privileges.
91     if (adb_unroot) {
92         drop = true;
93     }
94 
95     return drop;
96 }
97 
drop_privileges()98 static void drop_privileges() {
99     ScopedMinijail jail(minijail_new());
100 
101     // Add extra groups:
102     // AID_ADB to access the USB driver
103     // AID_LOG to read system logs (adb logcat)
104     // AID_INPUT to diagnose input issues (getevent)
105     // AID_INET to diagnose network issues (ping)
106     // AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
107     // AID_SDCARD_R to allow reading from the SD card
108     // AID_SDCARD_RW to allow writing to the SD card
109     // AID_NET_BW_STATS to read out qtaguid statistics
110     // AID_READPROC for reading /proc entries across UID boundaries
111     // AID_UHID for using 'hid' command to read/write to /dev/uhid
112     // AID_EXT_DATA_RW for writing to /sdcard/Android/data (devices without sdcardfs)
113     // AID_EXT_OBB_RW for writing to /sdcard/Android/obb (devices without sdcardfs)
114     // AID_READTRACEFS for reading tracefs entries
115     gid_t groups[] = {AID_ADB,          AID_LOG,          AID_INPUT,    AID_INET,
116                       AID_NET_BT,       AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
117                       AID_NET_BW_STATS, AID_READPROC,     AID_UHID,     AID_EXT_DATA_RW,
118                       AID_EXT_OBB_RW,   AID_READTRACEFS};
119     minijail_set_supplementary_gids(jail.get(), arraysize(groups), groups);
120 
121     // Don't run as root if running in secure mode.
122     if (should_drop_privileges()) {
123         const bool should_drop_caps = !__android_log_is_debuggable();
124 
125         if (should_drop_caps) {
126             // CAP_SETUI and CAP_SETGID are required for change_uid and change_gid calls below.
127             // CAP_SYS_NICE needs to be in the bounding set of adbd for sh spawned from `adb shell`
128             // to also have it in the bounding set. This in turn is required to be able to launch
129             // VMs from shell (e.g. adb shell /apex/com.android.virt/bin/vm run-microdroid).
130             // Full fork+execve chain looks like this:
131             //   adbd (CapBnd: CAP_SYS_NICE) -> /system/bin/sh (CapBnd: CAP_SYS_NICE) ->
132             //   /apex/com.android.virt/bin/vm (CapBnd: CAP_SYS_NICE) ->
133             //   virtmngr (CapBnd: CAP_SYS_NICE) -> crosvm (CapEff: CAP_SYS_NICE).
134             // Note: the adbd will drop it's effective capabilities several lines below, while the
135             // /system/bin/sh process spawned from adbd will run as non-root uid, hence won't be
136             // able to use the CAP_SYS_NICE capability in the first place.
137             minijail_use_caps(jail.get(), CAP_TO_MASK(CAP_SETUID) | CAP_TO_MASK(CAP_SETGID) |
138                                                   CAP_TO_MASK(CAP_SYS_NICE));
139         }
140 
141         minijail_change_gid(jail.get(), AID_SHELL);
142         minijail_change_uid(jail.get(), AID_SHELL);
143         // minijail_enter() will abort if any priv-dropping step fails.
144         minijail_enter(jail.get());
145 
146         // Whenever ambient capabilities are being used, minijail cannot
147         // simultaneously drop the bounding capability set to just
148         // CAP_SETUID|CAP_SETGID while clearing the inheritable, effective,
149         // and permitted sets. So we need to do that in two steps.
150         using ScopedCaps =
151             std::unique_ptr<std::remove_pointer<cap_t>::type, std::function<void(cap_t)>>;
152         ScopedCaps caps(cap_get_proc(), &cap_free);
153         if (cap_clear_flag(caps.get(), CAP_INHERITABLE) == -1) {
154             PLOG(FATAL) << "cap_clear_flag(INHERITABLE) failed";
155         }
156         if (cap_clear_flag(caps.get(), CAP_EFFECTIVE) == -1) {
157             PLOG(FATAL) << "cap_clear_flag(EFFECTIVE) failed";
158         }
159         if (cap_clear_flag(caps.get(), CAP_PERMITTED) == -1) {
160             PLOG(FATAL) << "cap_clear_flag(PEMITTED) failed";
161         }
162         if (cap_set_proc(caps.get()) != 0) {
163             PLOG(FATAL) << "cap_set_proc() failed";
164         }
165 
166         if (should_enter_tradeinmode()) {
167             enter_tradeinmode(tim_seclabel);
168             auth_required = false;
169         } else if (is_in_tradein_evaluation_mode()) {
170             auth_required = false;
171         }
172     } else {
173         // minijail_enter() will abort if any priv-dropping step fails.
174         minijail_enter(jail.get());
175 
176         if (root_seclabel != nullptr) {
177             if (selinux_android_setcon(root_seclabel) < 0) {
178                 // If we failed to become root, don't try again to avoid a
179                 // restart loop.
180                 android::base::SetProperty("service.adb.root", "0");
181                 LOG(FATAL) << "Could not set SELinux context";
182             }
183         }
184     }
185 }
186 #endif
187 
setup_adb(const std::vector<std::string> & addrs)188 static void setup_adb(const std::vector<std::string>& addrs) {
189 #if defined(__ANDROID__)
190     // Get the first valid port from addrs and setup mDNS.
191     int port = -1;
192     std::string error;
193     for (const auto& addr : addrs) {
194         port = get_host_socket_spec_port(addr, &error);
195         if (port != -1) {
196             break;
197         }
198     }
199     if (port == -1) {
200         port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
201     }
202     LOG(INFO) << "Setup mdns on port= " << port;
203     setup_mdns(port);
204 #endif
205     for (const auto& addr : addrs) {
206         LOG(INFO) << "adbd listening on " << addr;
207         init_transport_socket_server(addr);
208     }
209 }
210 
adbd_main()211 int adbd_main() {
212     umask(0);
213 
214     signal(SIGPIPE, SIG_IGN);
215 
216     // We need to call this even if auth isn't enabled because the file
217     // descriptor will always be open.
218     adbd_cloexec_auth_socket();
219 
220 #if defined(__ANDROID__)
221     bool device_unlocked = android::base::GetProperty("ro.boot.verifiedbootstate", "") == "orange";
222     if (device_unlocked || __android_log_is_debuggable()) {
223 #if defined(__ANDROID_RECOVERY__)
224         auth_required = false;  // Bypass authorization when the device transitions to
225         // fastbootd (from recovery). A corrupt userdata image can potentially
226         // result in the device falling into rescue, and a subsequent fastboot
227         // state should not require authorization - otherwise, it will force the
228         // need for manual intervention(b/188703874).
229 #else
230         // If we're on userdebug/eng or the device is unlocked, permit no-authentication.
231         auth_required = android::base::GetBoolProperty("ro.adb.secure", false);
232 #endif
233     }
234 #endif
235 
236     // Our external storage path may be different than apps, since
237     // we aren't able to bind mount after dropping root.
238     const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
239     if (adb_external_storage != nullptr) {
240         setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
241     } else {
242         D("Warning: ADB_EXTERNAL_STORAGE is not set.  Leaving EXTERNAL_STORAGE"
243           " unchanged.\n");
244     }
245 
246 #if defined(__ANDROID__)
247     drop_privileges();
248 #endif
249 
250 #if defined(__ANDROID__)
251     // A thread gets spawned as a side-effect of initializing the watchdog, so it needs to happen
252     // after we drop privileges.
253     watchdog::Initialize();
254 #endif
255 
256     // adbd_auth_init will spawn a thread, so we need to defer it until after selinux transitions.
257     adbd_auth_init();
258 
259     bool is_usb = false;
260 
261 #if defined(__ANDROID__)
262     if (access(USB_FFS_ADB_EP0, F_OK) == 0) {
263         // Listen on USB.
264         usb_init();
265         is_usb = true;
266     }
267 #endif
268 
269     // If one of these properties is set, also listen on that port.
270     // If one of the properties isn't set and we couldn't listen on usb, listen
271     // on the default port.
272     std::vector<std::string> addrs;
273     std::string prop_addr = android::base::GetProperty("service.adb.listen_addrs", "");
274     if (prop_addr.empty()) {
275         std::string prop_port = android::base::GetProperty("service.adb.tcp.port", "");
276         if (prop_port.empty()) {
277             prop_port = android::base::GetProperty("persist.adb.tcp.port", "");
278         }
279 
280 #if !defined(__ANDROID__)
281         if (prop_port.empty() && getenv("ADBD_PORT")) {
282             prop_port = getenv("ADBD_PORT");
283         }
284 #endif
285 
286         int port;
287         if (sscanf(prop_port.c_str(), "%d", &port) == 1 && port > 0) {
288             D("using tcp port=%d", port);
289             // Listen on TCP and VSOCK port specified by service.adb.tcp.port property.
290             addrs.push_back(android::base::StringPrintf("tcp:%d", port));
291             addrs.push_back(android::base::StringPrintf("vsock:%d", port));
292             setup_adb(addrs);
293         } else if (!is_usb) {
294             // Listen on default port.
295             addrs.push_back(
296                     android::base::StringPrintf("tcp:%d", DEFAULT_ADB_LOCAL_TRANSPORT_PORT));
297             addrs.push_back(
298                     android::base::StringPrintf("vsock:%d", DEFAULT_ADB_LOCAL_TRANSPORT_PORT));
299             setup_adb(addrs);
300         }
301     } else {
302         addrs = android::base::Split(prop_addr, ",");
303         setup_adb(addrs);
304     }
305 
306     LOG(INFO) << "adbd started";
307 
308     D("adbd_main(): pre init_jdwp()");
309     init_jdwp();
310     D("adbd_main(): post init_jdwp()");
311 
312     D("Event loop starting");
313     fdevent_loop();
314 
315     return 0;
316 }
317 
main(int argc,char ** argv)318 int main(int argc, char** argv) {
319 #if defined(__BIONIC__)
320     // Set M_DECAY_TIME so that our allocations aren't immediately purged on free.
321     mallopt(M_DECAY_TIME, 1);
322 #endif
323 
324     while (true) {
325         static struct option opts[] = {
326                 {"root_seclabel", required_argument, nullptr, 's'},
327                 {"tim_seclabel", required_argument, nullptr, 't'},
328                 {"device_banner", required_argument, nullptr, 'b'},
329                 {"version", no_argument, nullptr, 'v'},
330                 {"logpostfsdata", no_argument, nullptr, 'l'},
331                 {nullptr, no_argument, nullptr, 0},
332         };
333 
334         int option_index = 0;
335         int c = getopt_long(argc, argv, "", opts, &option_index);
336         if (c == -1) {
337             break;
338         }
339 
340         switch (c) {
341 #if defined(__ANDROID__)
342             case 's':
343                 root_seclabel = optarg;
344                 break;
345             case 't':
346                 tim_seclabel = optarg;
347                 break;
348 #endif
349             case 'b':
350                 adb_device_banner = optarg;
351                 break;
352             case 'v':
353                 printf("Android Debug Bridge Daemon version %d.%d.%d\n", ADB_VERSION_MAJOR,
354                        ADB_VERSION_MINOR, ADB_SERVER_VERSION);
355                 return 0;
356             case 'l':
357                 LOG(ERROR) << "post-fs-data triggered";
358                 return 0;
359             default:
360                 // getopt already prints "adbd: invalid option -- %c" for us.
361                 return 1;
362         }
363     }
364 
365     close_stdin();
366 
367     adb_trace_init(argv);
368 
369     D("Handling main()");
370     return adbd_main();
371 }
372