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