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