blob: 4b2fa0423d66499b4655c56c05aded005d77e3bd [file] [log] [blame]
Benoit Gobyd5fcafa2012-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 Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG AUTH
Dan Albert33134262015-03-19 15:21:08 -070018
Josh Gao2e671202016-08-18 22:00:12 -070019#include <dirent.h>
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070020#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080021#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070022#include <string.h>
Josh Gao2e671202016-08-18 22:00:12 -070023#if defined(__linux__)
24#include <sys/inotify.h>
25#endif
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070026
Josh Gao2e671202016-08-18 22:00:12 -070027#include <map>
Elliott Hughes0aeb5052016-06-29 17:42:01 -070028#include <mutex>
Josh Gao2e671202016-08-18 22:00:12 -070029#include <set>
30#include <string>
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070031
Joshua Duongef28ca42019-12-19 16:36:30 -080032#include <adb/crypto/rsa_2048_key.h>
Joshua Duong5cf78682020-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 Pursell5f787ed2016-01-27 08:52:53 -080036#include <android-base/errors.h>
Elliott Hughese8b663f2016-05-26 22:43:19 -070037#include <android-base/file.h>
Yurii Zubrytskyidace0152016-05-26 09:46:10 -070038#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080039#include <android-base/strings.h>
Mattias Nissler097b6bb2016-03-31 16:32:09 +020040#include <crypto_utils/android_pubkey.h>
Elliott Hughes625faf02016-06-21 16:50:48 -070041#include <openssl/base64.h>
Benoit Gobyd5fcafa2012-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 Gao2e671202016-08-18 22:00:12 -070048#include "adb.h"
49#include "adb_auth.h"
Josh Gao2dc4cab2018-11-15 17:45:46 -080050#include "adb_io.h"
Josh Gao2e671202016-08-18 22:00:12 -070051#include "adb_utils.h"
52#include "sysdeps.h"
Josh Gao3bd28792016-10-05 19:02:29 -070053#include "transport.h"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070054
Josh Gao2e671202016-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 Gobyd5fcafa2012-04-12 12:23:49 -070059
Joshua Duongef28ca42019-12-19 16:36:30 -080060using namespace adb::crypto;
Joshua Duong5cf78682020-01-21 13:19:42 -080061using namespace adb::tls;
Josh Gao032989a2019-04-29 12:36:32 -070062
Joshua Duongef28ca42019-12-19 16:36:30 -080063static bool generate_key(const std::string& file) {
Elliott Hughes0aeb5052016-06-29 17:42:01 -070064 LOG(INFO) << "generate_key(" << file << ")...";
65
Joshua Duongef28ca42019-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 Gao032989a2019-04-29 12:36:32 -070071 std::string pubkey;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070072
Joshua Duongef28ca42019-12-19 16:36:30 -080073 RSA* rsa = EVP_PKEY_get0_RSA(rsa_2048->GetEvpPkey());
74 CHECK(rsa);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070075
Joshua Duongef28ca42019-12-19 16:36:30 -080076 if (!CalculatePublicKey(&pubkey, rsa)) {
Josh Gao032989a2019-04-29 12:36:32 -070077 LOG(ERROR) << "failed to calculate public key";
Joshua Duongef28ca42019-12-19 16:36:30 -080078 return false;
Josh Gao032989a2019-04-29 12:36:32 -070079 }
80
Joshua Duongef28ca42019-12-19 16:36:30 -080081 mode_t old_mask = umask(077);
Benoit Goby64b31032012-08-31 12:14:21 -070082
Joshua Duongef28ca42019-12-19 16:36:30 -080083 std::unique_ptr<FILE, decltype(&fclose)> f(nullptr, &fclose);
84 f.reset(fopen(file.c_str(), "w"));
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070085 if (!f) {
Elliott Hughes0aeb5052016-06-29 17:42:01 -070086 PLOG(ERROR) << "Failed to open " << file;
Benoit Goby64b31032012-08-31 12:14:21 -070087 umask(old_mask);
Joshua Duongef28ca42019-12-19 16:36:30 -080088 return false;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070089 }
90
Benoit Goby64b31032012-08-31 12:14:21 -070091 umask(old_mask);
92
Joshua Duongef28ca42019-12-19 16:36:30 -080093 if (!PEM_write_PrivateKey(f.get(), rsa_2048->GetEvpPkey(), nullptr, nullptr, 0, nullptr,
94 nullptr)) {
Josh Gao032989a2019-04-29 12:36:32 -070095 LOG(ERROR) << "Failed to write key";
Joshua Duongef28ca42019-12-19 16:36:30 -080096 return false;
Josh Gao032989a2019-04-29 12:36:32 -070097 }
98
99 if (!android::base::WriteStringToFile(pubkey, file + ".pub")) {
100 PLOG(ERROR) << "failed to write public key";
Joshua Duongef28ca42019-12-19 16:36:30 -0800101 return false;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700102 }
103
Joshua Duongef28ca42019-12-19 16:36:30 -0800104 return true;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700105}
106
Josh Gao2e671202016-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 Gao2dc4cab2018-11-15 17:45:46 -0800122static std::shared_ptr<RSA> read_key_file(const std::string& file) {
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700123 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
Elliott Hughes8d5fa6d2015-04-24 23:02:00 -0700124 if (!fp) {
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700125 PLOG(ERROR) << "Failed to open '" << file << "'";
Josh Gao2dc4cab2018-11-15 17:45:46 -0800126 return nullptr;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700127 }
128
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700129 RSA* key = RSA_new();
130 if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
Elliott Hughes7fb14072019-10-07 08:21:58 -0700131 LOG(ERROR) << "Failed to read key from '" << file << "'";
132 ERR_print_errors_fp(stderr);
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700133 RSA_free(key);
Josh Gao2dc4cab2018-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 Hughes0aeb5052016-06-29 17:42:01 -0700143 return false;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700144 }
145
Josh Gao2e671202016-08-18 22:00:12 -0700146 std::lock_guard<std::mutex> lock(g_keys_mutex);
Josh Gao2dc4cab2018-11-15 17:45:46 -0800147 std::string fingerprint = hash_key(key.get());
Elliott Hughes401c7872020-03-07 12:51:00 -0800148 bool already_loaded = (g_keys.find(fingerprint) != g_keys.end());
149 if (!already_loaded) {
Josh Gao2dc4cab2018-11-15 17:45:46 -0800150 g_keys[fingerprint] = std::move(key);
Josh Gao2e671202016-08-18 22:00:12 -0700151 }
Elliott Hughes401c7872020-03-07 12:51:00 -0800152 LOG(INFO) << (already_loaded ? "ignored already-loaded" : "loaded new") << " key from '" << file
153 << "' with fingerprint " << SHA256BitsToHexString(fingerprint);
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700154 return true;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700155}
156
Josh Gao2dc4cab2018-11-15 17:45:46 -0800157static bool load_keys(const std::string& path, bool allow_dir = true) {
158 LOG(INFO) << "load_keys '" << path << "'...";
Josh Gao2e671202016-08-18 22:00:12 -0700159
160 struct stat st;
161 if (stat(path.c_str(), &st) != 0) {
Elliott Hughes401c7872020-03-07 12:51:00 -0800162 PLOG(ERROR) << "load_keys: failed to stat '" << path << "'";
Josh Gao2e671202016-08-18 22:00:12 -0700163 return false;
164 }
165
166 if (S_ISREG(st.st_mode)) {
Josh Gao2dc4cab2018-11-15 17:45:46 -0800167 return load_key(path);
Elliott Hughes401c7872020-03-07 12:51:00 -0800168 }
169
170 if (S_ISDIR(st.st_mode)) {
Josh Gao2e671202016-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 Hughes401c7872020-03-07 12:51:00 -0800174 LOG(WARNING) << "load_keys: refusing to recurse into directory '" << path << "'";
Josh Gao2e671202016-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 Hughes401c7872020-03-07 12:51:00 -0800180 PLOG(ERROR) << "load_keys: failed to open directory '" << path << "'";
Josh Gao2e671202016-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 Gaoa27666b2016-12-14 16:59:29 -0800193 if (!android::base::EndsWith(name, ".adb_key")) {
Elliott Hughes401c7872020-03-07 12:51:00 -0800194 LOG(INFO) << "skipped non-adb_key '" << path << "/" << name << "'";
Josh Gaoa27666b2016-12-14 16:59:29 -0800195 continue;
196 }
197
Josh Gao2dc4cab2018-11-15 17:45:46 -0800198 result |= load_key((path + OS_PATH_SEPARATOR + name));
Josh Gao2e671202016-08-18 22:00:12 -0700199 }
200 return result;
201 }
202
Elliott Hughes401c7872020-03-07 12:51:00 -0800203 LOG(ERROR) << "load_keys: unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
Josh Gao2e671202016-08-18 22:00:12 -0700204 return false;
205}
206
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700207static std::string get_user_key_path() {
Josh Gaoe0b75022016-08-30 15:23:35 -0700208 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700209}
210
Elliott Hughes7fb14072019-10-07 08:21:58 -0700211static bool load_userkey() {
Elliott Hughes0aeb5052016-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 Gobyd5fcafa2012-04-12 12:23:49 -0700216 }
217
Elliott Hughes0aeb5052016-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 Albert286bb6d2015-07-09 20:35:09 +0000221 if (!generate_key(path)) {
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700222 LOG(ERROR) << "Failed to generate new key";
223 return false;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700224 }
225 }
226
Josh Gao2dc4cab2018-11-15 17:45:46 -0800227 return load_key(path);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700228}
229
Josh Gao2e671202016-08-18 22:00:12 -0700230static std::set<std::string> get_vendor_keys() {
Elliott Hughes8d5fa6d2015-04-24 23:02:00 -0700231 const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
232 if (adb_keys_path == nullptr) {
Josh Gao2e671202016-08-18 22:00:12 -0700233 return std::set<std::string>();
Elliott Hughes8d5fa6d2015-04-24 23:02:00 -0700234 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700235
Josh Gao2e671202016-08-18 22:00:12 -0700236 std::set<std::string> result;
Elliott Hughes65fe2512015-10-07 15:59:35 -0700237 for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
Josh Gao2e671202016-08-18 22:00:12 -0700238 result.emplace(path);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700239 }
Josh Gao2e671202016-08-18 22:00:12 -0700240 return result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700241}
242
Josh Gao2e671202016-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 Gobyd5fcafa2012-04-12 12:23:49 -0700245
Josh Gao2e671202016-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 Hughes0aeb5052016-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 Gaof571fcb2018-02-05 18:49:10 -0800260static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) {
Sami Tolvanen7b9c20d2015-01-27 16:48:35 +0000261 if (token_size != TOKEN_SIZE) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700262 D("Unexpected token size %zd", token_size);
Yi Kongaed415c2018-07-13 18:15:16 -0700263 return nullptr;
Sami Tolvanen7b9c20d2015-01-27 16:48:35 +0000264 }
265
Josh Gaof571fcb2018-02-05 18:49:10 -0800266 std::string result;
267 result.resize(MAX_PAYLOAD);
268
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700269 unsigned int len;
Josh Gao06d61d42016-10-06 13:31:44 -0700270 if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
Josh Gaof571fcb2018-02-05 18:49:10 -0800271 reinterpret_cast<uint8_t*>(&result[0]), &len, key)) {
272 return std::string();
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700273 }
274
Josh Gaof571fcb2018-02-05 18:49:10 -0800275 result.resize(len);
276
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700277 D("adb_auth_sign len=%d", len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800278 return result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700279}
280
Josh Gao2dc4cab2018-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 Duongef28ca42019-12-19 16:36:30 -0800286 return CalculatePublicKey(out, privkey.get());
Josh Gao2dc4cab2018-11-15 17:45:46 -0800287}
288
Joshua Duongd85f5c02019-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 Hughese8b663f2016-05-26 22:43:19 -0700311std::string adb_auth_get_userkey() {
Elliott Hughes0aeb5052016-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 Hughese8b663f2016-05-26 22:43:19 -0700315 return "";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700316 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700317
Josh Gao2dc4cab2018-11-15 17:45:46 -0800318 std::string result;
319 if (!pubkey_from_privkey(&result, path)) {
Elliott Hughese8b663f2016-05-26 22:43:19 -0700320 return "";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700321 }
Josh Gao2dc4cab2018-11-15 17:45:46 -0800322 return result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700323}
324
Nick Kralevichbea3f9c2014-11-13 15:17:29 -0800325int adb_auth_keygen(const char* filename) {
Joshua Duongef28ca42019-12-19 16:36:30 -0800326 return !generate_key(filename);
Nick Kralevichbea3f9c2014-11-13 15:17:29 -0800327}
328
Josh Gao2dc4cab2018-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 }
334 pubkey.push_back('\n');
335
336 return WriteFdExactly(STDOUT_FILENO, pubkey.data(), pubkey.size()) ? 0 : 1;
337}
338
Josh Gao2e671202016-08-18 22:00:12 -0700339#if defined(__linux__)
340static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
341 LOG(INFO) << "adb_auth_inotify_update called";
342 if (!(fd_event & FDE_READ)) {
343 return;
344 }
345
346 char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
347 while (true) {
348 ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
349 if (rc == -1) {
350 if (errno == EAGAIN) {
351 LOG(INFO) << "done reading inotify fd";
352 break;
353 }
354 PLOG(FATAL) << "read of inotify event failed";
355 }
356
357 // The read potentially returned multiple events.
358 char* start = buf;
359 char* end = buf + rc;
360
361 while (start < end) {
362 inotify_event* event = reinterpret_cast<inotify_event*>(start);
363 auto root_it = g_monitored_paths.find(event->wd);
364 if (root_it == g_monitored_paths.end()) {
365 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
366 }
367
368 std::string path = root_it->second;
369 if (event->len > 0) {
370 path += '/';
371 path += event->name;
372 }
373
374 if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
375 if (event->mask & IN_ISDIR) {
376 LOG(INFO) << "ignoring new directory at '" << path << "'";
377 } else {
378 LOG(INFO) << "observed new file at '" << path << "'";
Josh Gao2dc4cab2018-11-15 17:45:46 -0800379 load_keys(path, false);
Josh Gao2e671202016-08-18 22:00:12 -0700380 }
381 } else {
382 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
383 << event->mask;
384 }
385
386 start += sizeof(struct inotify_event) + event->len;
387 }
388 }
389}
390
391static void adb_auth_inotify_init(const std::set<std::string>& paths) {
392 LOG(INFO) << "adb_auth_inotify_init...";
Josh Gaofb9a7e52017-01-18 18:14:17 -0800393
Josh Gao2e671202016-08-18 22:00:12 -0700394 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
Josh Gaofb9a7e52017-01-18 18:14:17 -0800395 if (infd < 0) {
396 PLOG(ERROR) << "failed to create inotify fd";
397 return;
398 }
399
Josh Gao2e671202016-08-18 22:00:12 -0700400 for (const std::string& path : paths) {
401 int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
402 if (wd < 0) {
403 PLOG(ERROR) << "failed to inotify_add_watch on path '" << path;
404 continue;
405 }
406
407 g_monitored_paths[wd] = path;
408 LOG(INFO) << "watch descriptor " << wd << " registered for " << path;
409 }
410
411 fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
412 fdevent_add(event, FDE_READ);
413}
414#endif
415
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700416void adb_auth_init() {
417 LOG(INFO) << "adb_auth_init...";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700418
Elliott Hughes7fb14072019-10-07 08:21:58 -0700419 if (!load_userkey()) {
420 LOG(ERROR) << "Failed to load (or generate) user key";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700421 return;
422 }
423
Josh Gao2e671202016-08-18 22:00:12 -0700424 const auto& key_paths = get_vendor_keys();
425
426#if defined(__linux__)
427 adb_auth_inotify_init(key_paths);
428#endif
429
430 for (const std::string& path : key_paths) {
Greg Kaisere2125fd2019-03-26 11:58:53 -0700431 load_keys(path);
Josh Gao2e671202016-08-18 22:00:12 -0700432 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700433}
Josh Gao3bd28792016-10-05 19:02:29 -0700434
435static void send_auth_publickey(atransport* t) {
436 LOG(INFO) << "Calling send_auth_publickey";
437
438 std::string key = adb_auth_get_userkey();
439 if (key.empty()) {
440 D("Failed to get user public key");
441 return;
442 }
443
444 if (key.size() >= MAX_PAYLOAD_V1) {
445 D("User public key too large (%zu B)", key.size());
446 return;
447 }
448
449 apacket* p = get_apacket();
Josh Gao3bd28792016-10-05 19:02:29 -0700450 p->msg.command = A_AUTH;
451 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
452
453 // adbd expects a null-terminated string.
Josh Gao1ce99572018-03-07 16:52:28 -0800454 p->payload.assign(key.data(), key.data() + key.size() + 1);
Josh Gaof571fcb2018-02-05 18:49:10 -0800455 p->msg.data_length = p->payload.size();
Josh Gao3bd28792016-10-05 19:02:29 -0700456 send_packet(p, t);
457}
458
Josh Gao06d61d42016-10-06 13:31:44 -0700459void send_auth_response(const char* token, size_t token_size, atransport* t) {
Josh Gao3bd28792016-10-05 19:02:29 -0700460 std::shared_ptr<RSA> key = t->NextKey();
461 if (key == nullptr) {
462 // No more private keys to try, send the public key.
Josh Gao704494b2018-05-04 16:04:49 -0700463 t->SetConnectionState(kCsUnauthorized);
Josh Gao362e6962018-08-08 16:20:14 -0700464 t->SetConnectionEstablished(true);
Josh Gao3bd28792016-10-05 19:02:29 -0700465 send_auth_publickey(t);
466 return;
467 }
468
469 LOG(INFO) << "Calling send_auth_response";
470 apacket* p = get_apacket();
471
Josh Gaof571fcb2018-02-05 18:49:10 -0800472 std::string result = adb_auth_sign(key.get(), token, token_size);
473 if (result.empty()) {
Josh Gao3bd28792016-10-05 19:02:29 -0700474 D("Error signing the token");
475 put_apacket(p);
476 return;
477 }
478
479 p->msg.command = A_AUTH;
480 p->msg.arg0 = ADB_AUTH_SIGNATURE;
Josh Gao1ce99572018-03-07 16:52:28 -0800481 p->payload.assign(result.begin(), result.end());
Josh Gaof571fcb2018-02-05 18:49:10 -0800482 p->msg.data_length = p->payload.size();
Josh Gao3bd28792016-10-05 19:02:29 -0700483 send_packet(p, t);
484}
Joshua Duong5cf78682020-01-21 13:19:42 -0800485
486void adb_auth_tls_handshake(atransport* t) {
487 std::thread([t]() {
488 std::shared_ptr<RSA> key = t->Key();
489 if (key == nullptr) {
490 // Can happen if !auth_required
491 LOG(INFO) << "t->auth_key not set before handshake";
492 key = t->NextKey();
493 CHECK(key);
494 }
495
496 LOG(INFO) << "Attempting to TLS handshake";
497 bool success = t->connection()->DoTlsHandshake(key.get());
498 if (success) {
499 LOG(INFO) << "Handshake succeeded. Waiting for CNXN packet...";
500 } else {
501 LOG(INFO) << "Handshake failed. Kicking transport";
502 t->Kick();
503 }
504 }).detach();
505}
506
507int adb_tls_set_certificate(SSL* ssl) {
508 LOG(INFO) << __func__;
509
510 const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
511 if (ca_list == nullptr) {
512 // Either the device doesn't know any keys, or !auth_required.
513 // So let's just try with the default certificate and see what happens.
514 LOG(INFO) << "No client CA list. Trying with default certificate.";
515 return 1;
516 }
517
518 const size_t num_cas = sk_X509_NAME_num(ca_list);
519 for (size_t i = 0; i < num_cas; ++i) {
520 auto* x509_name = sk_X509_NAME_value(ca_list, i);
521 auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
522 if (!adbFingerprint.has_value()) {
523 // This could be a real CA issuer. Unfortunately, we don't support
524 // it ATM.
525 continue;
526 }
527
528 LOG(INFO) << "Checking for fingerprint match [" << *adbFingerprint << "]";
529 auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
530 if (!encoded_key.has_value()) {
531 continue;
532 }
533 // Check against our list of encoded keys for a match
534 std::lock_guard<std::mutex> lock(g_keys_mutex);
535 auto rsa_priv_key = g_keys.find(*encoded_key);
536 if (rsa_priv_key != g_keys.end()) {
537 LOG(INFO) << "Got SHA256 match on a key";
538 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
539 CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
540 auto x509 = GenerateX509Certificate(evp_pkey.get());
541 auto x509_str = X509ToPEMString(x509.get());
542 auto evp_str = Key::ToPEMString(evp_pkey.get());
543 TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
544 return 1;
545 } else {
546 LOG(INFO) << "No match for [" << *adbFingerprint << "]";
547 }
548 }
549
550 // Let's just try with the default certificate anyways, because daemon might
551 // not require auth, even though it has a list of keys.
552 return 1;
553}