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