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 std::string();
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     fprintf(stdout, "%s\n", pubkey.data());
335     return 0;
336 }
337 
338 #if defined(__linux__)
adb_auth_inotify_update(int fd,unsigned fd_event,void *)339 static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
340     LOG(INFO) << "adb_auth_inotify_update called";
341     if (!(fd_event & FDE_READ)) {
342         return;
343     }
344 
345     char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
346     while (true) {
347         ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
348         if (rc == -1) {
349             if (errno == EAGAIN) {
350                 LOG(INFO) << "done reading inotify fd";
351                 break;
352             }
353             PLOG(FATAL) << "read of inotify event failed";
354         }
355 
356         // The read potentially returned multiple events.
357         char* start = buf;
358         char* end = buf + rc;
359 
360         while (start < end) {
361             inotify_event* event = reinterpret_cast<inotify_event*>(start);
362             auto root_it = g_monitored_paths.find(event->wd);
363             if (root_it == g_monitored_paths.end()) {
364                 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
365             }
366 
367             std::string path = root_it->second;
368             if (event->len > 0) {
369                 path += '/';
370                 path += event->name;
371             }
372 
373             if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
374                 if (event->mask & IN_ISDIR) {
375                     LOG(INFO) << "ignoring new directory at '" << path << "'";
376                 } else {
377                     LOG(INFO) << "observed new file at '" << path << "'";
378                     load_keys(path, false);
379                 }
380             } else {
381                 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
382                              << event->mask;
383             }
384 
385             start += sizeof(struct inotify_event) + event->len;
386         }
387     }
388 }
389 
adb_auth_inotify_init(const std::set<std::string> & paths)390 static void adb_auth_inotify_init(const std::set<std::string>& paths) {
391     LOG(INFO) << "adb_auth_inotify_init...";
392 
393     int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
394     if (infd < 0) {
395         PLOG(ERROR) << "failed to create inotify fd";
396         return;
397     }
398 
399     for (const std::string& path : paths) {
400         int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
401         if (wd < 0) {
402             PLOG(ERROR) << "failed to inotify_add_watch on path '" << path << "'";
403             continue;
404         }
405 
406         g_monitored_paths[wd] = path;
407         LOG(INFO) << "watch descriptor " << wd << " registered for '" << path << "'";
408     }
409 
410     fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
411     fdevent_add(event, FDE_READ);
412 }
413 #endif
414 
adb_auth_init()415 void adb_auth_init() {
416     LOG(INFO) << "adb_auth_init...";
417 
418     if (!load_userkey()) {
419         LOG(ERROR) << "Failed to load (or generate) user key";
420         return;
421     }
422 
423     const auto& key_paths = get_vendor_keys();
424 
425 #if defined(__linux__)
426     adb_auth_inotify_init(key_paths);
427 #endif
428 
429     for (const std::string& path : key_paths) {
430         load_keys(path);
431     }
432 }
433 
send_auth_publickey(atransport * t)434 static void send_auth_publickey(atransport* t) {
435     LOG(INFO) << "Calling send_auth_publickey";
436 
437     std::string key = adb_auth_get_userkey();
438     if (key.empty()) {
439         D("Failed to get user public key");
440         return;
441     }
442 
443     if (key.size() >= MAX_PAYLOAD_V1) {
444         D("User public key too large (%zu B)", key.size());
445         return;
446     }
447 
448     apacket* p = get_apacket();
449     p->msg.command = A_AUTH;
450     p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
451 
452     // adbd expects a null-terminated string.
453     p->payload.assign(key.data(), key.data() + key.size() + 1);
454     p->msg.data_length = p->payload.size();
455     send_packet(p, t);
456 }
457 
send_auth_response(const char * token,size_t token_size,atransport * t)458 void send_auth_response(const char* token, size_t token_size, atransport* t) {
459     std::shared_ptr<RSA> key = t->NextKey();
460     if (key == nullptr) {
461         // No more private keys to try, send the public key.
462         t->SetConnectionState(kCsUnauthorized);
463         t->SetConnectionEstablished(true);
464         send_auth_publickey(t);
465         return;
466     }
467 
468     LOG(INFO) << "Calling send_auth_response";
469     apacket* p = get_apacket();
470 
471     std::string result = adb_auth_sign(key.get(), token, token_size);
472     if (result.empty()) {
473         D("Error signing the token");
474         put_apacket(p);
475         return;
476     }
477 
478     p->msg.command = A_AUTH;
479     p->msg.arg0 = ADB_AUTH_SIGNATURE;
480     p->payload.assign(result.begin(), result.end());
481     p->msg.data_length = p->payload.size();
482     send_packet(p, t);
483 }
484 
adb_auth_tls_handshake(atransport * t)485 void adb_auth_tls_handshake(atransport* t) {
486     std::thread([t]() {
487         std::shared_ptr<RSA> key = t->Key();
488         if (key == nullptr) {
489             // Can happen if !auth_required
490             LOG(INFO) << "t->auth_key not set before handshake";
491             key = t->NextKey();
492             CHECK(key);
493         }
494 
495         LOG(INFO) << "Attempting to TLS handshake";
496         bool success = t->connection()->DoTlsHandshake(key.get());
497         if (success) {
498             LOG(INFO) << "Handshake succeeded. Waiting for CNXN packet...";
499         } else {
500             LOG(INFO) << "Handshake failed. Kicking transport";
501             t->Kick();
502         }
503     }).detach();
504 }
505 
506 // Callback given to SSL_set_cert_cb to select a certificate when server requests
507 // for a certificate. This is where the server will give us a CA-issuer list, and
508 // figure out if the server knows any of our public keys. We currently always return
509 // 1 here to indicate success, since we always try a key here (in the case of no auth).
510 // See https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#SSL_set_cert_cb
511 // for more details.
adb_tls_set_certificate(SSL * ssl)512 int adb_tls_set_certificate(SSL* ssl) {
513     LOG(INFO) << __func__;
514 
515     const STACK_OF(X509_NAME)* ca_list = SSL_get_client_CA_list(ssl);
516     if (ca_list == nullptr) {
517         // Either the device doesn't know any keys, or !auth_required.
518         // So let's just try with the default certificate and see what happens.
519         LOG(INFO) << "No client CA list. Trying with default certificate.";
520         return 1;
521     }
522 
523     const size_t num_cas = sk_X509_NAME_num(ca_list);
524     for (size_t i = 0; i < num_cas; ++i) {
525         auto* x509_name = sk_X509_NAME_value(ca_list, i);
526         auto adbFingerprint = ParseEncodedKeyFromCAIssuer(x509_name);
527         if (!adbFingerprint.has_value()) {
528             // This could be a real CA issuer. Unfortunately, we don't support
529             // it ATM.
530             continue;
531         }
532 
533         LOG(INFO) << "Checking for fingerprint match [" << *adbFingerprint << "]";
534         auto encoded_key = SHA256HexStringToBits(*adbFingerprint);
535         if (!encoded_key.has_value()) {
536             continue;
537         }
538         // Check against our list of encoded keys for a match
539         std::lock_guard<std::mutex> lock(g_keys_mutex);
540         auto rsa_priv_key = g_keys.find(*encoded_key);
541         if (rsa_priv_key != g_keys.end()) {
542             LOG(INFO) << "Got SHA256 match on a key";
543             bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
544             CHECK(EVP_PKEY_set1_RSA(evp_pkey.get(), rsa_priv_key->second.get()));
545             auto x509 = GenerateX509Certificate(evp_pkey.get());
546             auto x509_str = X509ToPEMString(x509.get());
547             auto evp_str = Key::ToPEMString(evp_pkey.get());
548             TlsConnection::SetCertAndKey(ssl, x509_str, evp_str);
549             return 1;
550         } else {
551             LOG(INFO) << "No match for [" << *adbFingerprint << "]";
552         }
553     }
554 
555     // Let's just try with the default certificate anyways, because daemon might
556     // not require auth, even though it has a list of keys.
557     return 1;
558 }
559