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_utils.h"
47#include "sysdeps.h"
48#include "transport.h"
49
50static std::mutex& g_keys_mutex = *new std::mutex;
51static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
52    *new std::map<std::string, std::shared_ptr<RSA>>;
53static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;
54
55static std::string get_user_info() {
56    LOG(INFO) << "get_user_info...";
57
58    std::string hostname;
59    if (getenv("HOSTNAME")) hostname = getenv("HOSTNAME");
60#if !defined(_WIN32)
61    char buf[64];
62    if (hostname.empty() && gethostname(buf, sizeof(buf)) != -1) hostname = buf;
63#endif
64    if (hostname.empty()) hostname = "unknown";
65
66    std::string username;
67    if (getenv("LOGNAME")) username = getenv("LOGNAME");
68#if !defined _WIN32 && !defined ADB_HOST_ON_TARGET
69    if (username.empty() && getlogin()) username = getlogin();
70#endif
71    if (username.empty()) hostname = "unknown";
72
73    return " " + username + "@" + hostname;
74}
75
76static bool write_public_keyfile(RSA* private_key, const std::string& private_key_path) {
77    LOG(INFO) << "write_public_keyfile...";
78
79    uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE];
80    if (!android_pubkey_encode(private_key, binary_key_data, sizeof(binary_key_data))) {
81        LOG(ERROR) << "Failed to convert to public key";
82        return false;
83    }
84
85    size_t expected_length;
86    if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
87        LOG(ERROR) << "Public key too large to base64 encode";
88        return false;
89    }
90
91    std::string content;
92    content.resize(expected_length);
93    size_t actual_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(&content[0]), binary_key_data,
94                                           sizeof(binary_key_data));
95    content.resize(actual_length);
96
97    content += get_user_info();
98
99    std::string path(private_key_path + ".pub");
100    if (!android::base::WriteStringToFile(content, path)) {
101        PLOG(ERROR) << "Failed to write public key to '" << path << "'";
102        return false;
103    }
104
105    return true;
106}
107
108static int generate_key(const std::string& file) {
109    LOG(INFO) << "generate_key(" << file << ")...";
110
111    mode_t old_mask;
112    FILE *f = NULL;
113    int ret = 0;
114
115    EVP_PKEY* pkey = EVP_PKEY_new();
116    BIGNUM* exponent = BN_new();
117    RSA* rsa = RSA_new();
118    if (!pkey || !exponent || !rsa) {
119        LOG(ERROR) << "Failed to allocate key";
120        goto out;
121    }
122
123    BN_set_word(exponent, RSA_F4);
124    RSA_generate_key_ex(rsa, 2048, exponent, NULL);
125    EVP_PKEY_set1_RSA(pkey, rsa);
126
127    old_mask = umask(077);
128
129    f = fopen(file.c_str(), "w");
130    if (!f) {
131        PLOG(ERROR) << "Failed to open " << file;
132        umask(old_mask);
133        goto out;
134    }
135
136    umask(old_mask);
137
138    if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL)) {
139        D("Failed to write key");
140        goto out;
141    }
142
143    if (!write_public_keyfile(rsa, file)) {
144        D("Failed to write public key");
145        goto out;
146    }
147
148    ret = 1;
149
150out:
151    if (f) fclose(f);
152    EVP_PKEY_free(pkey);
153    RSA_free(rsa);
154    BN_free(exponent);
155    return ret;
156}
157
158static std::string hash_key(RSA* key) {
159    unsigned char* pubkey = nullptr;
160    int len = i2d_RSA_PUBKEY(key, &pubkey);
161    if (len < 0) {
162        LOG(ERROR) << "failed to encode RSA public key";
163        return std::string();
164    }
165
166    std::string result;
167    result.resize(SHA256_DIGEST_LENGTH);
168    SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0]));
169    OPENSSL_free(pubkey);
170    return result;
171}
172
173static bool read_key_file(const std::string& file) {
174    LOG(INFO) << "read_key_file '" << file << "'...";
175
176    std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
177    if (!fp) {
178        PLOG(ERROR) << "Failed to open '" << file << "'";
179        return false;
180    }
181
182    RSA* key = RSA_new();
183    if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
184        LOG(ERROR) << "Failed to read key";
185        RSA_free(key);
186        return false;
187    }
188
189    std::lock_guard<std::mutex> lock(g_keys_mutex);
190    std::string fingerprint = hash_key(key);
191    if (g_keys.find(fingerprint) != g_keys.end()) {
192        LOG(INFO) << "ignoring already-loaded key: " << file;
193        RSA_free(key);
194    } else {
195        g_keys[fingerprint] = std::shared_ptr<RSA>(key, RSA_free);
196    }
197
198    return true;
199}
200
201static bool read_keys(const std::string& path, bool allow_dir = true) {
202    LOG(INFO) << "read_keys '" << path << "'...";
203
204    struct stat st;
205    if (stat(path.c_str(), &st) != 0) {
206        PLOG(ERROR) << "failed to stat '" << path << "'";
207        return false;
208    }
209
210    if (S_ISREG(st.st_mode)) {
211        return read_key_file(path);
212    } else if (S_ISDIR(st.st_mode)) {
213        if (!allow_dir) {
214            // inotify isn't recursive. It would break expectations to load keys in nested
215            // directories but not monitor them for new keys.
216            LOG(WARNING) << "refusing to recurse into directory '" << path << "'";
217            return false;
218        }
219
220        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
221        if (!dir) {
222            PLOG(ERROR) << "failed to open directory '" << path << "'";
223            return false;
224        }
225
226        bool result = false;
227        while (struct dirent* dent = readdir(dir.get())) {
228            std::string name = dent->d_name;
229
230            // We can't use dent->d_type here because it's not available on Windows.
231            if (name == "." || name == "..") {
232                continue;
233            }
234
235            if (!android::base::EndsWith(name, ".adb_key")) {
236                LOG(INFO) << "skipping non-adb_key '" << path << "/" << name << "'";
237                continue;
238            }
239
240            result |= read_key_file((path + OS_PATH_SEPARATOR + name));
241        }
242        return result;
243    }
244
245    LOG(ERROR) << "unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
246    return false;
247}
248
249static std::string get_user_key_path() {
250    return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
251}
252
253static bool get_user_key() {
254    std::string path = get_user_key_path();
255    if (path.empty()) {
256        PLOG(ERROR) << "Error getting user key filename";
257        return false;
258    }
259
260    struct stat buf;
261    if (stat(path.c_str(), &buf) == -1) {
262        LOG(INFO) << "User key '" << path << "' does not exist...";
263        if (!generate_key(path)) {
264            LOG(ERROR) << "Failed to generate new key";
265            return false;
266        }
267    }
268
269    return read_key_file(path);
270}
271
272static std::set<std::string> get_vendor_keys() {
273    const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
274    if (adb_keys_path == nullptr) {
275        return std::set<std::string>();
276    }
277
278    std::set<std::string> result;
279    for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
280        result.emplace(path);
281    }
282    return result;
283}
284
285std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
286    std::deque<std::shared_ptr<RSA>> result;
287
288    // Copy all the currently known keys.
289    std::lock_guard<std::mutex> lock(g_keys_mutex);
290    for (const auto& it : g_keys) {
291        result.push_back(it.second);
292    }
293
294    // Add a sentinel to the list. Our caller uses this to mean "out of private keys,
295    // but try using the public key" (the empty deque could otherwise mean this _or_
296    // that this function hasn't been called yet to request the keys).
297    result.push_back(nullptr);
298
299    return result;
300}
301
302static int adb_auth_sign(RSA* key, const char* token, size_t token_size, char* sig) {
303    if (token_size != TOKEN_SIZE) {
304        D("Unexpected token size %zd", token_size);
305        return 0;
306    }
307
308    unsigned int len;
309    if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
310                  reinterpret_cast<uint8_t*>(sig), &len, key)) {
311        return 0;
312    }
313
314    D("adb_auth_sign len=%d", len);
315    return (int)len;
316}
317
318std::string adb_auth_get_userkey() {
319    std::string path = get_user_key_path();
320    if (path.empty()) {
321        PLOG(ERROR) << "Error getting user key filename";
322        return "";
323    }
324    path += ".pub";
325
326    std::string content;
327    if (!android::base::ReadFileToString(path, &content)) {
328        PLOG(ERROR) << "Can't load '" << path << "'";
329        return "";
330    }
331    return content;
332}
333
334int adb_auth_keygen(const char* filename) {
335    return (generate_key(filename) == 0);
336}
337
338#if defined(__linux__)
339static 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                    read_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
390static 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
415void adb_auth_init() {
416    LOG(INFO) << "adb_auth_init...";
417
418    if (!get_user_key()) {
419        LOG(ERROR) << "Failed to get 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        read_keys(path.c_str());
431    }
432}
433
434static 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    memcpy(p->data, key.c_str(), key.size() + 1);
450
451    p->msg.command = A_AUTH;
452    p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
453
454    // adbd expects a null-terminated string.
455    p->msg.data_length = key.size() + 1;
456    send_packet(p, t);
457}
458
459void 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        send_auth_publickey(t);
464        return;
465    }
466
467    LOG(INFO) << "Calling send_auth_response";
468    apacket* p = get_apacket();
469
470    int ret = adb_auth_sign(key.get(), token, token_size, p->data);
471    if (!ret) {
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->msg.data_length = ret;
480    send_packet(p, t);
481}
482