blob: f87ee85a85e7d6e062f94731a523158e2dd0943a [file] [log] [blame]
Benoit Goby2cc19e42012-04-12 12:23:49 -07001/*
2 * Copyright (C) 2012 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
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG AUTH
Dan Albertdb6fe642015-03-19 15:21:08 -070018
Josh Gao22cb70b2016-08-18 22:00:12 -070019#include <dirent.h>
Benoit Goby2cc19e42012-04-12 12:23:49 -070020#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080021#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070022#include <string.h>
Josh Gao22cb70b2016-08-18 22:00:12 -070023#if defined(__linux__)
24#include <sys/inotify.h>
25#endif
Benoit Goby2cc19e42012-04-12 12:23:49 -070026
Josh Gao22cb70b2016-08-18 22:00:12 -070027#include <map>
Elliott Hughes801066a2016-06-29 17:42:01 -070028#include <mutex>
Josh Gao22cb70b2016-08-18 22:00:12 -070029#include <set>
30#include <string>
Benoit Goby2cc19e42012-04-12 12:23:49 -070031
Joshua Duong090c8072019-12-19 16:36:30 -080032#include <adb/crypto/rsa_2048_key.h>
Joshua Duong64fab752020-01-21 13:19:42 -080033#include <adb/crypto/x509_generator.h>
34#include <adb/tls/adb_ca_list.h>
35#include <adb/tls/tls_connection.h>
David Pursellc573d522016-01-27 08:52:53 -080036#include <android-base/errors.h>
Elliott Hughese0a6e2a2016-05-26 22:43:19 -070037#include <android-base/file.h>
Yurii Zubrytskyi09ecaa52016-05-26 09:46:10 -070038#include <android-base/stringprintf.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080039#include <android-base/strings.h>
Mattias Nisslera947b492016-03-31 16:32:09 +020040#include <crypto_utils/android_pubkey.h>
Elliott Hughesab942fd2016-06-21 16:50:48 -070041#include <openssl/base64.h>
Benoit Goby2cc19e42012-04-12 12:23:49 -070042#include <openssl/evp.h>
43#include <openssl/objects.h>
44#include <openssl/pem.h>
45#include <openssl/rsa.h>
46#include <openssl/sha.h>
47
Josh Gao22cb70b2016-08-18 22:00:12 -070048#include "adb.h"
49#include "adb_auth.h"
Josh Gao13102c32018-11-15 17:45:46 -080050#include "adb_io.h"
Josh Gao22cb70b2016-08-18 22:00:12 -070051#include "adb_utils.h"
52#include "sysdeps.h"
Josh Gaoeac20582016-10-05 19:02:29 -070053#include "transport.h"
Benoit Goby2cc19e42012-04-12 12:23:49 -070054
Josh Gao22cb70b2016-08-18 22:00:12 -070055static std::mutex& g_keys_mutex = *new std::mutex;
56static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
57 *new std::map<std::string, std::shared_ptr<RSA>>;
58static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;
Benoit Goby2cc19e42012-04-12 12:23:49 -070059
Joshua Duong090c8072019-12-19 16:36:30 -080060using namespace adb::crypto;
Joshua Duong64fab752020-01-21 13:19:42 -080061using namespace adb::tls;
Josh Gao972221b2019-04-29 12:36:32 -070062
Joshua Duong090c8072019-12-19 16:36:30 -080063static bool generate_key(const std::string& file) {
Elliott Hughes801066a2016-06-29 17:42:01 -070064 LOG(INFO) << "generate_key(" << file << ")...";
65
Joshua Duong090c8072019-12-19 16:36:30 -080066 auto rsa_2048 = CreateRSA2048Key();
67 if (!rsa_2048) {
68 LOG(ERROR) << "Unable to create key";
69 return false;
70 }
Josh Gao972221b2019-04-29 12:36:32 -070071 std::string pubkey;
Benoit Goby2cc19e42012-04-12 12:23:49 -070072
Joshua Duong090c8072019-12-19 16:36:30 -080073 RSA* rsa = EVP_PKEY_get0_RSA(rsa_2048->GetEvpPkey());
74 CHECK(rsa);
Benoit Goby2cc19e42012-04-12 12:23:49 -070075
Joshua Duong090c8072019-12-19 16:36:30 -080076 if (!CalculatePublicKey(&pubkey, rsa)) {
Josh Gao972221b2019-04-29 12:36:32 -070077 LOG(ERROR) << "failed to calculate public key";
Joshua Duong090c8072019-12-19 16:36:30 -080078 return false;
Josh Gao972221b2019-04-29 12:36:32 -070079 }
80
Joshua Duong090c8072019-12-19 16:36:30 -080081 mode_t old_mask = umask(077);
Benoit Gobycb37c502012-08-31 12:14:21 -070082
Joshua Duong090c8072019-12-19 16:36:30 -080083 std::unique_ptr<FILE, decltype(&fclose)> f(nullptr, &fclose);
84 f.reset(fopen(file.c_str(), "w"));
Benoit Goby2cc19e42012-04-12 12:23:49 -070085 if (!f) {
Elliott Hughes801066a2016-06-29 17:42:01 -070086 PLOG(ERROR) << "Failed to open " << file;
Benoit Gobycb37c502012-08-31 12:14:21 -070087 umask(old_mask);
Joshua Duong090c8072019-12-19 16:36:30 -080088 return false;
Benoit Goby2cc19e42012-04-12 12:23:49 -070089 }
90
Benoit Gobycb37c502012-08-31 12:14:21 -070091 umask(old_mask);
92
Joshua Duong090c8072019-12-19 16:36:30 -080093 if (!PEM_write_PrivateKey(f.get(), rsa_2048->GetEvpPkey(), nullptr, nullptr, 0, nullptr,
94 nullptr)) {
Josh Gao972221b2019-04-29 12:36:32 -070095 LOG(ERROR) << "Failed to write key";
Joshua Duong090c8072019-12-19 16:36:30 -080096 return false;
Josh Gao972221b2019-04-29 12:36:32 -070097 }
98
99 if (!android::base::WriteStringToFile(pubkey, file + ".pub")) {
100 PLOG(ERROR) << "failed to write public key";
Joshua Duong090c8072019-12-19 16:36:30 -0800101 return false;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700102 }
103
Joshua Duong090c8072019-12-19 16:36:30 -0800104 return true;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700105}
106
Josh Gao22cb70b2016-08-18 22:00:12 -0700107static std::string hash_key(RSA* key) {
108 unsigned char* pubkey = nullptr;
109 int len = i2d_RSA_PUBKEY(key, &pubkey);
110 if (len < 0) {
111 LOG(ERROR) << "failed to encode RSA public key";
112 return std::string();
113 }
114
115 std::string result;
116 result.resize(SHA256_DIGEST_LENGTH);
117 SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0]));
118 OPENSSL_free(pubkey);
119 return result;
120}
121
Josh Gao13102c32018-11-15 17:45:46 -0800122static std::shared_ptr<RSA> read_key_file(const std::string& file) {
Elliott Hughes801066a2016-06-29 17:42:01 -0700123 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
Elliott Hughesfb2ba512015-04-24 23:02:00 -0700124 if (!fp) {
Elliott Hughes801066a2016-06-29 17:42:01 -0700125 PLOG(ERROR) << "Failed to open '" << file << "'";
Josh Gao13102c32018-11-15 17:45:46 -0800126 return nullptr;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700127 }
128
Elliott Hughes801066a2016-06-29 17:42:01 -0700129 RSA* key = RSA_new();
130 if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
Elliott Hughes3b1ff092019-10-07 08:21:58 -0700131 LOG(ERROR) << "Failed to read key from '" << file << "'";
132 ERR_print_errors_fp(stderr);
Elliott Hughes801066a2016-06-29 17:42:01 -0700133 RSA_free(key);
Josh Gao13102c32018-11-15 17:45:46 -0800134 return nullptr;
135 }
136
137 return std::shared_ptr<RSA>(key, RSA_free);
138}
139
140static bool load_key(const std::string& file) {
141 std::shared_ptr<RSA> key = read_key_file(file);
142 if (!key) {
Elliott Hughes801066a2016-06-29 17:42:01 -0700143 return false;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700144 }
145
Josh Gao22cb70b2016-08-18 22:00:12 -0700146 std::lock_guard<std::mutex> lock(g_keys_mutex);
Josh Gao13102c32018-11-15 17:45:46 -0800147 std::string fingerprint = hash_key(key.get());
Elliott Hughesd3e5a5d2024-06-25 11:28:12 +0000148 bool already_loaded = g_keys.contains(fingerprint);
Elliott Hughes758a27d2020-03-07 12:51:00 -0800149 if (!already_loaded) {
Josh Gao13102c32018-11-15 17:45:46 -0800150 g_keys[fingerprint] = std::move(key);
Josh Gao22cb70b2016-08-18 22:00:12 -0700151 }
Elliott Hughes758a27d2020-03-07 12:51:00 -0800152 LOG(INFO) << (already_loaded ? "ignored already-loaded" : "loaded new") << " key from '" << file
153 << "' with fingerprint " << SHA256BitsToHexString(fingerprint);
Elliott Hughes801066a2016-06-29 17:42:01 -0700154 return true;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700155}
156
Josh Gao13102c32018-11-15 17:45:46 -0800157static bool load_keys(const std::string& path, bool allow_dir = true) {
158 LOG(INFO) << "load_keys '" << path << "'...";
Josh Gao22cb70b2016-08-18 22:00:12 -0700159
160 struct stat st;
161 if (stat(path.c_str(), &st) != 0) {
Elliott Hughes758a27d2020-03-07 12:51:00 -0800162 PLOG(ERROR) << "load_keys: failed to stat '" << path << "'";
Josh Gao22cb70b2016-08-18 22:00:12 -0700163 return false;
164 }
165
166 if (S_ISREG(st.st_mode)) {
Josh Gao13102c32018-11-15 17:45:46 -0800167 return load_key(path);
Elliott Hughes758a27d2020-03-07 12:51:00 -0800168 }
169
170 if (S_ISDIR(st.st_mode)) {
Josh Gao22cb70b2016-08-18 22:00:12 -0700171 if (!allow_dir) {
172 // inotify isn't recursive. It would break expectations to load keys in nested
173 // directories but not monitor them for new keys.
Elliott Hughes758a27d2020-03-07 12:51:00 -0800174 LOG(WARNING) << "load_keys: refusing to recurse into directory '" << path << "'";
Josh Gao22cb70b2016-08-18 22:00:12 -0700175 return false;
176 }
177
178 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
179 if (!dir) {
Elliott Hughes758a27d2020-03-07 12:51:00 -0800180 PLOG(ERROR) << "load_keys: failed to open directory '" << path << "'";
Josh Gao22cb70b2016-08-18 22:00:12 -0700181 return false;
182 }
183
184 bool result = false;
185 while (struct dirent* dent = readdir(dir.get())) {
186 std::string name = dent->d_name;
187
188 // We can't use dent->d_type here because it's not available on Windows.
189 if (name == "." || name == "..") {
190 continue;
191 }
192
Josh Gaoe9e7bac2016-12-14 16:59:29 -0800193 if (!android::base::EndsWith(name, ".adb_key")) {
Elliott Hughes758a27d2020-03-07 12:51:00 -0800194 LOG(INFO) << "skipped non-adb_key '" << path << "/" << name << "'";
Josh Gaoe9e7bac2016-12-14 16:59:29 -0800195 continue;
196 }
197
Josh Gao13102c32018-11-15 17:45:46 -0800198 result |= load_key((path + OS_PATH_SEPARATOR + name));
Josh Gao22cb70b2016-08-18 22:00:12 -0700199 }
200 return result;
201 }
202
Elliott Hughes758a27d2020-03-07 12:51:00 -0800203 LOG(ERROR) << "load_keys: unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
Josh Gao22cb70b2016-08-18 22:00:12 -0700204 return false;
205}
206
Elliott Hughes801066a2016-06-29 17:42:01 -0700207static std::string get_user_key_path() {
Josh Gao62ff9d42016-08-30 15:23:35 -0700208 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
Benoit Goby2cc19e42012-04-12 12:23:49 -0700209}
210
Elliott Hughes3b1ff092019-10-07 08:21:58 -0700211static bool load_userkey() {
Elliott Hughes801066a2016-06-29 17:42:01 -0700212 std::string path = get_user_key_path();
213 if (path.empty()) {
214 PLOG(ERROR) << "Error getting user key filename";
215 return false;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700216 }
217
Elliott Hughes801066a2016-06-29 17:42:01 -0700218 struct stat buf;
219 if (stat(path.c_str(), &buf) == -1) {
220 LOG(INFO) << "User key '" << path << "' does not exist...";
Dan Albert3d978e62015-07-09 20:35:09 +0000221 if (!generate_key(path)) {
Elliott Hughes801066a2016-06-29 17:42:01 -0700222 LOG(ERROR) << "Failed to generate new key";
223 return false;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700224 }
225 }
226
Josh Gao13102c32018-11-15 17:45:46 -0800227 return load_key(path);
Benoit Goby2cc19e42012-04-12 12:23:49 -0700228}
229
Josh Gao22cb70b2016-08-18 22:00:12 -0700230static std::set<std::string> get_vendor_keys() {
Elliott Hughesfb2ba512015-04-24 23:02:00 -0700231 const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
232 if (adb_keys_path == nullptr) {
Josh Gao22cb70b2016-08-18 22:00:12 -0700233 return std::set<std::string>();
Elliott Hughesfb2ba512015-04-24 23:02:00 -0700234 }
Benoit Goby2cc19e42012-04-12 12:23:49 -0700235
Josh Gao22cb70b2016-08-18 22:00:12 -0700236 std::set<std::string> result;
Elliott Hughes85952832015-10-07 15:59:35 -0700237 for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
Josh Gao22cb70b2016-08-18 22:00:12 -0700238 result.emplace(path);
Benoit Goby2cc19e42012-04-12 12:23:49 -0700239 }
Josh Gao22cb70b2016-08-18 22:00:12 -0700240 return result;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700241}
242
Josh Gao22cb70b2016-08-18 22:00:12 -0700243std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
244 std::deque<std::shared_ptr<RSA>> result;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700245
Josh Gao22cb70b2016-08-18 22:00:12 -0700246 // Copy all the currently known keys.
247 std::lock_guard<std::mutex> lock(g_keys_mutex);
248 for (const auto& it : g_keys) {
249 result.push_back(it.second);
Elliott Hughes801066a2016-06-29 17:42:01 -0700250 }
251
252 // Add a sentinel to the list. Our caller uses this to mean "out of private keys,
253 // but try using the public key" (the empty deque could otherwise mean this _or_
254 // that this function hasn't been called yet to request the keys).
255 result.push_back(nullptr);
256
257 return result;
258}
259
Josh Gao839b9322018-02-05 18:49:10 -0800260static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) {
Sami Tolvanenb92a35c2015-01-27 16:48:35 +0000261 if (token_size != TOKEN_SIZE) {
Yabin Cui815ad882015-09-02 17:44:28 -0700262 D("Unexpected token size %zd", token_size);
Ryan Prichardecff26f2024-01-05 13:54:36 -0800263 return std::string();
Sami Tolvanenb92a35c2015-01-27 16:48:35 +0000264 }
265
Josh Gao839b9322018-02-05 18:49:10 -0800266 std::string result;
267 result.resize(MAX_PAYLOAD);
268
Elliott Hughes801066a2016-06-29 17:42:01 -0700269 unsigned int len;
Josh Gao67ac3792016-10-06 13:31:44 -0700270 if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
Josh Gao839b9322018-02-05 18:49:10 -0800271 reinterpret_cast<uint8_t*>(&result[0]), &len, key)) {
272 return std::string();
Benoit Goby2cc19e42012-04-12 12:23:49 -0700273 }
274
Josh Gao839b9322018-02-05 18:49:10 -0800275 result.resize(len);
276
Yabin Cui815ad882015-09-02 17:44:28 -0700277 D("adb_auth_sign len=%d", len);
Josh Gao839b9322018-02-05 18:49:10 -0800278 return result;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700279}
280
Josh Gao13102c32018-11-15 17:45:46 -0800281static bool pubkey_from_privkey(std::string* out, const std::string& path) {
282 std::shared_ptr<RSA> privkey = read_key_file(path);
283 if (!privkey) {
284 return false;
285 }
Joshua Duong090c8072019-12-19 16:36:30 -0800286 return CalculatePublicKey(out, privkey.get());
Josh Gao13102c32018-11-15 17:45:46 -0800287}
288
Joshua Duong290ccb52019-11-20 14:18:43 -0800289bssl::UniquePtr<EVP_PKEY> adb_auth_get_user_privkey() {
290 std::string path = get_user_key_path();
291 if (path.empty()) {
292 PLOG(ERROR) << "Error getting user key filename";
293 return nullptr;
294 }
295
296 std::shared_ptr<RSA> rsa_privkey = read_key_file(path);
297 if (!rsa_privkey) {
298 return nullptr;
299 }
300
301 bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new());
302 if (!pkey) {
303 LOG(ERROR) << "Failed to allocate key";
304 return nullptr;
305 }
306
307 EVP_PKEY_set1_RSA(pkey.get(), rsa_privkey.get());
308 return pkey;
309}
310
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700311std::string adb_auth_get_userkey() {
Elliott Hughes801066a2016-06-29 17:42:01 -0700312 std::string path = get_user_key_path();
313 if (path.empty()) {
314 PLOG(ERROR) << "Error getting user key filename";
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700315 return "";
Benoit Goby2cc19e42012-04-12 12:23:49 -0700316 }
Benoit Goby2cc19e42012-04-12 12:23:49 -0700317
Josh Gao13102c32018-11-15 17:45:46 -0800318 std::string result;
319 if (!pubkey_from_privkey(&result, path)) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700320 return "";
Benoit Goby2cc19e42012-04-12 12:23:49 -0700321 }
Josh Gao13102c32018-11-15 17:45:46 -0800322 return result;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700323}
324
Nick Kralevich6183c962014-11-13 15:17:29 -0800325int adb_auth_keygen(const char* filename) {
Joshua Duong090c8072019-12-19 16:36:30 -0800326 return !generate_key(filename);
Nick Kralevich6183c962014-11-13 15:17:29 -0800327}
328
Josh Gao13102c32018-11-15 17:45:46 -0800329int adb_auth_pubkey(const char* filename) {
330 std::string pubkey;
331 if (!pubkey_from_privkey(&pubkey, filename)) {
332 return 1;
333 }
Nikita Pustovoi763ab7b2022-11-14 13:44:12 +1300334 fprintf(stdout, "%s\n", pubkey.data());
335 return 0;
Josh Gao13102c32018-11-15 17:45:46 -0800336}
337
Josh Gao22cb70b2016-08-18 22:00:12 -0700338#if defined(__linux__)
339static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
340 LOG(INFO) << "adb_auth_inotify_update called";
341 if (!(fd_event & FDE_READ)) {
342 return;
343 }
344
345 char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
346 while (true) {
347 ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
348 if (rc == -1) {
349 if (errno == EAGAIN) {
350 LOG(INFO) << "done reading inotify fd";
351 break;
352 }
353 PLOG(FATAL) << "read of inotify event failed";
354 }
355
356 // The read potentially returned multiple events.
357 char* start = buf;
358 char* end = buf + rc;
359
360 while (start < end) {
361 inotify_event* event = reinterpret_cast<inotify_event*>(start);
362 auto root_it = g_monitored_paths.find(event->wd);
363 if (root_it == g_monitored_paths.end()) {
364 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
365 }
366
367 std::string path = root_it->second;
368 if (event->len > 0) {
369 path += '/';
370 path += event->name;
371 }
372
373 if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
374 if (event->mask & IN_ISDIR) {
375 LOG(INFO) << "ignoring new directory at '" << path << "'";
376 } else {
377 LOG(INFO) << "observed new file at '" << path << "'";
Josh Gao13102c32018-11-15 17:45:46 -0800378 load_keys(path, false);
Josh Gao22cb70b2016-08-18 22:00:12 -0700379 }
380 } else {
381 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
382 << event->mask;
383 }
384
385 start += sizeof(struct inotify_event) + event->len;
386 }
387 }
388}
389
390static void adb_auth_inotify_init(const std::set<std::string>& paths) {
391 LOG(INFO) << "adb_auth_inotify_init...";
Josh Gao6946f112017-01-18 18:14:17 -0800392
Josh Gao22cb70b2016-08-18 22:00:12 -0700393 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
Josh Gao6946f112017-01-18 18:14:17 -0800394 if (infd < 0) {
395 PLOG(ERROR) << "failed to create inotify fd";
396 return;
397 }
398
Josh Gao22cb70b2016-08-18 22:00:12 -0700399 for (const std::string& path : paths) {
400 int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
401 if (wd < 0) {
Elliott Hughesabdf4c52020-07-15 11:55:40 -0700402 PLOG(ERROR) << "failed to inotify_add_watch on path '" << path << "'";
Josh Gao22cb70b2016-08-18 22:00:12 -0700403 continue;
404 }
405
406 g_monitored_paths[wd] = path;
Elliott Hughesabdf4c52020-07-15 11:55:40 -0700407 LOG(INFO) << "watch descriptor " << wd << " registered for '" << path << "'";
Josh Gao22cb70b2016-08-18 22:00:12 -0700408 }
409
410 fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
411 fdevent_add(event, FDE_READ);
412}
413#endif
414
Elliott Hughes801066a2016-06-29 17:42:01 -0700415void adb_auth_init() {
416 LOG(INFO) << "adb_auth_init...";
Benoit Goby2cc19e42012-04-12 12:23:49 -0700417
Elliott Hughes3b1ff092019-10-07 08:21:58 -0700418 if (!load_userkey()) {
419 LOG(ERROR) << "Failed to load (or generate) user key";
Benoit Goby2cc19e42012-04-12 12:23:49 -0700420 return;
421 }
422
Josh Gao22cb70b2016-08-18 22:00:12 -0700423 const auto& key_paths = get_vendor_keys();
424
425#if defined(__linux__)
426 adb_auth_inotify_init(key_paths);
427#endif
428
429 for (const std::string& path : key_paths) {
Greg Kaisere2f32342019-03-26 11:58:53 -0700430 load_keys(path);
Josh Gao22cb70b2016-08-18 22:00:12 -0700431 }
Benoit Goby2cc19e42012-04-12 12:23:49 -0700432}
Josh Gaoeac20582016-10-05 19:02:29 -0700433
434static void send_auth_publickey(atransport* t) {
435 LOG(INFO) << "Calling send_auth_publickey";
436
437 std::string key = adb_auth_get_userkey();
438 if (key.empty()) {
439 D("Failed to get user public key");
440 return;
441 }
442
443 if (key.size() >= MAX_PAYLOAD_V1) {
444 D("User public key too large (%zu B)", key.size());
445 return;
446 }
447
448 apacket* p = get_apacket();
Josh Gaoeac20582016-10-05 19:02:29 -0700449 p->msg.command = A_AUTH;
450 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
451
452 // adbd expects a null-terminated string.
Josh Gaocd2a5292018-03-07 16:52:28 -0800453 p->payload.assign(key.data(), key.data() + key.size() + 1);
Josh Gao839b9322018-02-05 18:49:10 -0800454 p->msg.data_length = p->payload.size();
Josh Gaoeac20582016-10-05 19:02:29 -0700455 send_packet(p, t);
456}
457
Josh Gao67ac3792016-10-06 13:31:44 -0700458void send_auth_response(const char* token, size_t token_size, atransport* t) {
Josh Gaoeac20582016-10-05 19:02:29 -0700459 std::shared_ptr<RSA> key = t->NextKey();
460 if (key == nullptr) {
461 // No more private keys to try, send the public key.
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700462 t->SetConnectionState(kCsUnauthorized);
Josh Gao597044d2018-08-08 16:20:14 -0700463 t->SetConnectionEstablished(true);
Josh Gaoeac20582016-10-05 19:02:29 -0700464 send_auth_publickey(t);
465 return;
466 }
467
468 LOG(INFO) << "Calling send_auth_response";
469 apacket* p = get_apacket();
470
Josh Gao839b9322018-02-05 18:49:10 -0800471 std::string result = adb_auth_sign(key.get(), token, token_size);
472 if (result.empty()) {
Josh Gaoeac20582016-10-05 19:02:29 -0700473 D("Error signing the token");
474 put_apacket(p);
475 return;
476 }
477
478 p->msg.command = A_AUTH;
479 p->msg.arg0 = ADB_AUTH_SIGNATURE;
Josh Gaocd2a5292018-03-07 16:52:28 -0800480 p->payload.assign(result.begin(), result.end());
Josh Gao839b9322018-02-05 18:49:10 -0800481 p->msg.data_length = p->payload.size();
Josh Gaoeac20582016-10-05 19:02:29 -0700482 send_packet(p, t);
483}
Joshua Duong64fab752020-01-21 13:19:42 -0800484
485void adb_auth_tls_handshake(atransport* t) {
486 std::thread([t]() {
487 std::shared_ptr<RSA> key = t->Key();
488 if (key == nullptr) {
489 // Can happen if !auth_required
490 LOG(INFO) << "t->auth_key not set before handshake";
491 key = t->NextKey();
492 CHECK(key);
493 }
494
495 LOG(INFO) << "Attempting to TLS handshake";
496 bool success = t->connection()->DoTlsHandshake(key.get());
497 if (success) {
498 LOG(INFO) << "Handshake succeeded. Waiting for CNXN packet...";
499 } else {
500 LOG(INFO) << "Handshake failed. Kicking transport";
501 t->Kick();
502 }
503 }).detach();
504}
505
Joshua Duong77b8ff32020-04-16 15:58:19 -0700506// Callback given to SSL_set_cert_cb to select a certificate when server requests
507// for a certificate. This is where the server will give us a CA-issuer list, and
508// figure out if the server knows any of our public keys. We currently always return
509// 1 here to indicate success, since we always try a key here (in the case of no auth).
510// See https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_cert_cb
511// for more details.
Joshua Duong64fab752020-01-21 13:19:42 -0800512int adb_tls_set_certificate(SSL* ssl) {
513 LOG(INFO) << __func__;
514
515 const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
516 if (ca_list == nullptr) {
517 // Either the device doesn't know any keys, or !auth_required.
518 // So let's just try with the default certificate and see what happens.
519 LOG(INFO) << "No client CA list. Trying with default certificate.";
520 return 1;
521 }
522
523 const size_t num_cas = sk_X509_NAME_num(ca_list);
524 for (size_t i = 0; i < num_cas; ++i) {
525 auto* x509_name = sk_X509_NAME_value(ca_list, i);
526 auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
527 if (!adbFingerprint.has_value()) {
528 // This could be a real CA issuer. Unfortunately, we don't support
529 // it ATM.
530 continue;
531 }
532
533 LOG(INFO) << "Checking for fingerprint match [" << *adbFingerprint << "]";
534 auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
535 if (!encoded_key.has_value()) {
536 continue;
537 }
538 // Check against our list of encoded keys for a match
539 std::lock_guard<std::mutex> lock(g_keys_mutex);
540 auto rsa_priv_key = g_keys.find(*encoded_key);
541 if (rsa_priv_key != g_keys.end()) {
542 LOG(INFO) << "Got SHA256 match on a key";
543 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
544 CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
545 auto x509 = GenerateX509Certificate(evp_pkey.get());
546 auto x509_str = X509ToPEMString(x509.get());
547 auto evp_str = Key::ToPEMString(evp_pkey.get());
548 TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
549 return 1;
550 } else {
551 LOG(INFO) << "No match for [" << *adbFingerprint << "]";
552 }
553 }
554
555 // Let's just try with the default certificate anyways, because daemon might
556 // not require auth, even though it has a list of keys.
557 return 1;
558}