adb_auth_host.cpp revision d81f75ae41b2eed4ae7b0911f250778f3e6ec9c2
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 TRACE_AUTH
18
19#include "sysdeps.h"
20#include "adb_auth.h"
21
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25
26#ifdef _WIN32
27#  ifndef WIN32_LEAN_AND_MEAN
28#    define WIN32_LEAN_AND_MEAN
29#  endif
30#  include "windows.h"
31#  include "shlobj.h"
32#else
33#  include <sys/types.h>
34#  include <sys/stat.h>
35#  include <unistd.h>
36#endif
37
38#include "adb.h"
39
40/* HACK: we need the RSAPublicKey struct
41 * but RSA_verify conflits with openssl */
42#define RSA_verify RSA_verify_mincrypt
43#include "mincrypt/rsa.h"
44#undef RSA_verify
45
46#include <base/strings.h>
47#include <cutils/list.h>
48
49#include <openssl/evp.h>
50#include <openssl/objects.h>
51#include <openssl/pem.h>
52#include <openssl/rsa.h>
53#include <openssl/sha.h>
54
55#if defined(OPENSSL_IS_BORINGSSL)
56#include <openssl/base64.h>
57#endif
58
59#define ANDROID_PATH   ".android"
60#define ADB_KEY_FILE   "adbkey"
61
62struct adb_private_key {
63    struct listnode node;
64    RSA *rsa;
65};
66
67static struct listnode key_list;
68
69
70/* Convert OpenSSL RSA private key to android pre-computed RSAPublicKey format */
71static int RSA_to_RSAPublicKey(RSA *rsa, RSAPublicKey *pkey)
72{
73    int ret = 1;
74    unsigned int i;
75
76    BN_CTX* ctx = BN_CTX_new();
77    BIGNUM* r32 = BN_new();
78    BIGNUM* rr = BN_new();
79    BIGNUM* r = BN_new();
80    BIGNUM* rem = BN_new();
81    BIGNUM* n = BN_new();
82    BIGNUM* n0inv = BN_new();
83
84    if (RSA_size(rsa) != RSANUMBYTES) {
85        ret = 0;
86        goto out;
87    }
88
89    BN_set_bit(r32, 32);
90    BN_copy(n, rsa->n);
91    BN_set_bit(r, RSANUMWORDS * 32);
92    BN_mod_sqr(rr, r, n, ctx);
93    BN_div(NULL, rem, n, r32, ctx);
94    BN_mod_inverse(n0inv, rem, r32, ctx);
95
96    pkey->len = RSANUMWORDS;
97    pkey->n0inv = 0 - BN_get_word(n0inv);
98    for (i = 0; i < RSANUMWORDS; i++) {
99        BN_div(rr, rem, rr, r32, ctx);
100        pkey->rr[i] = BN_get_word(rem);
101        BN_div(n, rem, n, r32, ctx);
102        pkey->n[i] = BN_get_word(rem);
103    }
104    pkey->exponent = BN_get_word(rsa->e);
105
106out:
107    BN_free(n0inv);
108    BN_free(n);
109    BN_free(rem);
110    BN_free(r);
111    BN_free(rr);
112    BN_free(r32);
113    BN_CTX_free(ctx);
114
115    return ret;
116}
117
118static void get_user_info(char *buf, size_t len)
119{
120    char hostname[1024], username[1024];
121    int ret = -1;
122
123    if (getenv("HOSTNAME") != NULL) {
124        strncpy(hostname, getenv("HOSTNAME"), sizeof(hostname));
125        hostname[sizeof(hostname)-1] = '\0';
126        ret = 0;
127    }
128
129#ifndef _WIN32
130    if (ret < 0)
131        ret = gethostname(hostname, sizeof(hostname));
132#endif
133    if (ret < 0)
134        strcpy(hostname, "unknown");
135
136    ret = -1;
137
138    if (getenv("LOGNAME") != NULL) {
139        strncpy(username, getenv("LOGNAME"), sizeof(username));
140        username[sizeof(username)-1] = '\0';
141        ret = 0;
142    }
143
144#if !defined _WIN32 && !defined ADB_HOST_ON_TARGET
145    if (ret < 0)
146        ret = getlogin_r(username, sizeof(username));
147#endif
148    if (ret < 0)
149        strcpy(username, "unknown");
150
151    ret = snprintf(buf, len, " %s@%s", username, hostname);
152    if (ret >= (signed)len)
153        buf[len - 1] = '\0';
154}
155
156static int write_public_keyfile(RSA *private_key, const char *private_key_path)
157{
158    RSAPublicKey pkey;
159    FILE *outfile = NULL;
160    char path[PATH_MAX], info[MAX_PAYLOAD];
161    uint8_t* encoded = nullptr;
162    size_t encoded_length;
163    int ret = 0;
164
165    if (snprintf(path, sizeof(path), "%s.pub", private_key_path) >=
166        (int)sizeof(path)) {
167        D("Path too long while writing public key\n");
168        return 0;
169    }
170
171    if (!RSA_to_RSAPublicKey(private_key, &pkey)) {
172        D("Failed to convert to publickey\n");
173        return 0;
174    }
175
176    outfile = fopen(path, "we");
177    if (!outfile) {
178        D("Failed to open '%s'\n", path);
179        return 0;
180    }
181
182    D("Writing public key to '%s'\n", path);
183
184#if defined(OPENSSL_IS_BORINGSSL)
185    if (!EVP_EncodedLength(&encoded_length, sizeof(pkey))) {
186        D("Public key too large to base64 encode");
187        goto out;
188    }
189#else
190    /* While we switch from OpenSSL to BoringSSL we have to implement
191     * |EVP_EncodedLength| here. */
192    encoded_length = 1 + ((sizeof(pkey) + 2) / 3 * 4);
193#endif
194
195    encoded = new uint8_t[encoded_length];
196    if (encoded == nullptr) {
197        D("Allocation failure");
198        goto out;
199    }
200
201    encoded_length = EVP_EncodeBlock(encoded, (uint8_t*) &pkey, sizeof(pkey));
202    get_user_info(info, sizeof(info));
203
204    if (fwrite(encoded, encoded_length, 1, outfile) != 1 ||
205        fwrite(info, strlen(info), 1, outfile) != 1) {
206        D("Write error while writing public key");
207        goto out;
208    }
209
210    ret = 1;
211
212 out:
213    if (outfile != NULL) {
214        fclose(outfile);
215    }
216    delete[] encoded;
217    return ret;
218}
219
220static int generate_key(const char *file)
221{
222    EVP_PKEY* pkey = EVP_PKEY_new();
223    BIGNUM* exponent = BN_new();
224    RSA* rsa = RSA_new();
225    mode_t old_mask;
226    FILE *f = NULL;
227    int ret = 0;
228
229    D("generate_key '%s'\n", file);
230
231    if (!pkey || !exponent || !rsa) {
232        D("Failed to allocate key\n");
233        goto out;
234    }
235
236    BN_set_word(exponent, RSA_F4);
237    RSA_generate_key_ex(rsa, 2048, exponent, NULL);
238    EVP_PKEY_set1_RSA(pkey, rsa);
239
240    old_mask = umask(077);
241
242    f = fopen(file, "we");
243    if (!f) {
244        D("Failed to open '%s'\n", file);
245        umask(old_mask);
246        goto out;
247    }
248
249    umask(old_mask);
250
251    if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL)) {
252        D("Failed to write key\n");
253        goto out;
254    }
255
256    if (!write_public_keyfile(rsa, file)) {
257        D("Failed to write public key\n");
258        goto out;
259    }
260
261    ret = 1;
262
263out:
264    if (f)
265        fclose(f);
266    EVP_PKEY_free(pkey);
267    RSA_free(rsa);
268    BN_free(exponent);
269    return ret;
270}
271
272static int read_key(const char *file, struct listnode *list)
273{
274    D("read_key '%s'\n", file);
275
276    FILE* fp = fopen(file, "re");
277    if (!fp) {
278        D("Failed to open '%s': %s\n", file, strerror(errno));
279        return 0;
280    }
281
282    adb_private_key* key = new adb_private_key;
283    key->rsa = RSA_new();
284
285    if (!PEM_read_RSAPrivateKey(fp, &key->rsa, NULL, NULL)) {
286        D("Failed to read key\n");
287        fclose(fp);
288        RSA_free(key->rsa);
289        delete key;
290        return 0;
291    }
292
293    fclose(fp);
294    list_add_tail(list, &key->node);
295    return 1;
296}
297
298static int get_user_keyfilepath(char *filename, size_t len)
299{
300    const char *format, *home;
301    char android_dir[PATH_MAX];
302    struct stat buf;
303#ifdef _WIN32
304    char path[PATH_MAX];
305    home = getenv("ANDROID_SDK_HOME");
306    if (!home) {
307        SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, path);
308        home = path;
309    }
310    format = "%s\\%s";
311#else
312    home = getenv("HOME");
313    if (!home)
314        return -1;
315    format = "%s/%s";
316#endif
317
318    D("home '%s'\n", home);
319
320    if (snprintf(android_dir, sizeof(android_dir), format, home,
321                        ANDROID_PATH) >= (int)sizeof(android_dir))
322        return -1;
323
324    if (stat(android_dir, &buf)) {
325        if (adb_mkdir(android_dir, 0750) < 0) {
326            D("Cannot mkdir '%s'", android_dir);
327            return -1;
328        }
329    }
330
331    return snprintf(filename, len, format, android_dir, ADB_KEY_FILE);
332}
333
334static int get_user_key(struct listnode *list)
335{
336    struct stat buf;
337    char path[PATH_MAX];
338    int ret;
339
340    ret = get_user_keyfilepath(path, sizeof(path));
341    if (ret < 0 || ret >= (signed)sizeof(path)) {
342        D("Error getting user key filename");
343        return 0;
344    }
345
346    D("user key '%s'\n", path);
347
348    if (stat(path, &buf) == -1) {
349        if (!generate_key(path)) {
350            D("Failed to generate new key\n");
351            return 0;
352        }
353    }
354
355    return read_key(path, list);
356}
357
358static void get_vendor_keys(struct listnode* key_list) {
359    const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
360    if (adb_keys_path == nullptr) {
361        return;
362    }
363
364    for (auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
365        if (!read_key(path.c_str(), key_list)) {
366            D("Failed to read '%s'\n", path.c_str());
367        }
368    }
369}
370
371int adb_auth_sign(void *node, const unsigned char* token, size_t token_size,
372                  unsigned char* sig)
373{
374    unsigned int len;
375    struct adb_private_key *key = node_to_item(node, struct adb_private_key, node);
376
377    if (token_size != TOKEN_SIZE) {
378        D("Unexpected token size %zd\n", token_size);
379        return 0;
380    }
381
382    if (!RSA_sign(NID_sha1, token, token_size, sig, &len, key->rsa)) {
383        return 0;
384    }
385
386    D("adb_auth_sign len=%d\n", len);
387    return (int)len;
388}
389
390void *adb_auth_nextkey(void *current)
391{
392    struct listnode *item;
393
394    if (list_empty(&key_list))
395        return NULL;
396
397    if (!current)
398        return list_head(&key_list);
399
400    list_for_each(item, &key_list) {
401        if (item == current) {
402            /* current is the last item, we tried all the keys */
403            if (item->next == &key_list)
404                return NULL;
405            return item->next;
406        }
407    }
408
409    return NULL;
410}
411
412int adb_auth_get_userkey(unsigned char *data, size_t len)
413{
414    char path[PATH_MAX];
415    int ret = get_user_keyfilepath(path, sizeof(path) - 4);
416    if (ret < 0 || ret >= (signed)(sizeof(path) - 4)) {
417        D("Error getting user key filename");
418        return 0;
419    }
420    strcat(path, ".pub");
421
422    // TODO(danalbert): ReadFileToString
423    unsigned size;
424    char* file_data = reinterpret_cast<char*>(load_file(path, &size));
425    if (file_data == nullptr) {
426        D("Can't load '%s'\n", path);
427        return 0;
428    }
429
430    if (len < (size_t)(size + 1)) {
431        D("%s: Content too large ret=%d\n", path, size);
432        free(file_data);
433        return 0;
434    }
435
436    memcpy(data, file_data, size);
437    free(file_data);
438    file_data = nullptr;
439    data[size] = '\0';
440
441    return size + 1;
442}
443
444int adb_auth_keygen(const char* filename) {
445    adb_trace_mask |= (1 << TRACE_AUTH);
446    return (generate_key(filename) == 0);
447}
448
449void adb_auth_init(void)
450{
451    int ret;
452
453    D("adb_auth_init\n");
454
455    list_init(&key_list);
456
457    ret = get_user_key(&key_list);
458    if (!ret) {
459        D("Failed to get user key\n");
460        return;
461    }
462
463    get_vendor_keys(&key_list);
464}
465