1 /* 2 * Copyright (C) 2009 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 LOG_NDEBUG 0 18 #define LOG_TAG "keystore" 19 20 #include <stdio.h> 21 #include <stdint.h> 22 #include <string.h> 23 #include <unistd.h> 24 #include <signal.h> 25 #include <errno.h> 26 #include <dirent.h> 27 #include <errno.h> 28 #include <fcntl.h> 29 #include <limits.h> 30 #include <assert.h> 31 #include <sys/types.h> 32 #include <sys/socket.h> 33 #include <sys/stat.h> 34 #include <sys/time.h> 35 #include <arpa/inet.h> 36 37 #include <openssl/aes.h> 38 #include <openssl/bio.h> 39 #include <openssl/evp.h> 40 #include <openssl/md5.h> 41 #include <openssl/pem.h> 42 43 #include <hardware/keymaster.h> 44 45 #include <keymaster/softkeymaster.h> 46 47 #include <UniquePtr.h> 48 #include <utils/String8.h> 49 #include <utils/Vector.h> 50 51 #include <keystore/IKeystoreService.h> 52 #include <binder/IPCThreadState.h> 53 #include <binder/IServiceManager.h> 54 55 #include <cutils/log.h> 56 #include <cutils/sockets.h> 57 #include <private/android_filesystem_config.h> 58 59 #include <keystore/keystore.h> 60 61 #include <selinux/android.h> 62 63 #include "defaults.h" 64 65 /* KeyStore is a secured storage for key-value pairs. In this implementation, 66 * each file stores one key-value pair. Keys are encoded in file names, and 67 * values are encrypted with checksums. The encryption key is protected by a 68 * user-defined password. To keep things simple, buffers are always larger than 69 * the maximum space we needed, so boundary checks on buffers are omitted. */ 70 71 #define KEY_SIZE ((NAME_MAX - 15) / 2) 72 #define VALUE_SIZE 32768 73 #define PASSWORD_SIZE VALUE_SIZE 74 75 76 struct BIGNUM_Delete { 77 void operator()(BIGNUM* p) const { 78 BN_free(p); 79 } 80 }; 81 typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM; 82 83 struct BIO_Delete { 84 void operator()(BIO* p) const { 85 BIO_free(p); 86 } 87 }; 88 typedef UniquePtr<BIO, BIO_Delete> Unique_BIO; 89 90 struct EVP_PKEY_Delete { 91 void operator()(EVP_PKEY* p) const { 92 EVP_PKEY_free(p); 93 } 94 }; 95 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; 96 97 struct PKCS8_PRIV_KEY_INFO_Delete { 98 void operator()(PKCS8_PRIV_KEY_INFO* p) const { 99 PKCS8_PRIV_KEY_INFO_free(p); 100 } 101 }; 102 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO; 103 104 105 static int keymaster_device_initialize(keymaster_device_t** dev) { 106 int rc; 107 108 const hw_module_t* mod; 109 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod); 110 if (rc) { 111 ALOGE("could not find any keystore module"); 112 goto out; 113 } 114 115 rc = keymaster_open(mod, dev); 116 if (rc) { 117 ALOGE("could not open keymaster device in %s (%s)", 118 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc)); 119 goto out; 120 } 121 122 return 0; 123 124 out: 125 *dev = NULL; 126 return rc; 127 } 128 129 static void keymaster_device_release(keymaster_device_t* dev) { 130 keymaster_close(dev); 131 } 132 133 /*************** 134 * PERMISSIONS * 135 ***************/ 136 137 /* Here are the permissions, actions, users, and the main function. */ 138 typedef enum { 139 P_TEST = 1 << 0, 140 P_GET = 1 << 1, 141 P_INSERT = 1 << 2, 142 P_DELETE = 1 << 3, 143 P_EXIST = 1 << 4, 144 P_SAW = 1 << 5, 145 P_RESET = 1 << 6, 146 P_PASSWORD = 1 << 7, 147 P_LOCK = 1 << 8, 148 P_UNLOCK = 1 << 9, 149 P_ZERO = 1 << 10, 150 P_SIGN = 1 << 11, 151 P_VERIFY = 1 << 12, 152 P_GRANT = 1 << 13, 153 P_DUPLICATE = 1 << 14, 154 P_CLEAR_UID = 1 << 15, 155 P_RESET_UID = 1 << 16, 156 P_SYNC_UID = 1 << 17, 157 P_PASSWORD_UID = 1 << 18, 158 } perm_t; 159 160 static struct user_euid { 161 uid_t uid; 162 uid_t euid; 163 } user_euids[] = { 164 {AID_VPN, AID_SYSTEM}, 165 {AID_WIFI, AID_SYSTEM}, 166 {AID_ROOT, AID_SYSTEM}, 167 }; 168 169 /* perm_labels associcated with keystore_key SELinux class verbs. */ 170 const char *perm_labels[] = { 171 "test", 172 "get", 173 "insert", 174 "delete", 175 "exist", 176 "saw", 177 "reset", 178 "password", 179 "lock", 180 "unlock", 181 "zero", 182 "sign", 183 "verify", 184 "grant", 185 "duplicate", 186 "clear_uid", 187 "reset_uid", 188 "sync_uid", 189 "password_uid", 190 }; 191 192 static struct user_perm { 193 uid_t uid; 194 perm_t perms; 195 } user_perms[] = { 196 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) }, 197 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) }, 198 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) }, 199 {AID_ROOT, static_cast<perm_t>(P_GET) }, 200 }; 201 202 static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN 203 | P_VERIFY); 204 205 static char *tctx; 206 static int ks_is_selinux_enabled; 207 208 static const char *get_perm_label(perm_t perm) { 209 unsigned int index = ffs(perm); 210 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) { 211 return perm_labels[index - 1]; 212 } else { 213 ALOGE("Keystore: Failed to retrieve permission label.\n"); 214 abort(); 215 } 216 } 217 218 /** 219 * Returns the app ID (in the Android multi-user sense) for the current 220 * UNIX UID. 221 */ 222 static uid_t get_app_id(uid_t uid) { 223 return uid % AID_USER; 224 } 225 226 /** 227 * Returns the user ID (in the Android multi-user sense) for the current 228 * UNIX UID. 229 */ 230 static uid_t get_user_id(uid_t uid) { 231 return uid / AID_USER; 232 } 233 234 static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) { 235 if (!ks_is_selinux_enabled) { 236 return true; 237 } 238 239 char *sctx = NULL; 240 const char *selinux_class = "keystore_key"; 241 const char *str_perm = get_perm_label(perm); 242 243 if (!str_perm) { 244 return false; 245 } 246 247 if (getpidcon(spid, &sctx) != 0) { 248 ALOGE("SELinux: Failed to get source pid context.\n"); 249 return false; 250 } 251 252 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm, 253 NULL) == 0; 254 freecon(sctx); 255 return allowed; 256 } 257 258 static bool has_permission(uid_t uid, perm_t perm, pid_t spid) { 259 // All system users are equivalent for multi-user support. 260 if (get_app_id(uid) == AID_SYSTEM) { 261 uid = AID_SYSTEM; 262 } 263 264 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) { 265 struct user_perm user = user_perms[i]; 266 if (user.uid == uid) { 267 return (user.perms & perm) && 268 keystore_selinux_check_access(uid, perm, spid); 269 } 270 } 271 272 return (DEFAULT_PERMS & perm) && 273 keystore_selinux_check_access(uid, perm, spid); 274 } 275 276 /** 277 * Returns the UID that the callingUid should act as. This is here for 278 * legacy support of the WiFi and VPN systems and should be removed 279 * when WiFi can operate in its own namespace. 280 */ 281 static uid_t get_keystore_euid(uid_t uid) { 282 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) { 283 struct user_euid user = user_euids[i]; 284 if (user.uid == uid) { 285 return user.euid; 286 } 287 } 288 289 return uid; 290 } 291 292 /** 293 * Returns true if the callingUid is allowed to interact in the targetUid's 294 * namespace. 295 */ 296 static bool is_granted_to(uid_t callingUid, uid_t targetUid) { 297 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) { 298 struct user_euid user = user_euids[i]; 299 if (user.euid == callingUid && user.uid == targetUid) { 300 return true; 301 } 302 } 303 304 return false; 305 } 306 307 /** 308 * Allow the system to perform some privileged tasks that have to do with 309 * system maintenance. This should not be used for any function that uses 310 * the keys in any way (e.g., signing). 311 */ 312 static bool is_self_or_system(uid_t callingUid, uid_t targetUid) { 313 return callingUid == targetUid || callingUid == AID_SYSTEM; 314 } 315 316 /* Here is the encoding of keys. This is necessary in order to allow arbitrary 317 * characters in keys. Characters in [0-~] are not encoded. Others are encoded 318 * into two bytes. The first byte is one of [+-.] which represents the first 319 * two bits of the character. The second byte encodes the rest of the bits into 320 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note 321 * that Base64 cannot be used here due to the need of prefix match on keys. */ 322 323 static size_t encode_key_length(const android::String8& keyName) { 324 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string()); 325 size_t length = keyName.length(); 326 for (int i = length; i > 0; --i, ++in) { 327 if (*in < '0' || *in > '~') { 328 ++length; 329 } 330 } 331 return length; 332 } 333 334 static int encode_key(char* out, const android::String8& keyName) { 335 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string()); 336 size_t length = keyName.length(); 337 for (int i = length; i > 0; --i, ++in, ++out) { 338 if (*in < '0' || *in > '~') { 339 *out = '+' + (*in >> 6); 340 *++out = '0' + (*in & 0x3F); 341 ++length; 342 } else { 343 *out = *in; 344 } 345 } 346 *out = '\0'; 347 return length; 348 } 349 350 /* 351 * Converts from the "escaped" format on disk to actual name. 352 * This will be smaller than the input string. 353 * 354 * Characters that should combine with the next at the end will be truncated. 355 */ 356 static size_t decode_key_length(const char* in, size_t length) { 357 size_t outLength = 0; 358 359 for (const char* end = in + length; in < end; in++) { 360 /* This combines with the next character. */ 361 if (*in < '0' || *in > '~') { 362 continue; 363 } 364 365 outLength++; 366 } 367 return outLength; 368 } 369 370 static void decode_key(char* out, const char* in, size_t length) { 371 for (const char* end = in + length; in < end; in++) { 372 if (*in < '0' || *in > '~') { 373 /* Truncate combining characters at the end. */ 374 if (in + 1 >= end) { 375 break; 376 } 377 378 *out = (*in++ - '+') << 6; 379 *out++ |= (*in - '0') & 0x3F; 380 } else { 381 *out++ = *in; 382 } 383 } 384 *out = '\0'; 385 } 386 387 static size_t readFully(int fd, uint8_t* data, size_t size) { 388 size_t remaining = size; 389 while (remaining > 0) { 390 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining)); 391 if (n <= 0) { 392 return size - remaining; 393 } 394 data += n; 395 remaining -= n; 396 } 397 return size; 398 } 399 400 static size_t writeFully(int fd, uint8_t* data, size_t size) { 401 size_t remaining = size; 402 while (remaining > 0) { 403 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining)); 404 if (n < 0) { 405 ALOGW("write failed: %s", strerror(errno)); 406 return size - remaining; 407 } 408 data += n; 409 remaining -= n; 410 } 411 return size; 412 } 413 414 class Entropy { 415 public: 416 Entropy() : mRandom(-1) {} 417 ~Entropy() { 418 if (mRandom >= 0) { 419 close(mRandom); 420 } 421 } 422 423 bool open() { 424 const char* randomDevice = "/dev/urandom"; 425 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY)); 426 if (mRandom < 0) { 427 ALOGE("open: %s: %s", randomDevice, strerror(errno)); 428 return false; 429 } 430 return true; 431 } 432 433 bool generate_random_data(uint8_t* data, size_t size) const { 434 return (readFully(mRandom, data, size) == size); 435 } 436 437 private: 438 int mRandom; 439 }; 440 441 /* Here is the file format. There are two parts in blob.value, the secret and 442 * the description. The secret is stored in ciphertext, and its original size 443 * can be found in blob.length. The description is stored after the secret in 444 * plaintext, and its size is specified in blob.info. The total size of the two 445 * parts must be no more than VALUE_SIZE bytes. The first field is the version, 446 * the second is the blob's type, and the third byte is flags. Fields other 447 * than blob.info, blob.length, and blob.value are modified by encryptBlob() 448 * and decryptBlob(). Thus they should not be accessed from outside. */ 449 450 /* ** Note to future implementors of encryption: ** 451 * Currently this is the construction: 452 * metadata || Enc(MD5(data) || data) 453 * 454 * This should be the construction used for encrypting if re-implementing: 455 * 456 * Derive independent keys for encryption and MAC: 457 * Kenc = AES_encrypt(masterKey, "Encrypt") 458 * Kmac = AES_encrypt(masterKey, "MAC") 459 * 460 * Store this: 461 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) || 462 * HMAC(Kmac, metadata || Enc(data)) 463 */ 464 struct __attribute__((packed)) blob { 465 uint8_t version; 466 uint8_t type; 467 uint8_t flags; 468 uint8_t info; 469 uint8_t vector[AES_BLOCK_SIZE]; 470 uint8_t encrypted[0]; // Marks offset to encrypted data. 471 uint8_t digest[MD5_DIGEST_LENGTH]; 472 uint8_t digested[0]; // Marks offset to digested data. 473 int32_t length; // in network byte order when encrypted 474 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE]; 475 }; 476 477 typedef enum { 478 TYPE_ANY = 0, // meta type that matches anything 479 TYPE_GENERIC = 1, 480 TYPE_MASTER_KEY = 2, 481 TYPE_KEY_PAIR = 3, 482 } BlobType; 483 484 static const uint8_t CURRENT_BLOB_VERSION = 2; 485 486 class Blob { 487 public: 488 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength, 489 BlobType type) { 490 mBlob.length = valueLength; 491 memcpy(mBlob.value, value, valueLength); 492 493 mBlob.info = infoLength; 494 memcpy(mBlob.value + valueLength, info, infoLength); 495 496 mBlob.version = CURRENT_BLOB_VERSION; 497 mBlob.type = uint8_t(type); 498 499 if (type == TYPE_MASTER_KEY) { 500 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED; 501 } else { 502 mBlob.flags = KEYSTORE_FLAG_NONE; 503 } 504 } 505 506 Blob(blob b) { 507 mBlob = b; 508 } 509 510 Blob() {} 511 512 const uint8_t* getValue() const { 513 return mBlob.value; 514 } 515 516 int32_t getLength() const { 517 return mBlob.length; 518 } 519 520 const uint8_t* getInfo() const { 521 return mBlob.value + mBlob.length; 522 } 523 524 uint8_t getInfoLength() const { 525 return mBlob.info; 526 } 527 528 uint8_t getVersion() const { 529 return mBlob.version; 530 } 531 532 bool isEncrypted() const { 533 if (mBlob.version < 2) { 534 return true; 535 } 536 537 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED; 538 } 539 540 void setEncrypted(bool encrypted) { 541 if (encrypted) { 542 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED; 543 } else { 544 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED; 545 } 546 } 547 548 bool isFallback() const { 549 return mBlob.flags & KEYSTORE_FLAG_FALLBACK; 550 } 551 552 void setFallback(bool fallback) { 553 if (fallback) { 554 mBlob.flags |= KEYSTORE_FLAG_FALLBACK; 555 } else { 556 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK; 557 } 558 } 559 560 void setVersion(uint8_t version) { 561 mBlob.version = version; 562 } 563 564 BlobType getType() const { 565 return BlobType(mBlob.type); 566 } 567 568 void setType(BlobType type) { 569 mBlob.type = uint8_t(type); 570 } 571 572 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) { 573 ALOGV("writing blob %s", filename); 574 if (isEncrypted()) { 575 if (state != STATE_NO_ERROR) { 576 ALOGD("couldn't insert encrypted blob while not unlocked"); 577 return LOCKED; 578 } 579 580 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) { 581 ALOGW("Could not read random data for: %s", filename); 582 return SYSTEM_ERROR; 583 } 584 } 585 586 // data includes the value and the value's length 587 size_t dataLength = mBlob.length + sizeof(mBlob.length); 588 // pad data to the AES_BLOCK_SIZE 589 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1) 590 / AES_BLOCK_SIZE * AES_BLOCK_SIZE); 591 // encrypted data includes the digest value 592 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH; 593 // move info after space for padding 594 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info); 595 // zero padding area 596 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength); 597 598 mBlob.length = htonl(mBlob.length); 599 600 if (isEncrypted()) { 601 MD5(mBlob.digested, digestedLength, mBlob.digest); 602 603 uint8_t vector[AES_BLOCK_SIZE]; 604 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE); 605 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, 606 aes_key, vector, AES_ENCRYPT); 607 } 608 609 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob); 610 size_t fileLength = encryptedLength + headerLength + mBlob.info; 611 612 const char* tmpFileName = ".tmp"; 613 int out = TEMP_FAILURE_RETRY(open(tmpFileName, 614 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)); 615 if (out < 0) { 616 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno)); 617 return SYSTEM_ERROR; 618 } 619 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength); 620 if (close(out) != 0) { 621 return SYSTEM_ERROR; 622 } 623 if (writtenBytes != fileLength) { 624 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength); 625 unlink(tmpFileName); 626 return SYSTEM_ERROR; 627 } 628 if (rename(tmpFileName, filename) == -1) { 629 ALOGW("could not rename blob to %s: %s", filename, strerror(errno)); 630 return SYSTEM_ERROR; 631 } 632 return NO_ERROR; 633 } 634 635 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) { 636 ALOGV("reading blob %s", filename); 637 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY)); 638 if (in < 0) { 639 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR; 640 } 641 // fileLength may be less than sizeof(mBlob) since the in 642 // memory version has extra padding to tolerate rounding up to 643 // the AES_BLOCK_SIZE 644 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob)); 645 if (close(in) != 0) { 646 return SYSTEM_ERROR; 647 } 648 649 if (isEncrypted() && (state != STATE_NO_ERROR)) { 650 return LOCKED; 651 } 652 653 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob); 654 if (fileLength < headerLength) { 655 return VALUE_CORRUPTED; 656 } 657 658 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info); 659 if (encryptedLength < 0) { 660 return VALUE_CORRUPTED; 661 } 662 663 ssize_t digestedLength; 664 if (isEncrypted()) { 665 if (encryptedLength % AES_BLOCK_SIZE != 0) { 666 return VALUE_CORRUPTED; 667 } 668 669 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key, 670 mBlob.vector, AES_DECRYPT); 671 digestedLength = encryptedLength - MD5_DIGEST_LENGTH; 672 uint8_t computedDigest[MD5_DIGEST_LENGTH]; 673 MD5(mBlob.digested, digestedLength, computedDigest); 674 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) { 675 return VALUE_CORRUPTED; 676 } 677 } else { 678 digestedLength = encryptedLength; 679 } 680 681 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length); 682 mBlob.length = ntohl(mBlob.length); 683 if (mBlob.length < 0 || mBlob.length > maxValueLength) { 684 return VALUE_CORRUPTED; 685 } 686 if (mBlob.info != 0) { 687 // move info from after padding to after data 688 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info); 689 } 690 return ::NO_ERROR; 691 } 692 693 private: 694 struct blob mBlob; 695 }; 696 697 class UserState { 698 public: 699 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) { 700 asprintf(&mUserDir, "user_%u", mUserId); 701 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir); 702 } 703 704 ~UserState() { 705 free(mUserDir); 706 free(mMasterKeyFile); 707 } 708 709 bool initialize() { 710 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) { 711 ALOGE("Could not create directory '%s'", mUserDir); 712 return false; 713 } 714 715 if (access(mMasterKeyFile, R_OK) == 0) { 716 setState(STATE_LOCKED); 717 } else { 718 setState(STATE_UNINITIALIZED); 719 } 720 721 return true; 722 } 723 724 uid_t getUserId() const { 725 return mUserId; 726 } 727 728 const char* getUserDirName() const { 729 return mUserDir; 730 } 731 732 const char* getMasterKeyFileName() const { 733 return mMasterKeyFile; 734 } 735 736 void setState(State state) { 737 mState = state; 738 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) { 739 mRetry = MAX_RETRY; 740 } 741 } 742 743 State getState() const { 744 return mState; 745 } 746 747 int8_t getRetry() const { 748 return mRetry; 749 } 750 751 void zeroizeMasterKeysInMemory() { 752 memset(mMasterKey, 0, sizeof(mMasterKey)); 753 memset(mSalt, 0, sizeof(mSalt)); 754 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption)); 755 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption)); 756 } 757 758 ResponseCode initialize(const android::String8& pw, Entropy* entropy) { 759 if (!generateMasterKey(entropy)) { 760 return SYSTEM_ERROR; 761 } 762 ResponseCode response = writeMasterKey(pw, entropy); 763 if (response != NO_ERROR) { 764 return response; 765 } 766 setupMasterKeys(); 767 return ::NO_ERROR; 768 } 769 770 ResponseCode copyMasterKey(UserState* src) { 771 if (mState != STATE_UNINITIALIZED) { 772 return ::SYSTEM_ERROR; 773 } 774 if (src->getState() != STATE_NO_ERROR) { 775 return ::SYSTEM_ERROR; 776 } 777 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES); 778 setupMasterKeys(); 779 return ::NO_ERROR; 780 } 781 782 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) { 783 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES]; 784 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt); 785 AES_KEY passwordAesKey; 786 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey); 787 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY); 788 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy); 789 } 790 791 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) { 792 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY)); 793 if (in < 0) { 794 return SYSTEM_ERROR; 795 } 796 797 // we read the raw blob to just to get the salt to generate 798 // the AES key, then we create the Blob to use with decryptBlob 799 blob rawBlob; 800 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob)); 801 if (close(in) != 0) { 802 return SYSTEM_ERROR; 803 } 804 // find salt at EOF if present, otherwise we have an old file 805 uint8_t* salt; 806 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) { 807 salt = (uint8_t*) &rawBlob + length - SALT_SIZE; 808 } else { 809 salt = NULL; 810 } 811 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES]; 812 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt); 813 AES_KEY passwordAesKey; 814 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey); 815 Blob masterKeyBlob(rawBlob); 816 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey, 817 STATE_NO_ERROR); 818 if (response == SYSTEM_ERROR) { 819 return response; 820 } 821 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) { 822 // if salt was missing, generate one and write a new master key file with the salt. 823 if (salt == NULL) { 824 if (!generateSalt(entropy)) { 825 return SYSTEM_ERROR; 826 } 827 response = writeMasterKey(pw, entropy); 828 } 829 if (response == NO_ERROR) { 830 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES); 831 setupMasterKeys(); 832 } 833 return response; 834 } 835 if (mRetry <= 0) { 836 reset(); 837 return UNINITIALIZED; 838 } 839 --mRetry; 840 switch (mRetry) { 841 case 0: return WRONG_PASSWORD_0; 842 case 1: return WRONG_PASSWORD_1; 843 case 2: return WRONG_PASSWORD_2; 844 case 3: return WRONG_PASSWORD_3; 845 default: return WRONG_PASSWORD_3; 846 } 847 } 848 849 AES_KEY* getEncryptionKey() { 850 return &mMasterKeyEncryption; 851 } 852 853 AES_KEY* getDecryptionKey() { 854 return &mMasterKeyDecryption; 855 } 856 857 bool reset() { 858 DIR* dir = opendir(getUserDirName()); 859 if (!dir) { 860 ALOGW("couldn't open user directory: %s", strerror(errno)); 861 return false; 862 } 863 864 struct dirent* file; 865 while ((file = readdir(dir)) != NULL) { 866 // We only care about files. 867 if (file->d_type != DT_REG) { 868 continue; 869 } 870 871 // Skip anything that starts with a "." 872 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) { 873 continue; 874 } 875 876 unlinkat(dirfd(dir), file->d_name, 0); 877 } 878 closedir(dir); 879 return true; 880 } 881 882 private: 883 static const int MASTER_KEY_SIZE_BYTES = 16; 884 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8; 885 886 static const int MAX_RETRY = 4; 887 static const size_t SALT_SIZE = 16; 888 889 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw, 890 uint8_t* salt) { 891 size_t saltSize; 892 if (salt != NULL) { 893 saltSize = SALT_SIZE; 894 } else { 895 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found 896 salt = (uint8_t*) "keystore"; 897 // sizeof = 9, not strlen = 8 898 saltSize = sizeof("keystore"); 899 } 900 901 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt, 902 saltSize, 8192, keySize, key); 903 } 904 905 bool generateSalt(Entropy* entropy) { 906 return entropy->generate_random_data(mSalt, sizeof(mSalt)); 907 } 908 909 bool generateMasterKey(Entropy* entropy) { 910 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) { 911 return false; 912 } 913 if (!generateSalt(entropy)) { 914 return false; 915 } 916 return true; 917 } 918 919 void setupMasterKeys() { 920 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption); 921 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption); 922 setState(STATE_NO_ERROR); 923 } 924 925 uid_t mUserId; 926 927 char* mUserDir; 928 char* mMasterKeyFile; 929 930 State mState; 931 int8_t mRetry; 932 933 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES]; 934 uint8_t mSalt[SALT_SIZE]; 935 936 AES_KEY mMasterKeyEncryption; 937 AES_KEY mMasterKeyDecryption; 938 }; 939 940 typedef struct { 941 uint32_t uid; 942 const uint8_t* filename; 943 } grant_t; 944 945 class KeyStore { 946 public: 947 KeyStore(Entropy* entropy, keymaster_device_t* device) 948 : mEntropy(entropy) 949 , mDevice(device) 950 { 951 memset(&mMetaData, '\0', sizeof(mMetaData)); 952 } 953 954 ~KeyStore() { 955 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); 956 it != mGrants.end(); it++) { 957 delete *it; 958 } 959 mGrants.clear(); 960 961 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); 962 it != mMasterKeys.end(); it++) { 963 delete *it; 964 } 965 mMasterKeys.clear(); 966 } 967 968 keymaster_device_t* getDevice() const { 969 return mDevice; 970 } 971 972 ResponseCode initialize() { 973 readMetaData(); 974 if (upgradeKeystore()) { 975 writeMetaData(); 976 } 977 978 return ::NO_ERROR; 979 } 980 981 State getState(uid_t uid) { 982 return getUserState(uid)->getState(); 983 } 984 985 ResponseCode initializeUser(const android::String8& pw, uid_t uid) { 986 UserState* userState = getUserState(uid); 987 return userState->initialize(pw, mEntropy); 988 } 989 990 ResponseCode copyMasterKey(uid_t src, uid_t uid) { 991 UserState *userState = getUserState(uid); 992 UserState *initState = getUserState(src); 993 return userState->copyMasterKey(initState); 994 } 995 996 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) { 997 UserState* userState = getUserState(uid); 998 return userState->writeMasterKey(pw, mEntropy); 999 } 1000 1001 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) { 1002 UserState* userState = getUserState(uid); 1003 return userState->readMasterKey(pw, mEntropy); 1004 } 1005 1006 android::String8 getKeyName(const android::String8& keyName) { 1007 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 1008 encode_key(encoded, keyName); 1009 return android::String8(encoded); 1010 } 1011 1012 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) { 1013 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 1014 encode_key(encoded, keyName); 1015 return android::String8::format("%u_%s", uid, encoded); 1016 } 1017 1018 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) { 1019 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 1020 encode_key(encoded, keyName); 1021 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid, 1022 encoded); 1023 } 1024 1025 bool reset(uid_t uid) { 1026 android::String8 prefix(""); 1027 android::Vector<android::String16> aliases; 1028 if (saw(prefix, &aliases, uid) != ::NO_ERROR) { 1029 return ::SYSTEM_ERROR; 1030 } 1031 1032 UserState* userState = getUserState(uid); 1033 for (uint32_t i = 0; i < aliases.size(); i++) { 1034 android::String8 filename(aliases[i]); 1035 filename = android::String8::format("%s/%s", userState->getUserDirName(), 1036 getKeyName(filename).string()); 1037 del(filename, ::TYPE_ANY, uid); 1038 } 1039 1040 userState->zeroizeMasterKeysInMemory(); 1041 userState->setState(STATE_UNINITIALIZED); 1042 return userState->reset(); 1043 } 1044 1045 bool isEmpty(uid_t uid) const { 1046 const UserState* userState = getUserState(uid); 1047 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) { 1048 return true; 1049 } 1050 1051 DIR* dir = opendir(userState->getUserDirName()); 1052 if (!dir) { 1053 return true; 1054 } 1055 1056 bool result = true; 1057 struct dirent* file; 1058 while ((file = readdir(dir)) != NULL) { 1059 // We only care about files. 1060 if (file->d_type != DT_REG) { 1061 continue; 1062 } 1063 1064 // Skip anything that starts with a "." 1065 if (file->d_name[0] == '.') { 1066 continue; 1067 } 1068 1069 result = false; 1070 break; 1071 } 1072 closedir(dir); 1073 return result; 1074 } 1075 1076 void lock(uid_t uid) { 1077 UserState* userState = getUserState(uid); 1078 userState->zeroizeMasterKeysInMemory(); 1079 userState->setState(STATE_LOCKED); 1080 } 1081 1082 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) { 1083 UserState* userState = getUserState(uid); 1084 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(), 1085 userState->getState()); 1086 if (rc != NO_ERROR) { 1087 return rc; 1088 } 1089 1090 const uint8_t version = keyBlob->getVersion(); 1091 if (version < CURRENT_BLOB_VERSION) { 1092 /* If we upgrade the key, we need to write it to disk again. Then 1093 * it must be read it again since the blob is encrypted each time 1094 * it's written. 1095 */ 1096 if (upgradeBlob(filename, keyBlob, version, type, uid)) { 1097 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR 1098 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(), 1099 userState->getState())) != NO_ERROR) { 1100 return rc; 1101 } 1102 } 1103 } 1104 1105 /* 1106 * This will upgrade software-backed keys to hardware-backed keys when 1107 * the HAL for the device supports the newer key types. 1108 */ 1109 if (rc == NO_ERROR && type == TYPE_KEY_PAIR 1110 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 1111 && keyBlob->isFallback()) { 1112 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename, 1113 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); 1114 1115 // The HAL allowed the import, reget the key to have the "fresh" 1116 // version. 1117 if (imported == NO_ERROR) { 1118 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid); 1119 } 1120 } 1121 1122 if (type != TYPE_ANY && keyBlob->getType() != type) { 1123 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type); 1124 return KEY_NOT_FOUND; 1125 } 1126 1127 return rc; 1128 } 1129 1130 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) { 1131 UserState* userState = getUserState(uid); 1132 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(), 1133 mEntropy); 1134 } 1135 1136 ResponseCode del(const char *filename, const BlobType type, uid_t uid) { 1137 Blob keyBlob; 1138 ResponseCode rc = get(filename, &keyBlob, type, uid); 1139 if (rc != ::NO_ERROR) { 1140 return rc; 1141 } 1142 1143 if (keyBlob.getType() == ::TYPE_KEY_PAIR) { 1144 // A device doesn't have to implement delete_keypair. 1145 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) { 1146 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) { 1147 rc = ::SYSTEM_ERROR; 1148 } 1149 } 1150 } 1151 if (rc != ::NO_ERROR) { 1152 return rc; 1153 } 1154 1155 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR; 1156 } 1157 1158 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches, 1159 uid_t uid) { 1160 1161 UserState* userState = getUserState(uid); 1162 size_t n = prefix.length(); 1163 1164 DIR* dir = opendir(userState->getUserDirName()); 1165 if (!dir) { 1166 ALOGW("can't open directory for user: %s", strerror(errno)); 1167 return ::SYSTEM_ERROR; 1168 } 1169 1170 struct dirent* file; 1171 while ((file = readdir(dir)) != NULL) { 1172 // We only care about files. 1173 if (file->d_type != DT_REG) { 1174 continue; 1175 } 1176 1177 // Skip anything that starts with a "." 1178 if (file->d_name[0] == '.') { 1179 continue; 1180 } 1181 1182 if (!strncmp(prefix.string(), file->d_name, n)) { 1183 const char* p = &file->d_name[n]; 1184 size_t plen = strlen(p); 1185 1186 size_t extra = decode_key_length(p, plen); 1187 char *match = (char*) malloc(extra + 1); 1188 if (match != NULL) { 1189 decode_key(match, p, plen); 1190 matches->push(android::String16(match, extra)); 1191 free(match); 1192 } else { 1193 ALOGW("could not allocate match of size %zd", extra); 1194 } 1195 } 1196 } 1197 closedir(dir); 1198 return ::NO_ERROR; 1199 } 1200 1201 void addGrant(const char* filename, uid_t granteeUid) { 1202 const grant_t* existing = getGrant(filename, granteeUid); 1203 if (existing == NULL) { 1204 grant_t* grant = new grant_t; 1205 grant->uid = granteeUid; 1206 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename)); 1207 mGrants.add(grant); 1208 } 1209 } 1210 1211 bool removeGrant(const char* filename, uid_t granteeUid) { 1212 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); 1213 it != mGrants.end(); it++) { 1214 grant_t* grant = *it; 1215 if (grant->uid == granteeUid 1216 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) { 1217 mGrants.erase(it); 1218 return true; 1219 } 1220 } 1221 return false; 1222 } 1223 1224 bool hasGrant(const char* filename, const uid_t uid) const { 1225 return getGrant(filename, uid) != NULL; 1226 } 1227 1228 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid, 1229 int32_t flags) { 1230 uint8_t* data; 1231 size_t dataLength; 1232 int rc; 1233 1234 if (mDevice->import_keypair == NULL) { 1235 ALOGE("Keymaster doesn't support import!"); 1236 return SYSTEM_ERROR; 1237 } 1238 1239 bool isFallback = false; 1240 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength); 1241 if (rc) { 1242 /* 1243 * Maybe the device doesn't support this type of key. Try to use the 1244 * software fallback keymaster implementation. This is a little bit 1245 * lazier than checking the PKCS#8 key type, but the software 1246 * implementation will do that anyway. 1247 */ 1248 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength); 1249 isFallback = true; 1250 1251 if (rc) { 1252 ALOGE("Error while importing keypair: %d", rc); 1253 return SYSTEM_ERROR; 1254 } 1255 } 1256 1257 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR); 1258 free(data); 1259 1260 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 1261 keyBlob.setFallback(isFallback); 1262 1263 return put(filename, &keyBlob, uid); 1264 } 1265 1266 bool isHardwareBacked(const android::String16& keyType) const { 1267 if (mDevice == NULL) { 1268 ALOGW("can't get keymaster device"); 1269 return false; 1270 } 1271 1272 if (sRSAKeyType == keyType) { 1273 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0; 1274 } else { 1275 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 1276 && (mDevice->common.module->module_api_version 1277 >= KEYMASTER_MODULE_API_VERSION_0_2); 1278 } 1279 } 1280 1281 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid, 1282 const BlobType type) { 1283 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid)); 1284 1285 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid); 1286 if (responseCode == NO_ERROR) { 1287 return responseCode; 1288 } 1289 1290 // If this is one of the legacy UID->UID mappings, use it. 1291 uid_t euid = get_keystore_euid(uid); 1292 if (euid != uid) { 1293 filepath8 = getKeyNameForUidWithDir(keyName, euid); 1294 responseCode = get(filepath8.string(), keyBlob, type, uid); 1295 if (responseCode == NO_ERROR) { 1296 return responseCode; 1297 } 1298 } 1299 1300 // They might be using a granted key. 1301 android::String8 filename8 = getKeyName(keyName); 1302 char* end; 1303 strtoul(filename8.string(), &end, 10); 1304 if (end[0] != '_' || end[1] == 0) { 1305 return KEY_NOT_FOUND; 1306 } 1307 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(), 1308 filename8.string()); 1309 if (!hasGrant(filepath8.string(), uid)) { 1310 return responseCode; 1311 } 1312 1313 // It is a granted key. Try to load it. 1314 return get(filepath8.string(), keyBlob, type, uid); 1315 } 1316 1317 /** 1318 * Returns any existing UserState or creates it if it doesn't exist. 1319 */ 1320 UserState* getUserState(uid_t uid) { 1321 uid_t userId = get_user_id(uid); 1322 1323 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); 1324 it != mMasterKeys.end(); it++) { 1325 UserState* state = *it; 1326 if (state->getUserId() == userId) { 1327 return state; 1328 } 1329 } 1330 1331 UserState* userState = new UserState(userId); 1332 if (!userState->initialize()) { 1333 /* There's not much we can do if initialization fails. Trying to 1334 * unlock the keystore for that user will fail as well, so any 1335 * subsequent request for this user will just return SYSTEM_ERROR. 1336 */ 1337 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId); 1338 } 1339 mMasterKeys.add(userState); 1340 return userState; 1341 } 1342 1343 /** 1344 * Returns NULL if the UserState doesn't already exist. 1345 */ 1346 const UserState* getUserState(uid_t uid) const { 1347 uid_t userId = get_user_id(uid); 1348 1349 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin()); 1350 it != mMasterKeys.end(); it++) { 1351 UserState* state = *it; 1352 if (state->getUserId() == userId) { 1353 return state; 1354 } 1355 } 1356 1357 return NULL; 1358 } 1359 1360 private: 1361 static const char* sOldMasterKey; 1362 static const char* sMetaDataFile; 1363 static const android::String16 sRSAKeyType; 1364 Entropy* mEntropy; 1365 1366 keymaster_device_t* mDevice; 1367 1368 android::Vector<UserState*> mMasterKeys; 1369 1370 android::Vector<grant_t*> mGrants; 1371 1372 typedef struct { 1373 uint32_t version; 1374 } keystore_metadata_t; 1375 1376 keystore_metadata_t mMetaData; 1377 1378 const grant_t* getGrant(const char* filename, uid_t uid) const { 1379 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); 1380 it != mGrants.end(); it++) { 1381 grant_t* grant = *it; 1382 if (grant->uid == uid 1383 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) { 1384 return grant; 1385 } 1386 } 1387 return NULL; 1388 } 1389 1390 /** 1391 * Upgrade code. This will upgrade the key from the current version 1392 * to whatever is newest. 1393 */ 1394 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion, 1395 const BlobType type, uid_t uid) { 1396 bool updated = false; 1397 uint8_t version = oldVersion; 1398 1399 /* From V0 -> V1: All old types were unknown */ 1400 if (version == 0) { 1401 ALOGV("upgrading to version 1 and setting type %d", type); 1402 1403 blob->setType(type); 1404 if (type == TYPE_KEY_PAIR) { 1405 importBlobAsKey(blob, filename, uid); 1406 } 1407 version = 1; 1408 updated = true; 1409 } 1410 1411 /* From V1 -> V2: All old keys were encrypted */ 1412 if (version == 1) { 1413 ALOGV("upgrading to version 2"); 1414 1415 blob->setEncrypted(true); 1416 version = 2; 1417 updated = true; 1418 } 1419 1420 /* 1421 * If we've updated, set the key blob to the right version 1422 * and write it. 1423 */ 1424 if (updated) { 1425 ALOGV("updated and writing file %s", filename); 1426 blob->setVersion(version); 1427 } 1428 1429 return updated; 1430 } 1431 1432 /** 1433 * Takes a blob that is an PEM-encoded RSA key as a byte array and 1434 * converts it to a DER-encoded PKCS#8 for import into a keymaster. 1435 * Then it overwrites the original blob with the new blob 1436 * format that is returned from the keymaster. 1437 */ 1438 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) { 1439 // We won't even write to the blob directly with this BIO, so const_cast is okay. 1440 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength())); 1441 if (b.get() == NULL) { 1442 ALOGE("Problem instantiating BIO"); 1443 return SYSTEM_ERROR; 1444 } 1445 1446 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL)); 1447 if (pkey.get() == NULL) { 1448 ALOGE("Couldn't read old PEM file"); 1449 return SYSTEM_ERROR; 1450 } 1451 1452 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get())); 1453 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL); 1454 if (len < 0) { 1455 ALOGE("Couldn't measure PKCS#8 length"); 1456 return SYSTEM_ERROR; 1457 } 1458 1459 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]); 1460 uint8_t* tmp = pkcs8key.get(); 1461 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) { 1462 ALOGE("Couldn't convert to PKCS#8"); 1463 return SYSTEM_ERROR; 1464 } 1465 1466 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid, 1467 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); 1468 if (rc != NO_ERROR) { 1469 return rc; 1470 } 1471 1472 return get(filename, blob, TYPE_KEY_PAIR, uid); 1473 } 1474 1475 void readMetaData() { 1476 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY)); 1477 if (in < 0) { 1478 return; 1479 } 1480 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData)); 1481 if (fileLength != sizeof(mMetaData)) { 1482 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, 1483 sizeof(mMetaData)); 1484 } 1485 close(in); 1486 } 1487 1488 void writeMetaData() { 1489 const char* tmpFileName = ".metadata.tmp"; 1490 int out = TEMP_FAILURE_RETRY(open(tmpFileName, 1491 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)); 1492 if (out < 0) { 1493 ALOGE("couldn't write metadata file: %s", strerror(errno)); 1494 return; 1495 } 1496 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData)); 1497 if (fileLength != sizeof(mMetaData)) { 1498 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength, 1499 sizeof(mMetaData)); 1500 } 1501 close(out); 1502 rename(tmpFileName, sMetaDataFile); 1503 } 1504 1505 bool upgradeKeystore() { 1506 bool upgraded = false; 1507 1508 if (mMetaData.version == 0) { 1509 UserState* userState = getUserState(0); 1510 1511 // Initialize first so the directory is made. 1512 userState->initialize(); 1513 1514 // Migrate the old .masterkey file to user 0. 1515 if (access(sOldMasterKey, R_OK) == 0) { 1516 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) { 1517 ALOGE("couldn't migrate old masterkey: %s", strerror(errno)); 1518 return false; 1519 } 1520 } 1521 1522 // Initialize again in case we had a key. 1523 userState->initialize(); 1524 1525 // Try to migrate existing keys. 1526 DIR* dir = opendir("."); 1527 if (!dir) { 1528 // Give up now; maybe we can upgrade later. 1529 ALOGE("couldn't open keystore's directory; something is wrong"); 1530 return false; 1531 } 1532 1533 struct dirent* file; 1534 while ((file = readdir(dir)) != NULL) { 1535 // We only care about files. 1536 if (file->d_type != DT_REG) { 1537 continue; 1538 } 1539 1540 // Skip anything that starts with a "." 1541 if (file->d_name[0] == '.') { 1542 continue; 1543 } 1544 1545 // Find the current file's user. 1546 char* end; 1547 unsigned long thisUid = strtoul(file->d_name, &end, 10); 1548 if (end[0] != '_' || end[1] == 0) { 1549 continue; 1550 } 1551 UserState* otherUser = getUserState(thisUid); 1552 if (otherUser->getUserId() != 0) { 1553 unlinkat(dirfd(dir), file->d_name, 0); 1554 } 1555 1556 // Rename the file into user directory. 1557 DIR* otherdir = opendir(otherUser->getUserDirName()); 1558 if (otherdir == NULL) { 1559 ALOGW("couldn't open user directory for rename"); 1560 continue; 1561 } 1562 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) { 1563 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno)); 1564 } 1565 closedir(otherdir); 1566 } 1567 closedir(dir); 1568 1569 mMetaData.version = 1; 1570 upgraded = true; 1571 } 1572 1573 return upgraded; 1574 } 1575 }; 1576 1577 const char* KeyStore::sOldMasterKey = ".masterkey"; 1578 const char* KeyStore::sMetaDataFile = ".metadata"; 1579 1580 const android::String16 KeyStore::sRSAKeyType("RSA"); 1581 1582 namespace android { 1583 class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient { 1584 public: 1585 KeyStoreProxy(KeyStore* keyStore) 1586 : mKeyStore(keyStore) 1587 { 1588 } 1589 1590 void binderDied(const wp<IBinder>&) { 1591 ALOGE("binder death detected"); 1592 } 1593 1594 int32_t test() { 1595 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1596 pid_t spid = IPCThreadState::self()->getCallingPid(); 1597 if (!has_permission(callingUid, P_TEST, spid)) { 1598 ALOGW("permission denied for %d: test", callingUid); 1599 return ::PERMISSION_DENIED; 1600 } 1601 1602 return mKeyStore->getState(callingUid); 1603 } 1604 1605 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) { 1606 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1607 pid_t spid = IPCThreadState::self()->getCallingPid(); 1608 if (!has_permission(callingUid, P_GET, spid)) { 1609 ALOGW("permission denied for %d: get", callingUid); 1610 return ::PERMISSION_DENIED; 1611 } 1612 1613 String8 name8(name); 1614 Blob keyBlob; 1615 1616 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 1617 TYPE_GENERIC); 1618 if (responseCode != ::NO_ERROR) { 1619 ALOGW("Could not read %s", name8.string()); 1620 *item = NULL; 1621 *itemLength = 0; 1622 return responseCode; 1623 } 1624 1625 *item = (uint8_t*) malloc(keyBlob.getLength()); 1626 memcpy(*item, keyBlob.getValue(), keyBlob.getLength()); 1627 *itemLength = keyBlob.getLength(); 1628 1629 return ::NO_ERROR; 1630 } 1631 1632 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid, 1633 int32_t flags) { 1634 pid_t spid = IPCThreadState::self()->getCallingPid(); 1635 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1636 if (!has_permission(callingUid, P_INSERT, spid)) { 1637 ALOGW("permission denied for %d: insert", callingUid); 1638 return ::PERMISSION_DENIED; 1639 } 1640 1641 State state = mKeyStore->getState(callingUid); 1642 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) { 1643 ALOGD("calling get in state: %d", state); 1644 return state; 1645 } 1646 1647 if (targetUid == -1) { 1648 targetUid = callingUid; 1649 } else if (!is_granted_to(callingUid, targetUid)) { 1650 return ::PERMISSION_DENIED; 1651 } 1652 1653 String8 name8(name); 1654 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1655 1656 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC); 1657 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 1658 1659 return mKeyStore->put(filename.string(), &keyBlob, targetUid); 1660 } 1661 1662 int32_t del(const String16& name, int targetUid) { 1663 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1664 pid_t spid = IPCThreadState::self()->getCallingPid(); 1665 if (!has_permission(callingUid, P_DELETE, spid)) { 1666 ALOGW("permission denied for %d: del", callingUid); 1667 return ::PERMISSION_DENIED; 1668 } 1669 1670 if (targetUid == -1) { 1671 targetUid = callingUid; 1672 } else if (!is_granted_to(callingUid, targetUid)) { 1673 return ::PERMISSION_DENIED; 1674 } 1675 1676 String8 name8(name); 1677 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1678 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid); 1679 } 1680 1681 int32_t exist(const String16& name, int targetUid) { 1682 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1683 pid_t spid = IPCThreadState::self()->getCallingPid(); 1684 if (!has_permission(callingUid, P_EXIST, spid)) { 1685 ALOGW("permission denied for %d: exist", callingUid); 1686 return ::PERMISSION_DENIED; 1687 } 1688 1689 if (targetUid == -1) { 1690 targetUid = callingUid; 1691 } else if (!is_granted_to(callingUid, targetUid)) { 1692 return ::PERMISSION_DENIED; 1693 } 1694 1695 String8 name8(name); 1696 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1697 1698 if (access(filename.string(), R_OK) == -1) { 1699 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND; 1700 } 1701 return ::NO_ERROR; 1702 } 1703 1704 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) { 1705 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1706 pid_t spid = IPCThreadState::self()->getCallingPid(); 1707 if (!has_permission(callingUid, P_SAW, spid)) { 1708 ALOGW("permission denied for %d: saw", callingUid); 1709 return ::PERMISSION_DENIED; 1710 } 1711 1712 if (targetUid == -1) { 1713 targetUid = callingUid; 1714 } else if (!is_granted_to(callingUid, targetUid)) { 1715 return ::PERMISSION_DENIED; 1716 } 1717 1718 const String8 prefix8(prefix); 1719 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid)); 1720 1721 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) { 1722 return ::SYSTEM_ERROR; 1723 } 1724 return ::NO_ERROR; 1725 } 1726 1727 int32_t reset() { 1728 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1729 pid_t spid = IPCThreadState::self()->getCallingPid(); 1730 if (!has_permission(callingUid, P_RESET, spid)) { 1731 ALOGW("permission denied for %d: reset", callingUid); 1732 return ::PERMISSION_DENIED; 1733 } 1734 1735 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR; 1736 } 1737 1738 /* 1739 * Here is the history. To improve the security, the parameters to generate the 1740 * master key has been changed. To make a seamless transition, we update the 1741 * file using the same password when the user unlock it for the first time. If 1742 * any thing goes wrong during the transition, the new file will not overwrite 1743 * the old one. This avoids permanent damages of the existing data. 1744 */ 1745 int32_t password(const String16& password) { 1746 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1747 pid_t spid = IPCThreadState::self()->getCallingPid(); 1748 if (!has_permission(callingUid, P_PASSWORD, spid)) { 1749 ALOGW("permission denied for %d: password", callingUid); 1750 return ::PERMISSION_DENIED; 1751 } 1752 1753 const String8 password8(password); 1754 1755 switch (mKeyStore->getState(callingUid)) { 1756 case ::STATE_UNINITIALIZED: { 1757 // generate master key, encrypt with password, write to file, initialize mMasterKey*. 1758 return mKeyStore->initializeUser(password8, callingUid); 1759 } 1760 case ::STATE_NO_ERROR: { 1761 // rewrite master key with new password. 1762 return mKeyStore->writeMasterKey(password8, callingUid); 1763 } 1764 case ::STATE_LOCKED: { 1765 // read master key, decrypt with password, initialize mMasterKey*. 1766 return mKeyStore->readMasterKey(password8, callingUid); 1767 } 1768 } 1769 return ::SYSTEM_ERROR; 1770 } 1771 1772 int32_t lock() { 1773 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1774 pid_t spid = IPCThreadState::self()->getCallingPid(); 1775 if (!has_permission(callingUid, P_LOCK, spid)) { 1776 ALOGW("permission denied for %d: lock", callingUid); 1777 return ::PERMISSION_DENIED; 1778 } 1779 1780 State state = mKeyStore->getState(callingUid); 1781 if (state != ::STATE_NO_ERROR) { 1782 ALOGD("calling lock in state: %d", state); 1783 return state; 1784 } 1785 1786 mKeyStore->lock(callingUid); 1787 return ::NO_ERROR; 1788 } 1789 1790 int32_t unlock(const String16& pw) { 1791 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1792 pid_t spid = IPCThreadState::self()->getCallingPid(); 1793 if (!has_permission(callingUid, P_UNLOCK, spid)) { 1794 ALOGW("permission denied for %d: unlock", callingUid); 1795 return ::PERMISSION_DENIED; 1796 } 1797 1798 State state = mKeyStore->getState(callingUid); 1799 if (state != ::STATE_LOCKED) { 1800 ALOGD("calling unlock when not locked"); 1801 return state; 1802 } 1803 1804 const String8 password8(pw); 1805 return password(pw); 1806 } 1807 1808 int32_t zero() { 1809 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1810 pid_t spid = IPCThreadState::self()->getCallingPid(); 1811 if (!has_permission(callingUid, P_ZERO, spid)) { 1812 ALOGW("permission denied for %d: zero", callingUid); 1813 return -1; 1814 } 1815 1816 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR; 1817 } 1818 1819 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize, 1820 int32_t flags, Vector<sp<KeystoreArg> >* args) { 1821 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1822 pid_t spid = IPCThreadState::self()->getCallingPid(); 1823 if (!has_permission(callingUid, P_INSERT, spid)) { 1824 ALOGW("permission denied for %d: generate", callingUid); 1825 return ::PERMISSION_DENIED; 1826 } 1827 1828 if (targetUid == -1) { 1829 targetUid = callingUid; 1830 } else if (!is_granted_to(callingUid, targetUid)) { 1831 return ::PERMISSION_DENIED; 1832 } 1833 1834 State state = mKeyStore->getState(callingUid); 1835 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) { 1836 ALOGW("calling generate in state: %d", state); 1837 return state; 1838 } 1839 1840 uint8_t* data; 1841 size_t dataLength; 1842 int rc; 1843 bool isFallback = false; 1844 1845 const keymaster_device_t* device = mKeyStore->getDevice(); 1846 if (device == NULL) { 1847 return ::SYSTEM_ERROR; 1848 } 1849 1850 if (device->generate_keypair == NULL) { 1851 return ::SYSTEM_ERROR; 1852 } 1853 1854 if (keyType == EVP_PKEY_DSA) { 1855 keymaster_dsa_keygen_params_t dsa_params; 1856 memset(&dsa_params, '\0', sizeof(dsa_params)); 1857 1858 if (keySize == -1) { 1859 keySize = DSA_DEFAULT_KEY_SIZE; 1860 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE 1861 || keySize > DSA_MAX_KEY_SIZE) { 1862 ALOGI("invalid key size %d", keySize); 1863 return ::SYSTEM_ERROR; 1864 } 1865 dsa_params.key_size = keySize; 1866 1867 if (args->size() == 3) { 1868 sp<KeystoreArg> gArg = args->itemAt(0); 1869 sp<KeystoreArg> pArg = args->itemAt(1); 1870 sp<KeystoreArg> qArg = args->itemAt(2); 1871 1872 if (gArg != NULL && pArg != NULL && qArg != NULL) { 1873 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data()); 1874 dsa_params.generator_len = gArg->size(); 1875 1876 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data()); 1877 dsa_params.prime_p_len = pArg->size(); 1878 1879 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data()); 1880 dsa_params.prime_q_len = qArg->size(); 1881 } else { 1882 ALOGI("not all DSA parameters were read"); 1883 return ::SYSTEM_ERROR; 1884 } 1885 } else if (args->size() != 0) { 1886 ALOGI("DSA args must be 3"); 1887 return ::SYSTEM_ERROR; 1888 } 1889 1890 if (isKeyTypeSupported(device, TYPE_DSA)) { 1891 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength); 1892 } else { 1893 isFallback = true; 1894 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength); 1895 } 1896 } else if (keyType == EVP_PKEY_EC) { 1897 keymaster_ec_keygen_params_t ec_params; 1898 memset(&ec_params, '\0', sizeof(ec_params)); 1899 1900 if (keySize == -1) { 1901 keySize = EC_DEFAULT_KEY_SIZE; 1902 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) { 1903 ALOGI("invalid key size %d", keySize); 1904 return ::SYSTEM_ERROR; 1905 } 1906 ec_params.field_size = keySize; 1907 1908 if (isKeyTypeSupported(device, TYPE_EC)) { 1909 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength); 1910 } else { 1911 isFallback = true; 1912 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength); 1913 } 1914 } else if (keyType == EVP_PKEY_RSA) { 1915 keymaster_rsa_keygen_params_t rsa_params; 1916 memset(&rsa_params, '\0', sizeof(rsa_params)); 1917 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT; 1918 1919 if (keySize == -1) { 1920 keySize = RSA_DEFAULT_KEY_SIZE; 1921 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) { 1922 ALOGI("invalid key size %d", keySize); 1923 return ::SYSTEM_ERROR; 1924 } 1925 rsa_params.modulus_size = keySize; 1926 1927 if (args->size() > 1) { 1928 ALOGI("invalid number of arguments: %zu", args->size()); 1929 return ::SYSTEM_ERROR; 1930 } else if (args->size() == 1) { 1931 sp<KeystoreArg> pubExpBlob = args->itemAt(0); 1932 if (pubExpBlob != NULL) { 1933 Unique_BIGNUM pubExpBn( 1934 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()), 1935 pubExpBlob->size(), NULL)); 1936 if (pubExpBn.get() == NULL) { 1937 ALOGI("Could not convert public exponent to BN"); 1938 return ::SYSTEM_ERROR; 1939 } 1940 unsigned long pubExp = BN_get_word(pubExpBn.get()); 1941 if (pubExp == 0xFFFFFFFFL) { 1942 ALOGI("cannot represent public exponent as a long value"); 1943 return ::SYSTEM_ERROR; 1944 } 1945 rsa_params.public_exponent = pubExp; 1946 } 1947 } 1948 1949 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength); 1950 } else { 1951 ALOGW("Unsupported key type %d", keyType); 1952 rc = -1; 1953 } 1954 1955 if (rc) { 1956 return ::SYSTEM_ERROR; 1957 } 1958 1959 String8 name8(name); 1960 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid)); 1961 1962 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR); 1963 free(data); 1964 1965 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 1966 keyBlob.setFallback(isFallback); 1967 1968 return mKeyStore->put(filename.string(), &keyBlob, callingUid); 1969 } 1970 1971 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid, 1972 int32_t flags) { 1973 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1974 pid_t spid = IPCThreadState::self()->getCallingPid(); 1975 if (!has_permission(callingUid, P_INSERT, spid)) { 1976 ALOGW("permission denied for %d: import", callingUid); 1977 return ::PERMISSION_DENIED; 1978 } 1979 1980 if (targetUid == -1) { 1981 targetUid = callingUid; 1982 } else if (!is_granted_to(callingUid, targetUid)) { 1983 return ::PERMISSION_DENIED; 1984 } 1985 1986 State state = mKeyStore->getState(targetUid); 1987 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) { 1988 ALOGD("calling import in state: %d", state); 1989 return state; 1990 } 1991 1992 String8 name8(name); 1993 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1994 1995 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags); 1996 } 1997 1998 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out, 1999 size_t* outLength) { 2000 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2001 pid_t spid = IPCThreadState::self()->getCallingPid(); 2002 if (!has_permission(callingUid, P_SIGN, spid)) { 2003 ALOGW("permission denied for %d: saw", callingUid); 2004 return ::PERMISSION_DENIED; 2005 } 2006 2007 Blob keyBlob; 2008 String8 name8(name); 2009 2010 ALOGV("sign %s from uid %d", name8.string(), callingUid); 2011 int rc; 2012 2013 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2014 ::TYPE_KEY_PAIR); 2015 if (responseCode != ::NO_ERROR) { 2016 return responseCode; 2017 } 2018 2019 const keymaster_device_t* device = mKeyStore->getDevice(); 2020 if (device == NULL) { 2021 ALOGE("no keymaster device; cannot sign"); 2022 return ::SYSTEM_ERROR; 2023 } 2024 2025 if (device->sign_data == NULL) { 2026 ALOGE("device doesn't implement signing"); 2027 return ::SYSTEM_ERROR; 2028 } 2029 2030 keymaster_rsa_sign_params_t params; 2031 params.digest_type = DIGEST_NONE; 2032 params.padding_type = PADDING_NONE; 2033 2034 if (keyBlob.isFallback()) { 2035 rc = openssl_sign_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, 2036 length, out, outLength); 2037 } else { 2038 rc = device->sign_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, 2039 length, out, outLength); 2040 } 2041 if (rc) { 2042 ALOGW("device couldn't sign data"); 2043 return ::SYSTEM_ERROR; 2044 } 2045 2046 return ::NO_ERROR; 2047 } 2048 2049 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength, 2050 const uint8_t* signature, size_t signatureLength) { 2051 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2052 pid_t spid = IPCThreadState::self()->getCallingPid(); 2053 if (!has_permission(callingUid, P_VERIFY, spid)) { 2054 ALOGW("permission denied for %d: verify", callingUid); 2055 return ::PERMISSION_DENIED; 2056 } 2057 2058 State state = mKeyStore->getState(callingUid); 2059 if (!isKeystoreUnlocked(state)) { 2060 ALOGD("calling verify in state: %d", state); 2061 return state; 2062 } 2063 2064 Blob keyBlob; 2065 String8 name8(name); 2066 int rc; 2067 2068 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2069 TYPE_KEY_PAIR); 2070 if (responseCode != ::NO_ERROR) { 2071 return responseCode; 2072 } 2073 2074 const keymaster_device_t* device = mKeyStore->getDevice(); 2075 if (device == NULL) { 2076 return ::SYSTEM_ERROR; 2077 } 2078 2079 if (device->verify_data == NULL) { 2080 return ::SYSTEM_ERROR; 2081 } 2082 2083 keymaster_rsa_sign_params_t params; 2084 params.digest_type = DIGEST_NONE; 2085 params.padding_type = PADDING_NONE; 2086 2087 if (keyBlob.isFallback()) { 2088 rc = openssl_verify_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, 2089 dataLength, signature, signatureLength); 2090 } else { 2091 rc = device->verify_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, 2092 dataLength, signature, signatureLength); 2093 } 2094 if (rc) { 2095 return ::SYSTEM_ERROR; 2096 } else { 2097 return ::NO_ERROR; 2098 } 2099 } 2100 2101 /* 2102 * TODO: The abstraction between things stored in hardware and regular blobs 2103 * of data stored on the filesystem should be moved down to keystore itself. 2104 * Unfortunately the Java code that calls this has naming conventions that it 2105 * knows about. Ideally keystore shouldn't be used to store random blobs of 2106 * data. 2107 * 2108 * Until that happens, it's necessary to have a separate "get_pubkey" and 2109 * "del_key" since the Java code doesn't really communicate what it's 2110 * intentions are. 2111 */ 2112 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) { 2113 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2114 pid_t spid = IPCThreadState::self()->getCallingPid(); 2115 if (!has_permission(callingUid, P_GET, spid)) { 2116 ALOGW("permission denied for %d: get_pubkey", callingUid); 2117 return ::PERMISSION_DENIED; 2118 } 2119 2120 Blob keyBlob; 2121 String8 name8(name); 2122 2123 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid); 2124 2125 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2126 TYPE_KEY_PAIR); 2127 if (responseCode != ::NO_ERROR) { 2128 return responseCode; 2129 } 2130 2131 const keymaster_device_t* device = mKeyStore->getDevice(); 2132 if (device == NULL) { 2133 return ::SYSTEM_ERROR; 2134 } 2135 2136 if (device->get_keypair_public == NULL) { 2137 ALOGE("device has no get_keypair_public implementation!"); 2138 return ::SYSTEM_ERROR; 2139 } 2140 2141 int rc; 2142 if (keyBlob.isFallback()) { 2143 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey, 2144 pubkeyLength); 2145 } else { 2146 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey, 2147 pubkeyLength); 2148 } 2149 if (rc) { 2150 return ::SYSTEM_ERROR; 2151 } 2152 2153 return ::NO_ERROR; 2154 } 2155 2156 int32_t del_key(const String16& name, int targetUid) { 2157 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2158 pid_t spid = IPCThreadState::self()->getCallingPid(); 2159 if (!has_permission(callingUid, P_DELETE, spid)) { 2160 ALOGW("permission denied for %d: del_key", callingUid); 2161 return ::PERMISSION_DENIED; 2162 } 2163 2164 if (targetUid == -1) { 2165 targetUid = callingUid; 2166 } else if (!is_granted_to(callingUid, targetUid)) { 2167 return ::PERMISSION_DENIED; 2168 } 2169 2170 String8 name8(name); 2171 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 2172 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid); 2173 } 2174 2175 int32_t grant(const String16& name, int32_t granteeUid) { 2176 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2177 pid_t spid = IPCThreadState::self()->getCallingPid(); 2178 if (!has_permission(callingUid, P_GRANT, spid)) { 2179 ALOGW("permission denied for %d: grant", callingUid); 2180 return ::PERMISSION_DENIED; 2181 } 2182 2183 State state = mKeyStore->getState(callingUid); 2184 if (!isKeystoreUnlocked(state)) { 2185 ALOGD("calling grant in state: %d", state); 2186 return state; 2187 } 2188 2189 String8 name8(name); 2190 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid)); 2191 2192 if (access(filename.string(), R_OK) == -1) { 2193 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND; 2194 } 2195 2196 mKeyStore->addGrant(filename.string(), granteeUid); 2197 return ::NO_ERROR; 2198 } 2199 2200 int32_t ungrant(const String16& name, int32_t granteeUid) { 2201 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2202 pid_t spid = IPCThreadState::self()->getCallingPid(); 2203 if (!has_permission(callingUid, P_GRANT, spid)) { 2204 ALOGW("permission denied for %d: ungrant", callingUid); 2205 return ::PERMISSION_DENIED; 2206 } 2207 2208 State state = mKeyStore->getState(callingUid); 2209 if (!isKeystoreUnlocked(state)) { 2210 ALOGD("calling ungrant in state: %d", state); 2211 return state; 2212 } 2213 2214 String8 name8(name); 2215 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid)); 2216 2217 if (access(filename.string(), R_OK) == -1) { 2218 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND; 2219 } 2220 2221 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND; 2222 } 2223 2224 int64_t getmtime(const String16& name) { 2225 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2226 pid_t spid = IPCThreadState::self()->getCallingPid(); 2227 if (!has_permission(callingUid, P_GET, spid)) { 2228 ALOGW("permission denied for %d: getmtime", callingUid); 2229 return -1L; 2230 } 2231 2232 String8 name8(name); 2233 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid)); 2234 2235 if (access(filename.string(), R_OK) == -1) { 2236 ALOGW("could not access %s for getmtime", filename.string()); 2237 return -1L; 2238 } 2239 2240 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY)); 2241 if (fd < 0) { 2242 ALOGW("could not open %s for getmtime", filename.string()); 2243 return -1L; 2244 } 2245 2246 struct stat s; 2247 int ret = fstat(fd, &s); 2248 close(fd); 2249 if (ret == -1) { 2250 ALOGW("could not stat %s for getmtime", filename.string()); 2251 return -1L; 2252 } 2253 2254 return static_cast<int64_t>(s.st_mtime); 2255 } 2256 2257 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey, 2258 int32_t destUid) { 2259 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2260 pid_t spid = IPCThreadState::self()->getCallingPid(); 2261 if (!has_permission(callingUid, P_DUPLICATE, spid)) { 2262 ALOGW("permission denied for %d: duplicate", callingUid); 2263 return -1L; 2264 } 2265 2266 State state = mKeyStore->getState(callingUid); 2267 if (!isKeystoreUnlocked(state)) { 2268 ALOGD("calling duplicate in state: %d", state); 2269 return state; 2270 } 2271 2272 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) { 2273 srcUid = callingUid; 2274 } else if (!is_granted_to(callingUid, srcUid)) { 2275 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid); 2276 return ::PERMISSION_DENIED; 2277 } 2278 2279 if (destUid == -1) { 2280 destUid = callingUid; 2281 } 2282 2283 if (srcUid != destUid) { 2284 if (static_cast<uid_t>(srcUid) != callingUid) { 2285 ALOGD("can only duplicate from caller to other or to same uid: " 2286 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid); 2287 return ::PERMISSION_DENIED; 2288 } 2289 2290 if (!is_granted_to(callingUid, destUid)) { 2291 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid); 2292 return ::PERMISSION_DENIED; 2293 } 2294 } 2295 2296 String8 source8(srcKey); 2297 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid)); 2298 2299 String8 target8(destKey); 2300 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid)); 2301 2302 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) { 2303 ALOGD("destination already exists: %s", targetFile.string()); 2304 return ::SYSTEM_ERROR; 2305 } 2306 2307 Blob keyBlob; 2308 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, 2309 srcUid); 2310 if (responseCode != ::NO_ERROR) { 2311 return responseCode; 2312 } 2313 2314 return mKeyStore->put(targetFile.string(), &keyBlob, destUid); 2315 } 2316 2317 int32_t is_hardware_backed(const String16& keyType) { 2318 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0; 2319 } 2320 2321 int32_t clear_uid(int64_t targetUid64) { 2322 uid_t targetUid = static_cast<uid_t>(targetUid64); 2323 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2324 pid_t spid = IPCThreadState::self()->getCallingPid(); 2325 if (!has_permission(callingUid, P_CLEAR_UID, spid)) { 2326 ALOGW("permission denied for %d: clear_uid", callingUid); 2327 return ::PERMISSION_DENIED; 2328 } 2329 2330 if (targetUid64 == -1) { 2331 targetUid = callingUid; 2332 } else if (!is_self_or_system(callingUid, targetUid)) { 2333 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid); 2334 return ::PERMISSION_DENIED; 2335 } 2336 2337 const keymaster_device_t* device = mKeyStore->getDevice(); 2338 if (device == NULL) { 2339 ALOGW("can't get keymaster device"); 2340 return ::SYSTEM_ERROR; 2341 } 2342 2343 String8 prefix = String8::format("%u_", targetUid); 2344 Vector<String16> aliases; 2345 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) { 2346 return ::SYSTEM_ERROR; 2347 } 2348 2349 for (uint32_t i = 0; i < aliases.size(); i++) { 2350 String8 name8(aliases[i]); 2351 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 2352 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid); 2353 } 2354 return ::NO_ERROR; 2355 } 2356 2357 int32_t reset_uid(int32_t targetUid) { 2358 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2359 pid_t spid = IPCThreadState::self()->getCallingPid(); 2360 2361 if (!has_permission(callingUid, P_RESET_UID, spid)) { 2362 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid); 2363 return ::PERMISSION_DENIED; 2364 } 2365 if (!is_self_or_system(callingUid, targetUid)) { 2366 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid); 2367 return ::PERMISSION_DENIED; 2368 } 2369 2370 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR; 2371 } 2372 2373 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) { 2374 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2375 pid_t spid = IPCThreadState::self()->getCallingPid(); 2376 if (!has_permission(callingUid, P_SYNC_UID, spid)) { 2377 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid); 2378 return ::PERMISSION_DENIED; 2379 } 2380 if (callingUid != AID_SYSTEM) { 2381 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid); 2382 return ::PERMISSION_DENIED; 2383 } 2384 if (sourceUid == targetUid) { 2385 return ::SYSTEM_ERROR; 2386 } 2387 2388 // Initialise user keystore with existing master key held in-memory 2389 return mKeyStore->copyMasterKey(sourceUid, targetUid); 2390 } 2391 2392 int32_t password_uid(const String16& pw, int32_t targetUid) { 2393 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2394 pid_t spid = IPCThreadState::self()->getCallingPid(); 2395 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) { 2396 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid); 2397 return ::PERMISSION_DENIED; 2398 } 2399 if (callingUid != AID_SYSTEM) { 2400 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid); 2401 return ::PERMISSION_DENIED; 2402 } 2403 2404 const String8 password8(pw); 2405 2406 switch (mKeyStore->getState(targetUid)) { 2407 case ::STATE_UNINITIALIZED: { 2408 // generate master key, encrypt with password, write to file, initialize mMasterKey*. 2409 return mKeyStore->initializeUser(password8, targetUid); 2410 } 2411 case ::STATE_NO_ERROR: { 2412 // rewrite master key with new password. 2413 return mKeyStore->writeMasterKey(password8, targetUid); 2414 } 2415 case ::STATE_LOCKED: { 2416 // read master key, decrypt with password, initialize mMasterKey*. 2417 return mKeyStore->readMasterKey(password8, targetUid); 2418 } 2419 } 2420 return ::SYSTEM_ERROR; 2421 } 2422 2423 private: 2424 inline bool isKeystoreUnlocked(State state) { 2425 switch (state) { 2426 case ::STATE_NO_ERROR: 2427 return true; 2428 case ::STATE_UNINITIALIZED: 2429 case ::STATE_LOCKED: 2430 return false; 2431 } 2432 return false; 2433 } 2434 2435 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) { 2436 const int32_t device_api = device->common.module->module_api_version; 2437 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) { 2438 switch (keyType) { 2439 case TYPE_RSA: 2440 case TYPE_DSA: 2441 case TYPE_EC: 2442 return true; 2443 default: 2444 return false; 2445 } 2446 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) { 2447 switch (keyType) { 2448 case TYPE_RSA: 2449 return true; 2450 case TYPE_DSA: 2451 return device->flags & KEYMASTER_SUPPORTS_DSA; 2452 case TYPE_EC: 2453 return device->flags & KEYMASTER_SUPPORTS_EC; 2454 default: 2455 return false; 2456 } 2457 } else { 2458 return keyType == TYPE_RSA; 2459 } 2460 } 2461 2462 ::KeyStore* mKeyStore; 2463 }; 2464 2465 }; // namespace android 2466 2467 int main(int argc, char* argv[]) { 2468 if (argc < 2) { 2469 ALOGE("A directory must be specified!"); 2470 return 1; 2471 } 2472 if (chdir(argv[1]) == -1) { 2473 ALOGE("chdir: %s: %s", argv[1], strerror(errno)); 2474 return 1; 2475 } 2476 2477 Entropy entropy; 2478 if (!entropy.open()) { 2479 return 1; 2480 } 2481 2482 keymaster_device_t* dev; 2483 if (keymaster_device_initialize(&dev)) { 2484 ALOGE("keystore keymaster could not be initialized; exiting"); 2485 return 1; 2486 } 2487 2488 ks_is_selinux_enabled = is_selinux_enabled(); 2489 if (ks_is_selinux_enabled) { 2490 union selinux_callback cb; 2491 cb.func_log = selinux_log_callback; 2492 selinux_set_callback(SELINUX_CB_LOG, cb); 2493 if (getcon(&tctx) != 0) { 2494 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n"); 2495 return -1; 2496 } 2497 } else { 2498 ALOGI("SELinux: Keystore SELinux is disabled.\n"); 2499 } 2500 2501 KeyStore keyStore(&entropy, dev); 2502 keyStore.initialize(); 2503 android::sp<android::IServiceManager> sm = android::defaultServiceManager(); 2504 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore); 2505 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy); 2506 if (ret != android::OK) { 2507 ALOGE("Couldn't register binder service!"); 2508 return -1; 2509 } 2510 2511 /* 2512 * We're the only thread in existence, so we're just going to process 2513 * Binder transaction as a single-threaded program. 2514 */ 2515 android::IPCThreadState::self()->joinThreadPool(); 2516 2517 keymaster_device_release(dev); 2518 return 1; 2519 } 2520