• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <android-base/errors.h>
33 #include <android-base/file.h>
34 #include <android-base/stringprintf.h>
35 #include <android-base/strings.h>
36 #include <crypto_utils/android_pubkey.h>
37 #include <openssl/base64.h>
38 #include <openssl/evp.h>
39 #include <openssl/objects.h>
40 #include <openssl/pem.h>
41 #include <openssl/rsa.h>
42 #include <openssl/sha.h>
43 
44 #include "adb.h"
45 #include "adb_auth.h"
46 #include "adb_io.h"
47 #include "adb_utils.h"
48 #include "sysdeps.h"
49 #include "transport.h"
50 
51 static std::mutex& g_keys_mutex = *new std::mutex;
52 static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
53     *new std::map<std::string, std::shared_ptr<RSA>>;
54 static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;
55 
calculate_public_key(std::string * out,RSA * private_key)56 static bool calculate_public_key(std::string* out, RSA* private_key) {
57     uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE];
58     if (!android_pubkey_encode(private_key, binary_key_data, sizeof(binary_key_data))) {
59         LOG(ERROR) << "Failed to convert to public key";
60         return false;
61     }
62 
63     size_t expected_length;
64     if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
65         LOG(ERROR) << "Public key too large to base64 encode";
66         return false;
67     }
68 
69     out->resize(expected_length);
70     size_t actual_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(out->data()), binary_key_data,
71                                            sizeof(binary_key_data));
72     out->resize(actual_length);
73     return true;
74 }
75 
generate_key(const std::string & file)76 static int generate_key(const std::string& file) {
77     LOG(INFO) << "generate_key(" << file << ")...";
78 
79     mode_t old_mask;
80     FILE *f = nullptr;
81     int ret = 0;
82 
83     EVP_PKEY* pkey = EVP_PKEY_new();
84     BIGNUM* exponent = BN_new();
85     RSA* rsa = RSA_new();
86     if (!pkey || !exponent || !rsa) {
87         LOG(ERROR) << "Failed to allocate key";
88         goto out;
89     }
90 
91     BN_set_word(exponent, RSA_F4);
92     RSA_generate_key_ex(rsa, 2048, exponent, nullptr);
93     EVP_PKEY_set1_RSA(pkey, rsa);
94 
95     old_mask = umask(077);
96 
97     f = fopen(file.c_str(), "w");
98     if (!f) {
99         PLOG(ERROR) << "Failed to open " << file;
100         umask(old_mask);
101         goto out;
102     }
103 
104     umask(old_mask);
105 
106     if (!PEM_write_PrivateKey(f, pkey, nullptr, nullptr, 0, nullptr, nullptr)) {
107         D("Failed to write key");
108         goto out;
109     }
110 
111     ret = 1;
112 
113 out:
114     if (f) fclose(f);
115     EVP_PKEY_free(pkey);
116     RSA_free(rsa);
117     BN_free(exponent);
118     return ret;
119 }
120 
hash_key(RSA * key)121 static std::string hash_key(RSA* key) {
122     unsigned char* pubkey = nullptr;
123     int len = i2d_RSA_PUBKEY(key, &pubkey);
124     if (len < 0) {
125         LOG(ERROR) << "failed to encode RSA public key";
126         return std::string();
127     }
128 
129     std::string result;
130     result.resize(SHA256_DIGEST_LENGTH);
131     SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0]));
132     OPENSSL_free(pubkey);
133     return result;
134 }
135 
read_key_file(const std::string & file)136 static std::shared_ptr<RSA> read_key_file(const std::string& file) {
137     std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
138     if (!fp) {
139         PLOG(ERROR) << "Failed to open '" << file << "'";
140         return nullptr;
141     }
142 
143     RSA* key = RSA_new();
144     if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
145         LOG(ERROR) << "Failed to read key";
146         RSA_free(key);
147         return nullptr;
148     }
149 
150     return std::shared_ptr<RSA>(key, RSA_free);
151 }
152 
load_key(const std::string & file)153 static bool load_key(const std::string& file) {
154     std::shared_ptr<RSA> key = read_key_file(file);
155     if (!key) {
156         return false;
157     }
158 
159     std::lock_guard<std::mutex> lock(g_keys_mutex);
160     std::string fingerprint = hash_key(key.get());
161     if (g_keys.find(fingerprint) != g_keys.end()) {
162         LOG(INFO) << "ignoring already-loaded key: " << file;
163     } else {
164         g_keys[fingerprint] = std::move(key);
165     }
166     return true;
167 }
168 
load_keys(const std::string & path,bool allow_dir=true)169 static bool load_keys(const std::string& path, bool allow_dir = true) {
170     LOG(INFO) << "load_keys '" << path << "'...";
171 
172     struct stat st;
173     if (stat(path.c_str(), &st) != 0) {
174         PLOG(ERROR) << "failed to stat '" << path << "'";
175         return false;
176     }
177 
178     if (S_ISREG(st.st_mode)) {
179         return load_key(path);
180     } else if (S_ISDIR(st.st_mode)) {
181         if (!allow_dir) {
182             // inotify isn't recursive. It would break expectations to load keys in nested
183             // directories but not monitor them for new keys.
184             LOG(WARNING) << "refusing to recurse into directory '" << path << "'";
185             return false;
186         }
187 
188         std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
189         if (!dir) {
190             PLOG(ERROR) << "failed to open directory '" << path << "'";
191             return false;
192         }
193 
194         bool result = false;
195         while (struct dirent* dent = readdir(dir.get())) {
196             std::string name = dent->d_name;
197 
198             // We can't use dent->d_type here because it's not available on Windows.
199             if (name == "." || name == "..") {
200                 continue;
201             }
202 
203             if (!android::base::EndsWith(name, ".adb_key")) {
204                 LOG(INFO) << "skipping non-adb_key '" << path << "/" << name << "'";
205                 continue;
206             }
207 
208             result |= load_key((path + OS_PATH_SEPARATOR + name));
209         }
210         return result;
211     }
212 
213     LOG(ERROR) << "unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
214     return false;
215 }
216 
get_user_key_path()217 static std::string get_user_key_path() {
218     return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
219 }
220 
generate_userkey()221 static bool generate_userkey() {
222     std::string path = get_user_key_path();
223     if (path.empty()) {
224         PLOG(ERROR) << "Error getting user key filename";
225         return false;
226     }
227 
228     struct stat buf;
229     if (stat(path.c_str(), &buf) == -1) {
230         LOG(INFO) << "User key '" << path << "' does not exist...";
231         if (!generate_key(path)) {
232             LOG(ERROR) << "Failed to generate new key";
233             return false;
234         }
235     }
236 
237     return load_key(path);
238 }
239 
get_vendor_keys()240 static std::set<std::string> get_vendor_keys() {
241     const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
242     if (adb_keys_path == nullptr) {
243         return std::set<std::string>();
244     }
245 
246     std::set<std::string> result;
247     for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
248         result.emplace(path);
249     }
250     return result;
251 }
252 
adb_auth_get_private_keys()253 std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
254     std::deque<std::shared_ptr<RSA>> result;
255 
256     // Copy all the currently known keys.
257     std::lock_guard<std::mutex> lock(g_keys_mutex);
258     for (const auto& it : g_keys) {
259         result.push_back(it.second);
260     }
261 
262     // Add a sentinel to the list. Our caller uses this to mean "out of private keys,
263     // but try using the public key" (the empty deque could otherwise mean this _or_
264     // that this function hasn't been called yet to request the keys).
265     result.push_back(nullptr);
266 
267     return result;
268 }
269 
adb_auth_sign(RSA * key,const char * token,size_t token_size)270 static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) {
271     if (token_size != TOKEN_SIZE) {
272         D("Unexpected token size %zd", token_size);
273         return nullptr;
274     }
275 
276     std::string result;
277     result.resize(MAX_PAYLOAD);
278 
279     unsigned int len;
280     if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
281                   reinterpret_cast<uint8_t*>(&result[0]), &len, key)) {
282         return std::string();
283     }
284 
285     result.resize(len);
286 
287     D("adb_auth_sign len=%d", len);
288     return result;
289 }
290 
pubkey_from_privkey(std::string * out,const std::string & path)291 static bool pubkey_from_privkey(std::string* out, const std::string& path) {
292     std::shared_ptr<RSA> privkey = read_key_file(path);
293     if (!privkey) {
294         return false;
295     }
296     return calculate_public_key(out, privkey.get());
297 }
298 
adb_auth_get_userkey()299 std::string adb_auth_get_userkey() {
300     std::string path = get_user_key_path();
301     if (path.empty()) {
302         PLOG(ERROR) << "Error getting user key filename";
303         return "";
304     }
305 
306     std::string result;
307     if (!pubkey_from_privkey(&result, path)) {
308         return "";
309     }
310     return result;
311 }
312 
adb_auth_keygen(const char * filename)313 int adb_auth_keygen(const char* filename) {
314     return (generate_key(filename) == 0);
315 }
316 
adb_auth_pubkey(const char * filename)317 int adb_auth_pubkey(const char* filename) {
318     std::string pubkey;
319     if (!pubkey_from_privkey(&pubkey, filename)) {
320         return 1;
321     }
322     pubkey.push_back('\n');
323 
324     return WriteFdExactly(STDOUT_FILENO, pubkey.data(), pubkey.size()) ? 0 : 1;
325 }
326 
327 #if defined(__linux__)
adb_auth_inotify_update(int fd,unsigned fd_event,void *)328 static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
329     LOG(INFO) << "adb_auth_inotify_update called";
330     if (!(fd_event & FDE_READ)) {
331         return;
332     }
333 
334     char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
335     while (true) {
336         ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
337         if (rc == -1) {
338             if (errno == EAGAIN) {
339                 LOG(INFO) << "done reading inotify fd";
340                 break;
341             }
342             PLOG(FATAL) << "read of inotify event failed";
343         }
344 
345         // The read potentially returned multiple events.
346         char* start = buf;
347         char* end = buf + rc;
348 
349         while (start < end) {
350             inotify_event* event = reinterpret_cast<inotify_event*>(start);
351             auto root_it = g_monitored_paths.find(event->wd);
352             if (root_it == g_monitored_paths.end()) {
353                 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
354             }
355 
356             std::string path = root_it->second;
357             if (event->len > 0) {
358                 path += '/';
359                 path += event->name;
360             }
361 
362             if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
363                 if (event->mask & IN_ISDIR) {
364                     LOG(INFO) << "ignoring new directory at '" << path << "'";
365                 } else {
366                     LOG(INFO) << "observed new file at '" << path << "'";
367                     load_keys(path, false);
368                 }
369             } else {
370                 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
371                              << event->mask;
372             }
373 
374             start += sizeof(struct inotify_event) + event->len;
375         }
376     }
377 }
378 
adb_auth_inotify_init(const std::set<std::string> & paths)379 static void adb_auth_inotify_init(const std::set<std::string>& paths) {
380     LOG(INFO) << "adb_auth_inotify_init...";
381 
382     int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
383     if (infd < 0) {
384         PLOG(ERROR) << "failed to create inotify fd";
385         return;
386     }
387 
388     for (const std::string& path : paths) {
389         int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
390         if (wd < 0) {
391             PLOG(ERROR) << "failed to inotify_add_watch on path '" << path;
392             continue;
393         }
394 
395         g_monitored_paths[wd] = path;
396         LOG(INFO) << "watch descriptor " << wd << " registered for " << path;
397     }
398 
399     fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
400     fdevent_add(event, FDE_READ);
401 }
402 #endif
403 
adb_auth_init()404 void adb_auth_init() {
405     LOG(INFO) << "adb_auth_init...";
406 
407     if (!generate_userkey()) {
408         LOG(ERROR) << "Failed to generate user key";
409         return;
410     }
411 
412     const auto& key_paths = get_vendor_keys();
413 
414 #if defined(__linux__)
415     adb_auth_inotify_init(key_paths);
416 #endif
417 
418     for (const std::string& path : key_paths) {
419         load_keys(path);
420     }
421 }
422 
send_auth_publickey(atransport * t)423 static void send_auth_publickey(atransport* t) {
424     LOG(INFO) << "Calling send_auth_publickey";
425 
426     std::string key = adb_auth_get_userkey();
427     if (key.empty()) {
428         D("Failed to get user public key");
429         return;
430     }
431 
432     if (key.size() >= MAX_PAYLOAD_V1) {
433         D("User public key too large (%zu B)", key.size());
434         return;
435     }
436 
437     apacket* p = get_apacket();
438     p->msg.command = A_AUTH;
439     p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
440 
441     // adbd expects a null-terminated string.
442     p->payload.assign(key.data(), key.data() + key.size() + 1);
443     p->msg.data_length = p->payload.size();
444     send_packet(p, t);
445 }
446 
send_auth_response(const char * token,size_t token_size,atransport * t)447 void send_auth_response(const char* token, size_t token_size, atransport* t) {
448     std::shared_ptr<RSA> key = t->NextKey();
449     if (key == nullptr) {
450         // No more private keys to try, send the public key.
451         t->SetConnectionState(kCsUnauthorized);
452         t->SetConnectionEstablished(true);
453         send_auth_publickey(t);
454         return;
455     }
456 
457     LOG(INFO) << "Calling send_auth_response";
458     apacket* p = get_apacket();
459 
460     std::string result = adb_auth_sign(key.get(), token, token_size);
461     if (result.empty()) {
462         D("Error signing the token");
463         put_apacket(p);
464         return;
465     }
466 
467     p->msg.command = A_AUTH;
468     p->msg.arg0 = ADB_AUTH_SIGNATURE;
469     p->payload.assign(result.begin(), result.end());
470     p->msg.data_length = p->payload.size();
471     send_packet(p, t);
472 }
473