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 if (g_keys.find(fingerprint) != g_keys.end()) {
149 LOG(INFO) << "ignoring already-loaded key: " << file;
150 } else {
151 LOG(INFO) << "Loaded fingerprint=[" << SHA256BitsToHexString(fingerprint) << "]";
152 g_keys[fingerprint] = std::move(key);
153 }
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) << "failed to stat '" << path << "'";
163 return false;
164 }
165
166 if (S_ISREG(st.st_mode)) {
167 return load_key(path);
168 } 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
191 if (!android::base::EndsWith(name, ".adb_key")) {
192 LOG(INFO) << "skipping 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) << "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 LOG(INFO) << "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 D("Unexpected token size %zd", token_size);
261 return nullptr;
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 D("adb_auth_sign len=%d", 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 pubkey.push_back('\n');
333
334 return WriteFdExactly(STDOUT_FILENO, pubkey.data(), pubkey.size()) ? 0 : 1;
335 }
336
337 #if defined(__linux__)
adb_auth_inotify_update(int fd,unsigned fd_event,void *)338 static 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 << "'";
377 load_keys(path, false);
378 }
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
adb_auth_inotify_init(const std::set<std::string> & paths)389 static void adb_auth_inotify_init(const std::set<std::string>& paths) {
390 LOG(INFO) << "adb_auth_inotify_init...";
391
392 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
393 if (infd < 0) {
394 PLOG(ERROR) << "failed to create inotify fd";
395 return;
396 }
397
398 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
adb_auth_init()414 void adb_auth_init() {
415 LOG(INFO) << "adb_auth_init...";
416
417 if (!load_userkey()) {
418 LOG(ERROR) << "Failed to load (or generate) user key";
419 return;
420 }
421
422 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) {
429 load_keys(path);
430 }
431 }
432
send_auth_publickey(atransport * t)433 static 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();
448 p->msg.command = A_AUTH;
449 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
450
451 // adbd expects a null-terminated string.
452 p->payload.assign(key.data(), key.data() + key.size() + 1);
453 p->msg.data_length = p->payload.size();
454 send_packet(p, t);
455 }
456
send_auth_response(const char * token,size_t token_size,atransport * t)457 void send_auth_response(const char* token, size_t token_size, atransport* t) {
458 std::shared_ptr<RSA> key = t->NextKey();
459 if (key == nullptr) {
460 // No more private keys to try, send the public key.
461 t->SetConnectionState(kCsUnauthorized);
462 t->SetConnectionEstablished(true);
463 send_auth_publickey(t);
464 return;
465 }
466
467 LOG(INFO) << "Calling send_auth_response";
468 apacket* p = get_apacket();
469
470 std::string result = adb_auth_sign(key.get(), token, token_size);
471 if (result.empty()) {
472 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;
479 p->payload.assign(result.begin(), result.end());
480 p->msg.data_length = p->payload.size();
481 send_packet(p, t);
482 }
483
adb_auth_tls_handshake(atransport * t)484 void 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
505 // Callback given to SSL_set_cert_cb to select a certificate when server requests
506 // for a certificate. This is where the server will give us a CA-issuer list, and
507 // figure out if the server knows any of our public keys. We currently always return
508 // 1 here to indicate success, since we always try a key here (in the case of no auth).
509 // See https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_cert_cb
510 // for more details.
adb_tls_set_certificate(SSL * ssl)511 int adb_tls_set_certificate(SSL* ssl) {
512 LOG(INFO) << __func__;
513
514 const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
515 if (ca_list == nullptr) {
516 // Either the device doesn't know any keys, or !auth_required.
517 // So let's just try with the default certificate and see what happens.
518 LOG(INFO) << "No client CA list. Trying with default certificate.";
519 return 1;
520 }
521
522 const size_t num_cas = sk_X509_NAME_num(ca_list);
523 for (size_t i = 0; i < num_cas; ++i) {
524 auto* x509_name = sk_X509_NAME_value(ca_list, i);
525 auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
526 if (!adbFingerprint.has_value()) {
527 // This could be a real CA issuer. Unfortunately, we don't support
528 // it ATM.
529 continue;
530 }
531
532 LOG(INFO) << "Checking for fingerprint match [" << *adbFingerprint << "]";
533 auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
534 if (!encoded_key.has_value()) {
535 continue;
536 }
537 // Check against our list of encoded keys for a match
538 std::lock_guard<std::mutex> lock(g_keys_mutex);
539 auto rsa_priv_key = g_keys.find(*encoded_key);
540 if (rsa_priv_key != g_keys.end()) {
541 LOG(INFO) << "Got SHA256 match on a key";
542 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
543 CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
544 auto x509 = GenerateX509Certificate(evp_pkey.get());
545 auto x509_str = X509ToPEMString(x509.get());
546 auto evp_str = Key::ToPEMString(evp_pkey.get());
547 TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
548 return 1;
549 } else {
550 LOG(INFO) << "No match for [" << *adbFingerprint << "]";
551 }
552 }
553
554 // Let's just try with the default certificate anyways, because daemon might
555 // not require auth, even though it has a list of keys.
556 return 1;
557 }
558