blob: 8738ce77a47c12a97135d1e3165d61051d625a20 [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());
Josh Gao2e671202016-08-18 22:00:12 -0700148 if (g_keys.find(fingerprint) != g_keys.end()) {
149 LOG(INFO) << "ignoring already-loaded key: " << file;
Josh Gao2e671202016-08-18 22:00:12 -0700150 } else {
Joshua Duong5cf78682020-01-21 13:19:42 -0800151 LOG(INFO) << "Loaded fingerprint=[" << SHA256BitsToHexString(fingerprint) << "]";
Josh Gao2dc4cab2018-11-15 17:45:46 -0800152 g_keys[fingerprint] = std::move(key);
Josh Gao2e671202016-08-18 22:00:12 -0700153 }
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) {
162 PLOG(ERROR) << "failed to stat '" << path << "'";
163 return false;
164 }
165
166 if (S_ISREG(st.st_mode)) {
Josh Gao2dc4cab2018-11-15 17:45:46 -0800167 return load_key(path);
Josh Gao2e671202016-08-18 22:00:12 -0700168 } else if (S_ISDIR(st.st_mode)) {
169 if (!allow_dir) {
170 // inotify isn't recursive. It would break expectations to load keys in nested
171 // directories but not monitor them for new keys.
172 LOG(WARNING) << "refusing to recurse into directory '" << path << "'";
173 return false;
174 }
175
176 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
177 if (!dir) {
178 PLOG(ERROR) << "failed to open directory '" << path << "'";
179 return false;
180 }
181
182 bool result = false;
183 while (struct dirent* dent = readdir(dir.get())) {
184 std::string name = dent->d_name;
185
186 // We can't use dent->d_type here because it's not available on Windows.
187 if (name == "." || name == "..") {
188 continue;
189 }
190
Josh Gaoa27666b2016-12-14 16:59:29 -0800191 if (!android::base::EndsWith(name, ".adb_key")) {
192 LOG(INFO) << "skipping non-adb_key '" << path << "/" << name << "'";
193 continue;
194 }
195
Josh Gao2dc4cab2018-11-15 17:45:46 -0800196 result |= load_key((path + OS_PATH_SEPARATOR + name));
Josh Gao2e671202016-08-18 22:00:12 -0700197 }
198 return result;
199 }
200
201 LOG(ERROR) << "unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
202 return false;
203}
204
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700205static std::string get_user_key_path() {
Josh Gaoe0b75022016-08-30 15:23:35 -0700206 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700207}
208
Elliott Hughes7fb14072019-10-07 08:21:58 -0700209static bool load_userkey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700210 std::string path = get_user_key_path();
211 if (path.empty()) {
212 PLOG(ERROR) << "Error getting user key filename";
213 return false;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700214 }
215
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700216 struct stat buf;
217 if (stat(path.c_str(), &buf) == -1) {
218 LOG(INFO) << "User key '" << path << "' does not exist...";
Dan Albert286bb6d2015-07-09 20:35:09 +0000219 if (!generate_key(path)) {
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700220 LOG(ERROR) << "Failed to generate new key";
221 return false;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700222 }
223 }
224
Josh Gao2dc4cab2018-11-15 17:45:46 -0800225 return load_key(path);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700226}
227
Josh Gao2e671202016-08-18 22:00:12 -0700228static std::set<std::string> get_vendor_keys() {
Elliott Hughes8d5fa6d2015-04-24 23:02:00 -0700229 const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
230 if (adb_keys_path == nullptr) {
Josh Gao2e671202016-08-18 22:00:12 -0700231 return std::set<std::string>();
Elliott Hughes8d5fa6d2015-04-24 23:02:00 -0700232 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700233
Josh Gao2e671202016-08-18 22:00:12 -0700234 std::set<std::string> result;
Elliott Hughes65fe2512015-10-07 15:59:35 -0700235 for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
Josh Gao2e671202016-08-18 22:00:12 -0700236 result.emplace(path);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700237 }
Josh Gao2e671202016-08-18 22:00:12 -0700238 return result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700239}
240
Josh Gao2e671202016-08-18 22:00:12 -0700241std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
242 std::deque<std::shared_ptr<RSA>> result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700243
Josh Gao2e671202016-08-18 22:00:12 -0700244 // Copy all the currently known keys.
245 std::lock_guard<std::mutex> lock(g_keys_mutex);
246 for (const auto& it : g_keys) {
247 result.push_back(it.second);
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700248 }
249
250 // Add a sentinel to the list. Our caller uses this to mean "out of private keys,
251 // but try using the public key" (the empty deque could otherwise mean this _or_
252 // that this function hasn't been called yet to request the keys).
253 result.push_back(nullptr);
254
255 return result;
256}
257
Josh Gaof571fcb2018-02-05 18:49:10 -0800258static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) {
Sami Tolvanen7b9c20d2015-01-27 16:48:35 +0000259 if (token_size != TOKEN_SIZE) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700260 D("Unexpected token size %zd", token_size);
Yi Kongaed415c2018-07-13 18:15:16 -0700261 return nullptr;
Sami Tolvanen7b9c20d2015-01-27 16:48:35 +0000262 }
263
Josh Gaof571fcb2018-02-05 18:49:10 -0800264 std::string result;
265 result.resize(MAX_PAYLOAD);
266
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700267 unsigned int len;
Josh Gao06d61d42016-10-06 13:31:44 -0700268 if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
Josh Gaof571fcb2018-02-05 18:49:10 -0800269 reinterpret_cast<uint8_t*>(&result[0]), &len, key)) {
270 return std::string();
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700271 }
272
Josh Gaof571fcb2018-02-05 18:49:10 -0800273 result.resize(len);
274
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700275 D("adb_auth_sign len=%d", len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800276 return result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700277}
278
Josh Gao2dc4cab2018-11-15 17:45:46 -0800279static bool pubkey_from_privkey(std::string* out, const std::string& path) {
280 std::shared_ptr<RSA> privkey = read_key_file(path);
281 if (!privkey) {
282 return false;
283 }
Joshua Duongef28ca42019-12-19 16:36:30 -0800284 return CalculatePublicKey(out, privkey.get());
Josh Gao2dc4cab2018-11-15 17:45:46 -0800285}
286
Joshua Duongd85f5c02019-11-20 14:18:43 -0800287bssl::UniquePtr<EVP_PKEY> adb_auth_get_user_privkey() {
288 std::string path = get_user_key_path();
289 if (path.empty()) {
290 PLOG(ERROR) << "Error getting user key filename";
291 return nullptr;
292 }
293
294 std::shared_ptr<RSA> rsa_privkey = read_key_file(path);
295 if (!rsa_privkey) {
296 return nullptr;
297 }
298
299 bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new());
300 if (!pkey) {
301 LOG(ERROR) << "Failed to allocate key";
302 return nullptr;
303 }
304
305 EVP_PKEY_set1_RSA(pkey.get(), rsa_privkey.get());
306 return pkey;
307}
308
Elliott Hughese8b663f2016-05-26 22:43:19 -0700309std::string adb_auth_get_userkey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700310 std::string path = get_user_key_path();
311 if (path.empty()) {
312 PLOG(ERROR) << "Error getting user key filename";
Elliott Hughese8b663f2016-05-26 22:43:19 -0700313 return "";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700314 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700315
Josh Gao2dc4cab2018-11-15 17:45:46 -0800316 std::string result;
317 if (!pubkey_from_privkey(&result, path)) {
Elliott Hughese8b663f2016-05-26 22:43:19 -0700318 return "";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700319 }
Josh Gao2dc4cab2018-11-15 17:45:46 -0800320 return result;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700321}
322
Nick Kralevichbea3f9c2014-11-13 15:17:29 -0800323int adb_auth_keygen(const char* filename) {
Joshua Duongef28ca42019-12-19 16:36:30 -0800324 return !generate_key(filename);
Nick Kralevichbea3f9c2014-11-13 15:17:29 -0800325}
326
Josh Gao2dc4cab2018-11-15 17:45:46 -0800327int adb_auth_pubkey(const char* filename) {
328 std::string pubkey;
329 if (!pubkey_from_privkey(&pubkey, filename)) {
330 return 1;
331 }
332 pubkey.push_back('\n');
333
334 return WriteFdExactly(STDOUT_FILENO, pubkey.data(), pubkey.size()) ? 0 : 1;
335}
336
Josh Gao2e671202016-08-18 22:00:12 -0700337#if defined(__linux__)
338static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
339 LOG(INFO) << "adb_auth_inotify_update called";
340 if (!(fd_event & FDE_READ)) {
341 return;
342 }
343
344 char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
345 while (true) {
346 ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
347 if (rc == -1) {
348 if (errno == EAGAIN) {
349 LOG(INFO) << "done reading inotify fd";
350 break;
351 }
352 PLOG(FATAL) << "read of inotify event failed";
353 }
354
355 // The read potentially returned multiple events.
356 char* start = buf;
357 char* end = buf + rc;
358
359 while (start < end) {
360 inotify_event* event = reinterpret_cast<inotify_event*>(start);
361 auto root_it = g_monitored_paths.find(event->wd);
362 if (root_it == g_monitored_paths.end()) {
363 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
364 }
365
366 std::string path = root_it->second;
367 if (event->len > 0) {
368 path += '/';
369 path += event->name;
370 }
371
372 if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
373 if (event->mask & IN_ISDIR) {
374 LOG(INFO) << "ignoring new directory at '" << path << "'";
375 } else {
376 LOG(INFO) << "observed new file at '" << path << "'";
Josh Gao2dc4cab2018-11-15 17:45:46 -0800377 load_keys(path, false);
Josh Gao2e671202016-08-18 22:00:12 -0700378 }
379 } else {
380 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
381 << event->mask;
382 }
383
384 start += sizeof(struct inotify_event) + event->len;
385 }
386 }
387}
388
389static void adb_auth_inotify_init(const std::set<std::string>& paths) {
390 LOG(INFO) << "adb_auth_inotify_init...";
Josh Gaofb9a7e52017-01-18 18:14:17 -0800391
Josh Gao2e671202016-08-18 22:00:12 -0700392 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
Josh Gaofb9a7e52017-01-18 18:14:17 -0800393 if (infd < 0) {
394 PLOG(ERROR) << "failed to create inotify fd";
395 return;
396 }
397
Josh Gao2e671202016-08-18 22:00:12 -0700398 for (const std::string& path : paths) {
399 int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
400 if (wd < 0) {
401 PLOG(ERROR) << "failed to inotify_add_watch on path '" << path;
402 continue;
403 }
404
405 g_monitored_paths[wd] = path;
406 LOG(INFO) << "watch descriptor " << wd << " registered for " << path;
407 }
408
409 fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
410 fdevent_add(event, FDE_READ);
411}
412#endif
413
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700414void adb_auth_init() {
415 LOG(INFO) << "adb_auth_init...";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700416
Elliott Hughes7fb14072019-10-07 08:21:58 -0700417 if (!load_userkey()) {
418 LOG(ERROR) << "Failed to load (or generate) user key";
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700419 return;
420 }
421
Josh Gao2e671202016-08-18 22:00:12 -0700422 const auto& key_paths = get_vendor_keys();
423
424#if defined(__linux__)
425 adb_auth_inotify_init(key_paths);
426#endif
427
428 for (const std::string& path : key_paths) {
Greg Kaisere2125fd2019-03-26 11:58:53 -0700429 load_keys(path);
Josh Gao2e671202016-08-18 22:00:12 -0700430 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700431}
Josh Gao3bd28792016-10-05 19:02:29 -0700432
433static void send_auth_publickey(atransport* t) {
434 LOG(INFO) << "Calling send_auth_publickey";
435
436 std::string key = adb_auth_get_userkey();
437 if (key.empty()) {
438 D("Failed to get user public key");
439 return;
440 }
441
442 if (key.size() >= MAX_PAYLOAD_V1) {
443 D("User public key too large (%zu B)", key.size());
444 return;
445 }
446
447 apacket* p = get_apacket();
Josh Gao3bd28792016-10-05 19:02:29 -0700448 p->msg.command = A_AUTH;
449 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
450
451 // adbd expects a null-terminated string.
Josh Gao1ce99572018-03-07 16:52:28 -0800452 p->payload.assign(key.data(), key.data() + key.size() + 1);
Josh Gaof571fcb2018-02-05 18:49:10 -0800453 p->msg.data_length = p->payload.size();
Josh Gao3bd28792016-10-05 19:02:29 -0700454 send_packet(p, t);
455}
456
Josh Gao06d61d42016-10-06 13:31:44 -0700457void send_auth_response(const char* token, size_t token_size, atransport* t) {
Josh Gao3bd28792016-10-05 19:02:29 -0700458 std::shared_ptr<RSA> key = t->NextKey();
459 if (key == nullptr) {
460 // No more private keys to try, send the public key.
Josh Gao704494b2018-05-04 16:04:49 -0700461 t->SetConnectionState(kCsUnauthorized);
Josh Gao362e6962018-08-08 16:20:14 -0700462 t->SetConnectionEstablished(true);
Josh Gao3bd28792016-10-05 19:02:29 -0700463 send_auth_publickey(t);
464 return;
465 }
466
467 LOG(INFO) << "Calling send_auth_response";
468 apacket* p = get_apacket();
469
Josh Gaof571fcb2018-02-05 18:49:10 -0800470 std::string result = adb_auth_sign(key.get(), token, token_size);
471 if (result.empty()) {
Josh Gao3bd28792016-10-05 19:02:29 -0700472 D("Error signing the token");
473 put_apacket(p);
474 return;
475 }
476
477 p->msg.command = A_AUTH;
478 p->msg.arg0 = ADB_AUTH_SIGNATURE;
Josh Gao1ce99572018-03-07 16:52:28 -0800479 p->payload.assign(result.begin(), result.end());
Josh Gaof571fcb2018-02-05 18:49:10 -0800480 p->msg.data_length = p->payload.size();
Josh Gao3bd28792016-10-05 19:02:29 -0700481 send_packet(p, t);
482}
Joshua Duong5cf78682020-01-21 13:19:42 -0800483
484void adb_auth_tls_handshake(atransport* t) {
485 std::thread([t]() {
486 std::shared_ptr<RSA> key = t->Key();
487 if (key == nullptr) {
488 // Can happen if !auth_required
489 LOG(INFO) << "t->auth_key not set before handshake";
490 key = t->NextKey();
491 CHECK(key);
492 }
493
494 LOG(INFO) << "Attempting to TLS handshake";
495 bool success = t->connection()->DoTlsHandshake(key.get());
496 if (success) {
497 LOG(INFO) << "Handshake succeeded. Waiting for CNXN packet...";
498 } else {
499 LOG(INFO) << "Handshake failed. Kicking transport";
500 t->Kick();
501 }
502 }).detach();
503}
504
505int adb_tls_set_certificate(SSL* ssl) {
506 LOG(INFO) << __func__;
507
508 const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
509 if (ca_list == nullptr) {
510 // Either the device doesn't know any keys, or !auth_required.
511 // So let's just try with the default certificate and see what happens.
512 LOG(INFO) << "No client CA list. Trying with default certificate.";
513 return 1;
514 }
515
516 const size_t num_cas = sk_X509_NAME_num(ca_list);
517 for (size_t i = 0; i < num_cas; ++i) {
518 auto* x509_name = sk_X509_NAME_value(ca_list, i);
519 auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
520 if (!adbFingerprint.has_value()) {
521 // This could be a real CA issuer. Unfortunately, we don't support
522 // it ATM.
523 continue;
524 }
525
526 LOG(INFO) << "Checking for fingerprint match [" << *adbFingerprint << "]";
527 auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
528 if (!encoded_key.has_value()) {
529 continue;
530 }
531 // Check against our list of encoded keys for a match
532 std::lock_guard<std::mutex> lock(g_keys_mutex);
533 auto rsa_priv_key = g_keys.find(*encoded_key);
534 if (rsa_priv_key != g_keys.end()) {
535 LOG(INFO) << "Got SHA256 match on a key";
536 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
537 CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
538 auto x509 = GenerateX509Certificate(evp_pkey.get());
539 auto x509_str = X509ToPEMString(x509.get());
540 auto evp_str = Key::ToPEMString(evp_pkey.get());
541 TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
542 return 1;
543 } else {
544 LOG(INFO) << "No match for [" << *adbFingerprint << "]";
545 }
546 }
547
548 // Let's just try with the default certificate anyways, because daemon might
549 // not require auth, even though it has a list of keys.
550 return 1;
551}