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