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 #include <dirent.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #if defined(__linux__)
22 #include <sys/inotify.h>
23 #endif
24
25 #include <map>
26 #include <mutex>
27 #include <set>
28 #include <string>
29
30 #include <adb/crypto/rsa_2048_key.h>
31 #include <adb/crypto/x509_generator.h>
32 #include <adb/tls/adb_ca_list.h>
33 #include <adb/tls/tls_connection.h>
34 #include <android-base/errors.h>
35 #include <android-base/file.h>
36 #include <android-base/stringprintf.h>
37 #include <android-base/strings.h>
38 #include <crypto_utils/android_pubkey.h>
39 #include <openssl/base64.h>
40 #include <openssl/evp.h>
41 #include <openssl/objects.h>
42 #include <openssl/pem.h>
43 #include <openssl/rsa.h>
44 #include <openssl/sha.h>
45
46 #include "adb.h"
47 #include "adb_auth.h"
48 #include "adb_io.h"
49 #include "adb_utils.h"
50 #include "sysdeps.h"
51 #include "transport.h"
52
53 static std::mutex& g_keys_mutex = *new std::mutex;
54 static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
55 *new std::map<std::string, std::shared_ptr<RSA>>;
56 static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;
57
58 using namespace adb::crypto;
59 using namespace adb::tls;
60
generate_key(const std::string & file)61 static bool generate_key(const std::string& file) {
62 VLOG(AUTH) << "generate_key(" << file << ")...";
63
64 auto rsa_2048 = CreateRSA2048Key();
65 if (!rsa_2048) {
66 LOG(ERROR) << "Unable to create key";
67 return false;
68 }
69 std::string pubkey;
70
71 RSA* rsa = EVP_PKEY_get0_RSA(rsa_2048->GetEvpPkey());
72 CHECK(rsa);
73
74 if (!CalculatePublicKey(&pubkey, rsa)) {
75 LOG(ERROR) << "failed to calculate public key";
76 return false;
77 }
78
79 mode_t old_mask = umask(077);
80
81 std::unique_ptr<FILE, decltype(&fclose)> f(nullptr, &fclose);
82 f.reset(fopen(file.c_str(), "w"));
83 if (!f) {
84 PLOG(ERROR) << "Failed to open " << file;
85 umask(old_mask);
86 return false;
87 }
88
89 umask(old_mask);
90
91 if (!PEM_write_PrivateKey(f.get(), rsa_2048->GetEvpPkey(), nullptr, nullptr, 0, nullptr,
92 nullptr)) {
93 LOG(ERROR) << "Failed to write key";
94 return false;
95 }
96
97 if (!android::base::WriteStringToFile(pubkey, file + ".pub")) {
98 PLOG(ERROR) << "failed to write public key";
99 return false;
100 }
101
102 return true;
103 }
104
hash_key(RSA * key)105 static std::string hash_key(RSA* key) {
106 unsigned char* pubkey = nullptr;
107 int len = i2d_RSA_PUBKEY(key, &pubkey);
108 if (len < 0) {
109 LOG(ERROR) << "failed to encode RSA public key";
110 return std::string();
111 }
112
113 std::string result;
114 result.resize(SHA256_DIGEST_LENGTH);
115 SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0]));
116 OPENSSL_free(pubkey);
117 return result;
118 }
119
read_key_file(const std::string & file)120 static std::shared_ptr<RSA> read_key_file(const std::string& file) {
121 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
122 if (!fp) {
123 PLOG(ERROR) << "Failed to open '" << file << "'";
124 return nullptr;
125 }
126
127 RSA* key = RSA_new();
128 if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
129 LOG(ERROR) << "Failed to read key from '" << file << "'";
130 ERR_print_errors_fp(stderr);
131 RSA_free(key);
132 return nullptr;
133 }
134
135 return std::shared_ptr<RSA>(key, RSA_free);
136 }
137
load_key(const std::string & file)138 static bool load_key(const std::string& file) {
139 std::shared_ptr<RSA> key = read_key_file(file);
140 if (!key) {
141 return false;
142 }
143
144 std::lock_guard<std::mutex> lock(g_keys_mutex);
145 std::string fingerprint = hash_key(key.get());
146 bool already_loaded = g_keys.contains(fingerprint);
147 if (!already_loaded) {
148 g_keys[fingerprint] = std::move(key);
149 }
150 VLOG(AUTH) << (already_loaded ? "ignored already-loaded" : "loaded new") << " key from '"
151 << file << "' with fingerprint " << SHA256BitsToHexString(fingerprint);
152 return true;
153 }
154
load_keys(const std::string & path,bool allow_dir=true)155 static bool load_keys(const std::string& path, bool allow_dir = true) {
156 VLOG(AUTH) << "load_keys '" << path << "'...";
157
158 struct stat st;
159 if (stat(path.c_str(), &st) != 0) {
160 PLOG(ERROR) << "load_keys: failed to stat '" << path << "'";
161 return false;
162 }
163
164 if (S_ISREG(st.st_mode)) {
165 return load_key(path);
166 }
167
168 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) << "load_keys: 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) << "load_keys: 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
191 if (!android::base::EndsWith(name, ".adb_key")) {
192 VLOG(AUTH) << "skipped non-adb_key '" << path << "/" << name << "'";
193 continue;
194 }
195
196 result |= load_key((path + OS_PATH_SEPARATOR + name));
197 }
198 return result;
199 }
200
201 LOG(ERROR) << "load_keys: unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
202 return false;
203 }
204
get_user_key_path()205 static std::string get_user_key_path() {
206 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
207 }
208
load_userkey()209 static bool load_userkey() {
210 std::string path = get_user_key_path();
211 if (path.empty()) {
212 PLOG(ERROR) << "Error getting user key filename";
213 return false;
214 }
215
216 struct stat buf;
217 if (stat(path.c_str(), &buf) == -1) {
218 VLOG(AUTH) << "User key '" << path << "' does not exist...";
219 if (!generate_key(path)) {
220 LOG(ERROR) << "Failed to generate new key";
221 return false;
222 }
223 }
224
225 return load_key(path);
226 }
227
get_vendor_keys()228 static std::set<std::string> get_vendor_keys() {
229 const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
230 if (adb_keys_path == nullptr) {
231 return std::set<std::string>();
232 }
233
234 std::set<std::string> result;
235 for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
236 result.emplace(path);
237 }
238 return result;
239 }
240
adb_auth_get_private_keys()241 std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
242 std::deque<std::shared_ptr<RSA>> result;
243
244 // 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);
248 }
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
adb_auth_sign(RSA * key,const char * token,size_t token_size)258 static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) {
259 if (token_size != TOKEN_SIZE) {
260 LOG(WARNING) << "Unexpected token size=" << token_size;
261 return std::string();
262 }
263
264 std::string result;
265 result.resize(MAX_PAYLOAD);
266
267 unsigned int len;
268 if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
269 reinterpret_cast<uint8_t*>(&result[0]), &len, key)) {
270 return std::string();
271 }
272
273 result.resize(len);
274
275 VLOG(AUTH) << "adb_auth_sign len=" << len;
276 return result;
277 }
278
pubkey_from_privkey(std::string * out,const std::string & path)279 static 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 }
284 return CalculatePublicKey(out, privkey.get());
285 }
286
adb_auth_get_user_privkey()287 bssl::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
adb_auth_get_userkey()309 std::string adb_auth_get_userkey() {
310 std::string path = get_user_key_path();
311 if (path.empty()) {
312 PLOG(ERROR) << "Error getting user key filename";
313 return "";
314 }
315
316 std::string result;
317 if (!pubkey_from_privkey(&result, path)) {
318 return "";
319 }
320 return result;
321 }
322
adb_auth_keygen(const char * filename)323 int adb_auth_keygen(const char* filename) {
324 return !generate_key(filename);
325 }
326
adb_auth_pubkey(const char * filename)327 int adb_auth_pubkey(const char* filename) {
328 std::string pubkey;
329 if (!pubkey_from_privkey(&pubkey, filename)) {
330 return 1;
331 }
332 fprintf(stdout, "%s\n", pubkey.data());
333 return 0;
334 }
335
336 #if defined(__linux__)
adb_auth_inotify_update(int fd,unsigned fd_event,void *)337 static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
338 VLOG(AUTH) << "adb_auth_inotify_update called";
339 if (!(fd_event & FDE_READ)) {
340 return;
341 }
342
343 char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
344 while (true) {
345 ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
346 if (rc == -1) {
347 if (errno == EAGAIN) {
348 VLOG(AUTH) << "done reading inotify fd";
349 break;
350 }
351 PLOG(FATAL) << "read of inotify event failed";
352 }
353
354 // The read potentially returned multiple events.
355 char* start = buf;
356 char* end = buf + rc;
357
358 while (start < end) {
359 inotify_event* event = reinterpret_cast<inotify_event*>(start);
360 auto root_it = g_monitored_paths.find(event->wd);
361 if (root_it == g_monitored_paths.end()) {
362 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
363 }
364
365 std::string path = root_it->second;
366 if (event->len > 0) {
367 path += '/';
368 path += event->name;
369 }
370
371 if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
372 if (event->mask & IN_ISDIR) {
373 VLOG(AUTH) << "ignoring new directory at '" << path << "'";
374 } else {
375 VLOG(AUTH) << "observed new file at '" << path << "'";
376 load_keys(path, false);
377 }
378 } else {
379 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
380 << event->mask;
381 }
382
383 start += sizeof(struct inotify_event) + event->len;
384 }
385 }
386 }
387
adb_auth_inotify_init(const std::set<std::string> & paths)388 static void adb_auth_inotify_init(const std::set<std::string>& paths) {
389 VLOG(AUTH) << "adb_auth_inotify_init...";
390
391 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
392 if (infd < 0) {
393 PLOG(ERROR) << "failed to create inotify fd";
394 return;
395 }
396
397 for (const std::string& path : paths) {
398 int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
399 if (wd < 0) {
400 PLOG(ERROR) << "failed to inotify_add_watch on path '" << path << "'";
401 continue;
402 }
403
404 g_monitored_paths[wd] = path;
405 VLOG(AUTH) << "watch descriptor " << wd << " registered for '" << path << "'";
406 }
407
408 fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
409 fdevent_add(event, FDE_READ);
410 }
411 #endif
412
adb_auth_init()413 void adb_auth_init() {
414 VLOG(AUTH) << "adb_auth_init...";
415
416 if (!load_userkey()) {
417 LOG(ERROR) << "Failed to load (or generate) user key";
418 return;
419 }
420
421 const auto& key_paths = get_vendor_keys();
422
423 #if defined(__linux__)
424 adb_auth_inotify_init(key_paths);
425 #endif
426
427 for (const std::string& path : key_paths) {
428 load_keys(path);
429 }
430 }
431
send_auth_publickey(atransport * t)432 static void send_auth_publickey(atransport* t) {
433 VLOG(AUTH) << "Calling send_auth_publickey";
434
435 std::string key = adb_auth_get_userkey();
436 if (key.empty()) {
437 LOG(WARNING) << "Failed to get user public key";
438 return;
439 }
440
441 if (key.size() >= MAX_PAYLOAD_V1) {
442 LOG(WARNING) << "User public key too large " << key.size() << " bytes";
443 return;
444 }
445
446 apacket* p = get_apacket();
447 p->msg.command = A_AUTH;
448 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
449
450 // adbd expects a null-terminated string.
451 p->payload.assign(key.data(), key.data() + key.size() + 1);
452 p->msg.data_length = p->payload.size();
453 send_packet(p, t);
454 }
455
send_auth_response(const char * token,size_t token_size,atransport * t)456 void send_auth_response(const char* token, size_t token_size, atransport* t) {
457 std::shared_ptr<RSA> key = t->NextKey();
458 if (key == nullptr) {
459 // No more private keys to try, send the public key.
460 t->SetConnectionState(kCsUnauthorized);
461 t->SetConnectionEstablished(true);
462 send_auth_publickey(t);
463 return;
464 }
465
466 VLOG(AUTH) << "Calling send_auth_response";
467 apacket* p = get_apacket();
468
469 std::string result = adb_auth_sign(key.get(), token, token_size);
470 if (result.empty()) {
471 LOG(WARNING) << "Error signing the token";
472 put_apacket(p);
473 return;
474 }
475
476 p->msg.command = A_AUTH;
477 p->msg.arg0 = ADB_AUTH_SIGNATURE;
478 p->payload.assign(result.begin(), result.end());
479 p->msg.data_length = p->payload.size();
480 send_packet(p, t);
481 }
482
adb_auth_tls_handshake(atransport * t)483 void adb_auth_tls_handshake(atransport* t) {
484 std::thread([t]() {
485 std::shared_ptr<RSA> key = t->Key();
486 if (key == nullptr) {
487 // Can happen if !auth_required
488 VLOG(AUTH) << "t->auth_key not set before handshake";
489 key = t->NextKey();
490 CHECK(key);
491 }
492
493 VLOG(AUTH) << "Attempting to TLS handshake";
494 bool success = t->connection()->DoTlsHandshake(key.get());
495 if (success) {
496 VLOG(AUTH) << "Handshake succeeded. Waiting for CNXN packet...";
497 } else {
498 VLOG(AUTH) << "Handshake failed. Kicking transport";
499 t->Kick();
500 }
501 }).detach();
502 }
503
504 // Callback given to SSL_set_cert_cb to select a certificate when server requests
505 // for a certificate. This is where the server will give us a CA-issuer list, and
506 // figure out if the server knows any of our public keys. We currently always return
507 // 1 here to indicate success, since we always try a key here (in the case of no auth).
508 // See https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_cert_cb
509 // for more details.
adb_tls_set_certificate(SSL * ssl)510 int adb_tls_set_certificate(SSL* ssl) {
511 VLOG(AUTH) << __func__;
512
513 const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
514 if (ca_list == nullptr) {
515 // Either the device doesn't know any keys, or !auth_required.
516 // So let's just try with the default certificate and see what happens.
517 VLOG(AUTH) << "No client CA list. Trying with default certificate.";
518 return 1;
519 }
520
521 const size_t num_cas = sk_X509_NAME_num(ca_list);
522 for (size_t i = 0; i < num_cas; ++i) {
523 auto* x509_name = sk_X509_NAME_value(ca_list, i);
524 auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
525 if (!adbFingerprint.has_value()) {
526 // This could be a real CA issuer. Unfortunately, we don't support
527 // it ATM.
528 continue;
529 }
530
531 VLOG(AUTH) << "Checking for fingerprint match [" << *adbFingerprint << "]";
532 auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
533 if (!encoded_key.has_value()) {
534 continue;
535 }
536 // Check against our list of encoded keys for a match
537 std::lock_guard<std::mutex> lock(g_keys_mutex);
538 auto rsa_priv_key = g_keys.find(*encoded_key);
539 if (rsa_priv_key != g_keys.end()) {
540 VLOG(AUTH) << "Got SHA256 match on a key";
541 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
542 CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
543 auto x509 = GenerateX509Certificate(evp_pkey.get());
544 auto x509_str = X509ToPEMString(x509.get());
545 auto evp_str = Key::ToPEMString(evp_pkey.get());
546 TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
547 return 1;
548 } else {
549 VLOG(AUTH) << "No match for [" << *adbFingerprint << "]";
550 }
551 }
552
553 // Let's just try with the default certificate anyways, because daemon might
554 // not require auth, even though it has a list of keys.
555 return 1;
556 }
557