1 /*
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
17 #define TRACE_TAG AUTH
18
19 #include <dirent.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #if defined(__linux__)
24 #include <sys/inotify.h>
25 #endif
26
27 #include <map>
28 #include <mutex>
29 #include <set>
30 #include <string>
31
32 #include <adb/crypto/rsa_2048_key.h>
33 #include <adb/crypto/x509_generator.h>
34 #include <adb/tls/adb_ca_list.h>
35 #include <adb/tls/tls_connection.h>
36 #include <android-base/errors.h>
37 #include <android-base/file.h>
38 #include <android-base/stringprintf.h>
39 #include <android-base/strings.h>
40 #include <crypto_utils/android_pubkey.h>
41 #include <openssl/base64.h>
42 #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
48 #include "adb.h"
49 #include "adb_auth.h"
50 #include "adb_io.h"
51 #include "adb_utils.h"
52 #include "sysdeps.h"
53 #include "transport.h"
54
55 static std::mutex& g_keys_mutex = *new std::mutex;
56 static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
57 *new std::map<std::string, std::shared_ptr<RSA>>;
58 static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;
59
60 using namespace adb::crypto;
61 using namespace adb::tls;
62
generate_key(const std::string & file)63 static bool generate_key(const std::string& file) {
64 LOG(INFO) << "generate_key(" << file << ")...";
65
66 auto rsa_2048 = CreateRSA2048Key();
67 if (!rsa_2048) {
68 LOG(ERROR) << "Unable to create key";
69 return false;
70 }
71 std::string pubkey;
72
73 RSA* rsa = EVP_PKEY_get0_RSA(rsa_2048->GetEvpPkey());
74 CHECK(rsa);
75
76 if (!CalculatePublicKey(&pubkey, rsa)) {
77 LOG(ERROR) << "failed to calculate public key";
78 return false;
79 }
80
81 mode_t old_mask = umask(077);
82
83 std::unique_ptr<FILE, decltype(&fclose)> f(nullptr, &fclose);
84 f.reset(fopen(file.c_str(), "w"));
85 if (!f) {
86 PLOG(ERROR) << "Failed to open " << file;
87 umask(old_mask);
88 return false;
89 }
90
91 umask(old_mask);
92
93 if (!PEM_write_PrivateKey(f.get(), rsa_2048->GetEvpPkey(), nullptr, nullptr, 0, nullptr,
94 nullptr)) {
95 LOG(ERROR) << "Failed to write key";
96 return false;
97 }
98
99 if (!android::base::WriteStringToFile(pubkey, file + ".pub")) {
100 PLOG(ERROR) << "failed to write public key";
101 return false;
102 }
103
104 return true;
105 }
106
hash_key(RSA * key)107 static 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
read_key_file(const std::string & file)122 static std::shared_ptr<RSA> read_key_file(const std::string& file) {
123 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
124 if (!fp) {
125 PLOG(ERROR) << "Failed to open '" << file << "'";
126 return nullptr;
127 }
128
129 RSA* key = RSA_new();
130 if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
131 LOG(ERROR) << "Failed to read key from '" << file << "'";
132 ERR_print_errors_fp(stderr);
133 RSA_free(key);
134 return nullptr;
135 }
136
137 return std::shared_ptr<RSA>(key, RSA_free);
138 }
139
load_key(const std::string & file)140 static bool load_key(const std::string& file) {
141 std::shared_ptr<RSA> key = read_key_file(file);
142 if (!key) {
143 return false;
144 }
145
146 std::lock_guard<std::mutex> lock(g_keys_mutex);
147 std::string fingerprint = hash_key(key.get());
148 bool already_loaded = (g_keys.find(fingerprint) != g_keys.end());
149 if (!already_loaded) {
150 g_keys[fingerprint] = std::move(key);
151 }
152 LOG(INFO) << (already_loaded ? "ignored already-loaded" : "loaded new") << " key from '" << file
153 << "' with fingerprint " << SHA256BitsToHexString(fingerprint);
154 return true;
155 }
156
load_keys(const std::string & path,bool allow_dir=true)157 static bool load_keys(const std::string& path, bool allow_dir = true) {
158 LOG(INFO) << "load_keys '" << path << "'...";
159
160 struct stat st;
161 if (stat(path.c_str(), &st) != 0) {
162 PLOG(ERROR) << "load_keys: failed to stat '" << path << "'";
163 return false;
164 }
165
166 if (S_ISREG(st.st_mode)) {
167 return load_key(path);
168 }
169
170 if (S_ISDIR(st.st_mode)) {
171 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.
174 LOG(WARNING) << "load_keys: refusing to recurse into directory '" << path << "'";
175 return false;
176 }
177
178 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
179 if (!dir) {
180 PLOG(ERROR) << "load_keys: failed to open directory '" << path << "'";
181 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
193 if (!android::base::EndsWith(name, ".adb_key")) {
194 LOG(INFO) << "skipped non-adb_key '" << path << "/" << name << "'";
195 continue;
196 }
197
198 result |= load_key((path + OS_PATH_SEPARATOR + name));
199 }
200 return result;
201 }
202
203 LOG(ERROR) << "load_keys: unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
204 return false;
205 }
206
get_user_key_path()207 static std::string get_user_key_path() {
208 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
209 }
210
load_userkey()211 static bool load_userkey() {
212 std::string path = get_user_key_path();
213 if (path.empty()) {
214 PLOG(ERROR) << "Error getting user key filename";
215 return false;
216 }
217
218 struct stat buf;
219 if (stat(path.c_str(), &buf) == -1) {
220 LOG(INFO) << "User key '" << path << "' does not exist...";
221 if (!generate_key(path)) {
222 LOG(ERROR) << "Failed to generate new key";
223 return false;
224 }
225 }
226
227 return load_key(path);
228 }
229
get_vendor_keys()230 static std::set<std::string> get_vendor_keys() {
231 const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
232 if (adb_keys_path == nullptr) {
233 return std::set<std::string>();
234 }
235
236 std::set<std::string> result;
237 for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
238 result.emplace(path);
239 }
240 return result;
241 }
242
adb_auth_get_private_keys()243 std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
244 std::deque<std::shared_ptr<RSA>> result;
245
246 // 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);
250 }
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
adb_auth_sign(RSA * key,const char * token,size_t token_size)260 static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) {
261 if (token_size != TOKEN_SIZE) {
262 D("Unexpected token size %zd", token_size);
263 return nullptr;
264 }
265
266 std::string result;
267 result.resize(MAX_PAYLOAD);
268
269 unsigned int len;
270 if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
271 reinterpret_cast<uint8_t*>(&result[0]), &len, key)) {
272 return std::string();
273 }
274
275 result.resize(len);
276
277 D("adb_auth_sign len=%d", len);
278 return result;
279 }
280
pubkey_from_privkey(std::string * out,const std::string & path)281 static 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 }
286 return CalculatePublicKey(out, privkey.get());
287 }
288
adb_auth_get_user_privkey()289 bssl::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
adb_auth_get_userkey()311 std::string adb_auth_get_userkey() {
312 std::string path = get_user_key_path();
313 if (path.empty()) {
314 PLOG(ERROR) << "Error getting user key filename";
315 return "";
316 }
317
318 std::string result;
319 if (!pubkey_from_privkey(&result, path)) {
320 return "";
321 }
322 return result;
323 }
324
adb_auth_keygen(const char * filename)325 int adb_auth_keygen(const char* filename) {
326 return !generate_key(filename);
327 }
328
adb_auth_pubkey(const char * filename)329 int 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
339 #if defined(__linux__)
adb_auth_inotify_update(int fd,unsigned fd_event,void *)340 static 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 << "'";
379 load_keys(path, false);
380 }
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
adb_auth_inotify_init(const std::set<std::string> & paths)391 static void adb_auth_inotify_init(const std::set<std::string>& paths) {
392 LOG(INFO) << "adb_auth_inotify_init...";
393
394 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
395 if (infd < 0) {
396 PLOG(ERROR) << "failed to create inotify fd";
397 return;
398 }
399
400 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
adb_auth_init()416 void adb_auth_init() {
417 LOG(INFO) << "adb_auth_init...";
418
419 if (!load_userkey()) {
420 LOG(ERROR) << "Failed to load (or generate) user key";
421 return;
422 }
423
424 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) {
431 load_keys(path);
432 }
433 }
434
send_auth_publickey(atransport * t)435 static 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();
450 p->msg.command = A_AUTH;
451 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
452
453 // adbd expects a null-terminated string.
454 p->payload.assign(key.data(), key.data() + key.size() + 1);
455 p->msg.data_length = p->payload.size();
456 send_packet(p, t);
457 }
458
send_auth_response(const char * token,size_t token_size,atransport * t)459 void send_auth_response(const char* token, size_t token_size, atransport* t) {
460 std::shared_ptr<RSA> key = t->NextKey();
461 if (key == nullptr) {
462 // No more private keys to try, send the public key.
463 t->SetConnectionState(kCsUnauthorized);
464 t->SetConnectionEstablished(true);
465 send_auth_publickey(t);
466 return;
467 }
468
469 LOG(INFO) << "Calling send_auth_response";
470 apacket* p = get_apacket();
471
472 std::string result = adb_auth_sign(key.get(), token, token_size);
473 if (result.empty()) {
474 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;
481 p->payload.assign(result.begin(), result.end());
482 p->msg.data_length = p->payload.size();
483 send_packet(p, t);
484 }
485
adb_auth_tls_handshake(atransport * t)486 void 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
507 // Callback given to SSL_set_cert_cb to select a certificate when server requests
508 // for a certificate. This is where the server will give us a CA-issuer list, and
509 // figure out if the server knows any of our public keys. We currently always return
510 // 1 here to indicate success, since we always try a key here (in the case of no auth).
511 // See https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_cert_cb
512 // for more details.
adb_tls_set_certificate(SSL * ssl)513 int adb_tls_set_certificate(SSL* ssl) {
514 LOG(INFO) << __func__;
515
516 const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
517 if (ca_list == nullptr) {
518 // Either the device doesn't know any keys, or !auth_required.
519 // So let's just try with the default certificate and see what happens.
520 LOG(INFO) << "No client CA list. Trying with default certificate.";
521 return 1;
522 }
523
524 const size_t num_cas = sk_X509_NAME_num(ca_list);
525 for (size_t i = 0; i < num_cas; ++i) {
526 auto* x509_name = sk_X509_NAME_value(ca_list, i);
527 auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
528 if (!adbFingerprint.has_value()) {
529 // This could be a real CA issuer. Unfortunately, we don't support
530 // it ATM.
531 continue;
532 }
533
534 LOG(INFO) << "Checking for fingerprint match [" << *adbFingerprint << "]";
535 auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
536 if (!encoded_key.has_value()) {
537 continue;
538 }
539 // Check against our list of encoded keys for a match
540 std::lock_guard<std::mutex> lock(g_keys_mutex);
541 auto rsa_priv_key = g_keys.find(*encoded_key);
542 if (rsa_priv_key != g_keys.end()) {
543 LOG(INFO) << "Got SHA256 match on a key";
544 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
545 CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
546 auto x509 = GenerateX509Certificate(evp_pkey.get());
547 auto x509_str = X509ToPEMString(x509.get());
548 auto evp_str = Key::ToPEMString(evp_pkey.get());
549 TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
550 return 1;
551 } else {
552 LOG(INFO) << "No match for [" << *adbFingerprint << "]";
553 }
554 }
555
556 // Let's just try with the default certificate anyways, because daemon might
557 // not require auth, even though it has a list of keys.
558 return 1;
559 }
560