keystore.cpp revision 8cfb8ac6e9bd291e9d861a32de2719e3bc797191
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 <strings.h> 24#include <unistd.h> 25#include <signal.h> 26#include <errno.h> 27#include <dirent.h> 28#include <errno.h> 29#include <fcntl.h> 30#include <limits.h> 31#include <assert.h> 32#include <sys/types.h> 33#include <sys/socket.h> 34#include <sys/stat.h> 35#include <sys/time.h> 36#include <arpa/inet.h> 37 38#include <openssl/aes.h> 39#include <openssl/bio.h> 40#include <openssl/evp.h> 41#include <openssl/md5.h> 42#include <openssl/pem.h> 43 44#include <hardware/keymaster0.h> 45 46#include <keymaster/soft_keymaster_device.h> 47#include <keymaster/soft_keymaster_logger.h> 48#include <keymaster/softkeymaster.h> 49 50#include <UniquePtr.h> 51#include <utils/String8.h> 52#include <utils/Vector.h> 53 54#include <keystore/IKeystoreService.h> 55#include <binder/IPCThreadState.h> 56#include <binder/IServiceManager.h> 57 58#include <cutils/log.h> 59#include <cutils/sockets.h> 60#include <private/android_filesystem_config.h> 61 62#include <keystore/keystore.h> 63 64#include <selinux/android.h> 65 66#include "auth_token_table.h" 67#include "defaults.h" 68#include "operation.h" 69 70/* KeyStore is a secured storage for key-value pairs. In this implementation, 71 * each file stores one key-value pair. Keys are encoded in file names, and 72 * values are encrypted with checksums. The encryption key is protected by a 73 * user-defined password. To keep things simple, buffers are always larger than 74 * the maximum space we needed, so boundary checks on buffers are omitted. */ 75 76#define KEY_SIZE ((NAME_MAX - 15) / 2) 77#define VALUE_SIZE 32768 78#define PASSWORD_SIZE VALUE_SIZE 79 80 81struct BIGNUM_Delete { 82 void operator()(BIGNUM* p) const { 83 BN_free(p); 84 } 85}; 86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM; 87 88struct BIO_Delete { 89 void operator()(BIO* p) const { 90 BIO_free(p); 91 } 92}; 93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO; 94 95struct EVP_PKEY_Delete { 96 void operator()(EVP_PKEY* p) const { 97 EVP_PKEY_free(p); 98 } 99}; 100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; 101 102struct PKCS8_PRIV_KEY_INFO_Delete { 103 void operator()(PKCS8_PRIV_KEY_INFO* p) const { 104 PKCS8_PRIV_KEY_INFO_free(p); 105 } 106}; 107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO; 108 109static int keymaster_device_initialize(keymaster0_device_t** dev) { 110 int rc; 111 112 const hw_module_t* mod; 113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod); 114 if (rc) { 115 ALOGE("could not find any keystore module"); 116 goto out; 117 } 118 119 rc = keymaster0_open(mod, dev); 120 if (rc) { 121 ALOGE("could not open keymaster device in %s (%s)", 122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc)); 123 goto out; 124 } 125 126 return 0; 127 128out: 129 *dev = NULL; 130 return rc; 131} 132 133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the 134// logger used by SoftKeymasterDevice. 135static keymaster::SoftKeymasterLogger softkeymaster_logger; 136 137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) { 138 keymaster::SoftKeymasterDevice* softkeymaster = 139 new keymaster::SoftKeymasterDevice(); 140 *dev = softkeymaster->keymaster_device(); 141 // softkeymaster will be freed by *dev->close_device; don't delete here. 142 return 0; 143} 144 145static void keymaster_device_release(keymaster0_device_t* dev) { 146 keymaster0_close(dev); 147} 148 149/*************** 150 * PERMISSIONS * 151 ***************/ 152 153/* Here are the permissions, actions, users, and the main function. */ 154typedef enum { 155 P_GET_STATE = 1 << 0, 156 P_GET = 1 << 1, 157 P_INSERT = 1 << 2, 158 P_DELETE = 1 << 3, 159 P_EXIST = 1 << 4, 160 P_LIST = 1 << 5, 161 P_RESET = 1 << 6, 162 P_PASSWORD = 1 << 7, 163 P_LOCK = 1 << 8, 164 P_UNLOCK = 1 << 9, 165 P_IS_EMPTY = 1 << 10, 166 P_SIGN = 1 << 11, 167 P_VERIFY = 1 << 12, 168 P_GRANT = 1 << 13, 169 P_DUPLICATE = 1 << 14, 170 P_CLEAR_UID = 1 << 15, 171 P_ADD_AUTH = 1 << 16, 172 P_USER_CHANGED = 1 << 17, 173} perm_t; 174 175static struct user_euid { 176 uid_t uid; 177 uid_t euid; 178} user_euids[] = { 179 {AID_VPN, AID_SYSTEM}, 180 {AID_WIFI, AID_SYSTEM}, 181 {AID_ROOT, AID_SYSTEM}, 182}; 183 184/* perm_labels associcated with keystore_key SELinux class verbs. */ 185const char *perm_labels[] = { 186 "get_state", 187 "get", 188 "insert", 189 "delete", 190 "exist", 191 "list", 192 "reset", 193 "password", 194 "lock", 195 "unlock", 196 "is_empty", 197 "sign", 198 "verify", 199 "grant", 200 "duplicate", 201 "clear_uid", 202 "add_auth", 203 "user_changed", 204}; 205 206static struct user_perm { 207 uid_t uid; 208 perm_t perms; 209} user_perms[] = { 210 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) }, 211 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) }, 212 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) }, 213 {AID_ROOT, static_cast<perm_t>(P_GET) }, 214}; 215 216static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE 217 | P_EXIST | P_LIST | P_SIGN | P_VERIFY); 218 219static char *tctx; 220static int ks_is_selinux_enabled; 221 222static const char *get_perm_label(perm_t perm) { 223 unsigned int index = ffs(perm); 224 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) { 225 return perm_labels[index - 1]; 226 } else { 227 ALOGE("Keystore: Failed to retrieve permission label.\n"); 228 abort(); 229 } 230} 231 232/** 233 * Returns the app ID (in the Android multi-user sense) for the current 234 * UNIX UID. 235 */ 236static uid_t get_app_id(uid_t uid) { 237 return uid % AID_USER; 238} 239 240/** 241 * Returns the user ID (in the Android multi-user sense) for the current 242 * UNIX UID. 243 */ 244static uid_t get_user_id(uid_t uid) { 245 return uid / AID_USER; 246} 247 248static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) { 249 if (!ks_is_selinux_enabled) { 250 return true; 251 } 252 253 char *sctx = NULL; 254 const char *selinux_class = "keystore_key"; 255 const char *str_perm = get_perm_label(perm); 256 257 if (!str_perm) { 258 return false; 259 } 260 261 if (getpidcon(spid, &sctx) != 0) { 262 ALOGE("SELinux: Failed to get source pid context.\n"); 263 return false; 264 } 265 266 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm, 267 NULL) == 0; 268 freecon(sctx); 269 return allowed; 270} 271 272static bool has_permission(uid_t uid, perm_t perm, pid_t spid) { 273 // All system users are equivalent for multi-user support. 274 if (get_app_id(uid) == AID_SYSTEM) { 275 uid = AID_SYSTEM; 276 } 277 278 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) { 279 struct user_perm user = user_perms[i]; 280 if (user.uid == uid) { 281 return (user.perms & perm) && 282 keystore_selinux_check_access(uid, perm, spid); 283 } 284 } 285 286 return (DEFAULT_PERMS & perm) && 287 keystore_selinux_check_access(uid, perm, spid); 288} 289 290/** 291 * Returns the UID that the callingUid should act as. This is here for 292 * legacy support of the WiFi and VPN systems and should be removed 293 * when WiFi can operate in its own namespace. 294 */ 295static uid_t get_keystore_euid(uid_t uid) { 296 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) { 297 struct user_euid user = user_euids[i]; 298 if (user.uid == uid) { 299 return user.euid; 300 } 301 } 302 303 return uid; 304} 305 306/** 307 * Returns true if the callingUid is allowed to interact in the targetUid's 308 * namespace. 309 */ 310static bool is_granted_to(uid_t callingUid, uid_t targetUid) { 311 if (callingUid == targetUid) { 312 return true; 313 } 314 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) { 315 struct user_euid user = user_euids[i]; 316 if (user.euid == callingUid && user.uid == targetUid) { 317 return true; 318 } 319 } 320 321 return false; 322} 323 324/* Here is the encoding of keys. This is necessary in order to allow arbitrary 325 * characters in keys. Characters in [0-~] are not encoded. Others are encoded 326 * into two bytes. The first byte is one of [+-.] which represents the first 327 * two bits of the character. The second byte encodes the rest of the bits into 328 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note 329 * that Base64 cannot be used here due to the need of prefix match on keys. */ 330 331static size_t encode_key_length(const android::String8& keyName) { 332 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string()); 333 size_t length = keyName.length(); 334 for (int i = length; i > 0; --i, ++in) { 335 if (*in < '0' || *in > '~') { 336 ++length; 337 } 338 } 339 return length; 340} 341 342static int encode_key(char* out, const android::String8& keyName) { 343 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string()); 344 size_t length = keyName.length(); 345 for (int i = length; i > 0; --i, ++in, ++out) { 346 if (*in < '0' || *in > '~') { 347 *out = '+' + (*in >> 6); 348 *++out = '0' + (*in & 0x3F); 349 ++length; 350 } else { 351 *out = *in; 352 } 353 } 354 *out = '\0'; 355 return length; 356} 357 358/* 359 * Converts from the "escaped" format on disk to actual name. 360 * This will be smaller than the input string. 361 * 362 * Characters that should combine with the next at the end will be truncated. 363 */ 364static size_t decode_key_length(const char* in, size_t length) { 365 size_t outLength = 0; 366 367 for (const char* end = in + length; in < end; in++) { 368 /* This combines with the next character. */ 369 if (*in < '0' || *in > '~') { 370 continue; 371 } 372 373 outLength++; 374 } 375 return outLength; 376} 377 378static void decode_key(char* out, const char* in, size_t length) { 379 for (const char* end = in + length; in < end; in++) { 380 if (*in < '0' || *in > '~') { 381 /* Truncate combining characters at the end. */ 382 if (in + 1 >= end) { 383 break; 384 } 385 386 *out = (*in++ - '+') << 6; 387 *out++ |= (*in - '0') & 0x3F; 388 } else { 389 *out++ = *in; 390 } 391 } 392 *out = '\0'; 393} 394 395static size_t readFully(int fd, uint8_t* data, size_t size) { 396 size_t remaining = size; 397 while (remaining > 0) { 398 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining)); 399 if (n <= 0) { 400 return size - remaining; 401 } 402 data += n; 403 remaining -= n; 404 } 405 return size; 406} 407 408static size_t writeFully(int fd, uint8_t* data, size_t size) { 409 size_t remaining = size; 410 while (remaining > 0) { 411 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining)); 412 if (n < 0) { 413 ALOGW("write failed: %s", strerror(errno)); 414 return size - remaining; 415 } 416 data += n; 417 remaining -= n; 418 } 419 return size; 420} 421 422class Entropy { 423public: 424 Entropy() : mRandom(-1) {} 425 ~Entropy() { 426 if (mRandom >= 0) { 427 close(mRandom); 428 } 429 } 430 431 bool open() { 432 const char* randomDevice = "/dev/urandom"; 433 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY)); 434 if (mRandom < 0) { 435 ALOGE("open: %s: %s", randomDevice, strerror(errno)); 436 return false; 437 } 438 return true; 439 } 440 441 bool generate_random_data(uint8_t* data, size_t size) const { 442 return (readFully(mRandom, data, size) == size); 443 } 444 445private: 446 int mRandom; 447}; 448 449/* Here is the file format. There are two parts in blob.value, the secret and 450 * the description. The secret is stored in ciphertext, and its original size 451 * can be found in blob.length. The description is stored after the secret in 452 * plaintext, and its size is specified in blob.info. The total size of the two 453 * parts must be no more than VALUE_SIZE bytes. The first field is the version, 454 * the second is the blob's type, and the third byte is flags. Fields other 455 * than blob.info, blob.length, and blob.value are modified by encryptBlob() 456 * and decryptBlob(). Thus they should not be accessed from outside. */ 457 458/* ** Note to future implementors of encryption: ** 459 * Currently this is the construction: 460 * metadata || Enc(MD5(data) || data) 461 * 462 * This should be the construction used for encrypting if re-implementing: 463 * 464 * Derive independent keys for encryption and MAC: 465 * Kenc = AES_encrypt(masterKey, "Encrypt") 466 * Kmac = AES_encrypt(masterKey, "MAC") 467 * 468 * Store this: 469 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) || 470 * HMAC(Kmac, metadata || Enc(data)) 471 */ 472struct __attribute__((packed)) blob { 473 uint8_t version; 474 uint8_t type; 475 uint8_t flags; 476 uint8_t info; 477 uint8_t vector[AES_BLOCK_SIZE]; 478 uint8_t encrypted[0]; // Marks offset to encrypted data. 479 uint8_t digest[MD5_DIGEST_LENGTH]; 480 uint8_t digested[0]; // Marks offset to digested data. 481 int32_t length; // in network byte order when encrypted 482 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE]; 483}; 484 485typedef enum { 486 TYPE_ANY = 0, // meta type that matches anything 487 TYPE_GENERIC = 1, 488 TYPE_MASTER_KEY = 2, 489 TYPE_KEY_PAIR = 3, 490 TYPE_KEYMASTER_10 = 4, 491} BlobType; 492 493static const uint8_t CURRENT_BLOB_VERSION = 2; 494 495class Blob { 496public: 497 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength, 498 BlobType type) { 499 mBlob.length = valueLength; 500 memcpy(mBlob.value, value, valueLength); 501 502 mBlob.info = infoLength; 503 memcpy(mBlob.value + valueLength, info, infoLength); 504 505 mBlob.version = CURRENT_BLOB_VERSION; 506 mBlob.type = uint8_t(type); 507 508 if (type == TYPE_MASTER_KEY) { 509 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED; 510 } else { 511 mBlob.flags = KEYSTORE_FLAG_NONE; 512 } 513 } 514 515 Blob(blob b) { 516 mBlob = b; 517 } 518 519 Blob() {} 520 521 const uint8_t* getValue() const { 522 return mBlob.value; 523 } 524 525 int32_t getLength() const { 526 return mBlob.length; 527 } 528 529 const uint8_t* getInfo() const { 530 return mBlob.value + mBlob.length; 531 } 532 533 uint8_t getInfoLength() const { 534 return mBlob.info; 535 } 536 537 uint8_t getVersion() const { 538 return mBlob.version; 539 } 540 541 bool isEncrypted() const { 542 if (mBlob.version < 2) { 543 return true; 544 } 545 546 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED; 547 } 548 549 void setEncrypted(bool encrypted) { 550 if (encrypted) { 551 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED; 552 } else { 553 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED; 554 } 555 } 556 557 bool isFallback() const { 558 return mBlob.flags & KEYSTORE_FLAG_FALLBACK; 559 } 560 561 void setFallback(bool fallback) { 562 if (fallback) { 563 mBlob.flags |= KEYSTORE_FLAG_FALLBACK; 564 } else { 565 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK; 566 } 567 } 568 569 void setVersion(uint8_t version) { 570 mBlob.version = version; 571 } 572 573 BlobType getType() const { 574 return BlobType(mBlob.type); 575 } 576 577 void setType(BlobType type) { 578 mBlob.type = uint8_t(type); 579 } 580 581 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) { 582 ALOGV("writing blob %s", filename); 583 if (isEncrypted()) { 584 if (state != STATE_NO_ERROR) { 585 ALOGD("couldn't insert encrypted blob while not unlocked"); 586 return LOCKED; 587 } 588 589 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) { 590 ALOGW("Could not read random data for: %s", filename); 591 return SYSTEM_ERROR; 592 } 593 } 594 595 // data includes the value and the value's length 596 size_t dataLength = mBlob.length + sizeof(mBlob.length); 597 // pad data to the AES_BLOCK_SIZE 598 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1) 599 / AES_BLOCK_SIZE * AES_BLOCK_SIZE); 600 // encrypted data includes the digest value 601 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH; 602 // move info after space for padding 603 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info); 604 // zero padding area 605 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength); 606 607 mBlob.length = htonl(mBlob.length); 608 609 if (isEncrypted()) { 610 MD5(mBlob.digested, digestedLength, mBlob.digest); 611 612 uint8_t vector[AES_BLOCK_SIZE]; 613 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE); 614 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, 615 aes_key, vector, AES_ENCRYPT); 616 } 617 618 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob); 619 size_t fileLength = encryptedLength + headerLength + mBlob.info; 620 621 const char* tmpFileName = ".tmp"; 622 int out = TEMP_FAILURE_RETRY(open(tmpFileName, 623 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)); 624 if (out < 0) { 625 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno)); 626 return SYSTEM_ERROR; 627 } 628 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength); 629 if (close(out) != 0) { 630 return SYSTEM_ERROR; 631 } 632 if (writtenBytes != fileLength) { 633 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength); 634 unlink(tmpFileName); 635 return SYSTEM_ERROR; 636 } 637 if (rename(tmpFileName, filename) == -1) { 638 ALOGW("could not rename blob to %s: %s", filename, strerror(errno)); 639 return SYSTEM_ERROR; 640 } 641 return NO_ERROR; 642 } 643 644 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) { 645 ALOGV("reading blob %s", filename); 646 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY)); 647 if (in < 0) { 648 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR; 649 } 650 // fileLength may be less than sizeof(mBlob) since the in 651 // memory version has extra padding to tolerate rounding up to 652 // the AES_BLOCK_SIZE 653 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob)); 654 if (close(in) != 0) { 655 return SYSTEM_ERROR; 656 } 657 658 if (isEncrypted() && (state != STATE_NO_ERROR)) { 659 return LOCKED; 660 } 661 662 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob); 663 if (fileLength < headerLength) { 664 return VALUE_CORRUPTED; 665 } 666 667 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info); 668 if (encryptedLength < 0) { 669 return VALUE_CORRUPTED; 670 } 671 672 ssize_t digestedLength; 673 if (isEncrypted()) { 674 if (encryptedLength % AES_BLOCK_SIZE != 0) { 675 return VALUE_CORRUPTED; 676 } 677 678 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key, 679 mBlob.vector, AES_DECRYPT); 680 digestedLength = encryptedLength - MD5_DIGEST_LENGTH; 681 uint8_t computedDigest[MD5_DIGEST_LENGTH]; 682 MD5(mBlob.digested, digestedLength, computedDigest); 683 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) { 684 return VALUE_CORRUPTED; 685 } 686 } else { 687 digestedLength = encryptedLength; 688 } 689 690 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length); 691 mBlob.length = ntohl(mBlob.length); 692 if (mBlob.length < 0 || mBlob.length > maxValueLength) { 693 return VALUE_CORRUPTED; 694 } 695 if (mBlob.info != 0) { 696 // move info from after padding to after data 697 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info); 698 } 699 return ::NO_ERROR; 700 } 701 702private: 703 struct blob mBlob; 704}; 705 706class UserState { 707public: 708 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) { 709 asprintf(&mUserDir, "user_%u", mUserId); 710 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir); 711 } 712 713 ~UserState() { 714 free(mUserDir); 715 free(mMasterKeyFile); 716 } 717 718 bool initialize() { 719 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) { 720 ALOGE("Could not create directory '%s'", mUserDir); 721 return false; 722 } 723 724 if (access(mMasterKeyFile, R_OK) == 0) { 725 setState(STATE_LOCKED); 726 } else { 727 setState(STATE_UNINITIALIZED); 728 } 729 730 return true; 731 } 732 733 uid_t getUserId() const { 734 return mUserId; 735 } 736 737 const char* getUserDirName() const { 738 return mUserDir; 739 } 740 741 const char* getMasterKeyFileName() const { 742 return mMasterKeyFile; 743 } 744 745 void setState(State state) { 746 mState = state; 747 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) { 748 mRetry = MAX_RETRY; 749 } 750 } 751 752 State getState() const { 753 return mState; 754 } 755 756 int8_t getRetry() const { 757 return mRetry; 758 } 759 760 void zeroizeMasterKeysInMemory() { 761 memset(mMasterKey, 0, sizeof(mMasterKey)); 762 memset(mSalt, 0, sizeof(mSalt)); 763 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption)); 764 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption)); 765 } 766 767 bool deleteMasterKey() { 768 setState(STATE_UNINITIALIZED); 769 zeroizeMasterKeysInMemory(); 770 return unlink(mMasterKeyFile) == 0 || errno == ENOENT; 771 } 772 773 ResponseCode initialize(const android::String8& pw, Entropy* entropy) { 774 if (!generateMasterKey(entropy)) { 775 return SYSTEM_ERROR; 776 } 777 ResponseCode response = writeMasterKey(pw, entropy); 778 if (response != NO_ERROR) { 779 return response; 780 } 781 setupMasterKeys(); 782 return ::NO_ERROR; 783 } 784 785 ResponseCode copyMasterKey(UserState* src) { 786 if (mState != STATE_UNINITIALIZED) { 787 return ::SYSTEM_ERROR; 788 } 789 if (src->getState() != STATE_NO_ERROR) { 790 return ::SYSTEM_ERROR; 791 } 792 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES); 793 setupMasterKeys(); 794 return ::NO_ERROR; 795 } 796 797 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) { 798 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES]; 799 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt); 800 AES_KEY passwordAesKey; 801 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey); 802 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY); 803 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy); 804 } 805 806 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) { 807 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY)); 808 if (in < 0) { 809 return SYSTEM_ERROR; 810 } 811 812 // we read the raw blob to just to get the salt to generate 813 // the AES key, then we create the Blob to use with decryptBlob 814 blob rawBlob; 815 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob)); 816 if (close(in) != 0) { 817 return SYSTEM_ERROR; 818 } 819 // find salt at EOF if present, otherwise we have an old file 820 uint8_t* salt; 821 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) { 822 salt = (uint8_t*) &rawBlob + length - SALT_SIZE; 823 } else { 824 salt = NULL; 825 } 826 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES]; 827 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt); 828 AES_KEY passwordAesKey; 829 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey); 830 Blob masterKeyBlob(rawBlob); 831 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey, 832 STATE_NO_ERROR); 833 if (response == SYSTEM_ERROR) { 834 return response; 835 } 836 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) { 837 // if salt was missing, generate one and write a new master key file with the salt. 838 if (salt == NULL) { 839 if (!generateSalt(entropy)) { 840 return SYSTEM_ERROR; 841 } 842 response = writeMasterKey(pw, entropy); 843 } 844 if (response == NO_ERROR) { 845 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES); 846 setupMasterKeys(); 847 } 848 return response; 849 } 850 if (mRetry <= 0) { 851 reset(); 852 return UNINITIALIZED; 853 } 854 --mRetry; 855 switch (mRetry) { 856 case 0: return WRONG_PASSWORD_0; 857 case 1: return WRONG_PASSWORD_1; 858 case 2: return WRONG_PASSWORD_2; 859 case 3: return WRONG_PASSWORD_3; 860 default: return WRONG_PASSWORD_3; 861 } 862 } 863 864 AES_KEY* getEncryptionKey() { 865 return &mMasterKeyEncryption; 866 } 867 868 AES_KEY* getDecryptionKey() { 869 return &mMasterKeyDecryption; 870 } 871 872 bool reset() { 873 DIR* dir = opendir(getUserDirName()); 874 if (!dir) { 875 // If the directory doesn't exist then nothing to do. 876 if (errno == ENOENT) { 877 return true; 878 } 879 ALOGW("couldn't open user directory: %s", strerror(errno)); 880 return false; 881 } 882 883 struct dirent* file; 884 while ((file = readdir(dir)) != NULL) { 885 // skip . and .. 886 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) { 887 continue; 888 } 889 890 unlinkat(dirfd(dir), file->d_name, 0); 891 } 892 closedir(dir); 893 return true; 894 } 895 896private: 897 static const int MASTER_KEY_SIZE_BYTES = 16; 898 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8; 899 900 static const int MAX_RETRY = 4; 901 static const size_t SALT_SIZE = 16; 902 903 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw, 904 uint8_t* salt) { 905 size_t saltSize; 906 if (salt != NULL) { 907 saltSize = SALT_SIZE; 908 } else { 909 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found 910 salt = (uint8_t*) "keystore"; 911 // sizeof = 9, not strlen = 8 912 saltSize = sizeof("keystore"); 913 } 914 915 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt, 916 saltSize, 8192, keySize, key); 917 } 918 919 bool generateSalt(Entropy* entropy) { 920 return entropy->generate_random_data(mSalt, sizeof(mSalt)); 921 } 922 923 bool generateMasterKey(Entropy* entropy) { 924 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) { 925 return false; 926 } 927 if (!generateSalt(entropy)) { 928 return false; 929 } 930 return true; 931 } 932 933 void setupMasterKeys() { 934 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption); 935 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption); 936 setState(STATE_NO_ERROR); 937 } 938 939 uid_t mUserId; 940 941 char* mUserDir; 942 char* mMasterKeyFile; 943 944 State mState; 945 int8_t mRetry; 946 947 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES]; 948 uint8_t mSalt[SALT_SIZE]; 949 950 AES_KEY mMasterKeyEncryption; 951 AES_KEY mMasterKeyDecryption; 952}; 953 954typedef struct { 955 uint32_t uid; 956 const uint8_t* filename; 957} grant_t; 958 959class KeyStore { 960public: 961 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback) 962 : mEntropy(entropy) 963 , mDevice(device) 964 , mFallbackDevice(fallback) 965 { 966 memset(&mMetaData, '\0', sizeof(mMetaData)); 967 } 968 969 ~KeyStore() { 970 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); 971 it != mGrants.end(); it++) { 972 delete *it; 973 } 974 mGrants.clear(); 975 976 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); 977 it != mMasterKeys.end(); it++) { 978 delete *it; 979 } 980 mMasterKeys.clear(); 981 } 982 983 /** 984 * Depending on the hardware keymaster version is this may return a 985 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from 986 * keymaster0 are safe to call, calls to keymaster1_device_t methods should 987 * be guarded by a check on the device's version. 988 */ 989 keymaster1_device_t *getDevice() const { 990 return mDevice; 991 } 992 993 keymaster1_device_t *getFallbackDevice() const { 994 return mFallbackDevice; 995 } 996 997 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const { 998 return blob.isFallback() ? mFallbackDevice: mDevice; 999 } 1000 1001 ResponseCode initialize() { 1002 readMetaData(); 1003 if (upgradeKeystore()) { 1004 writeMetaData(); 1005 } 1006 1007 return ::NO_ERROR; 1008 } 1009 1010 State getState(uid_t userId) { 1011 return getUserState(userId)->getState(); 1012 } 1013 1014 ResponseCode initializeUser(const android::String8& pw, uid_t userId) { 1015 UserState* userState = getUserState(userId); 1016 return userState->initialize(pw, mEntropy); 1017 } 1018 1019 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) { 1020 UserState *userState = getUserState(dstUser); 1021 UserState *initState = getUserState(srcUser); 1022 return userState->copyMasterKey(initState); 1023 } 1024 1025 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) { 1026 UserState* userState = getUserState(userId); 1027 return userState->writeMasterKey(pw, mEntropy); 1028 } 1029 1030 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) { 1031 UserState* userState = getUserState(userId); 1032 return userState->readMasterKey(pw, mEntropy); 1033 } 1034 1035 android::String8 getKeyName(const android::String8& keyName) { 1036 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 1037 encode_key(encoded, keyName); 1038 return android::String8(encoded); 1039 } 1040 1041 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) { 1042 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 1043 encode_key(encoded, keyName); 1044 return android::String8::format("%u_%s", uid, encoded); 1045 } 1046 1047 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) { 1048 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 1049 encode_key(encoded, keyName); 1050 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid, 1051 encoded); 1052 } 1053 1054 /* 1055 * Delete entries owned by userId. If keepUnencryptedEntries is true 1056 * then only encrypted entries will be removed, otherwise all entries will 1057 * be removed. 1058 */ 1059 void resetUser(uid_t userId, bool keepUnenryptedEntries) { 1060 android::String8 prefix(""); 1061 android::Vector<android::String16> aliases; 1062 UserState* userState = getUserState(userId); 1063 if (list(prefix, &aliases, userId) != ::NO_ERROR) { 1064 return; 1065 } 1066 for (uint32_t i = 0; i < aliases.size(); i++) { 1067 android::String8 filename(aliases[i]); 1068 filename = android::String8::format("%s/%s", userState->getUserDirName(), 1069 getKeyName(filename).string()); 1070 bool shouldDelete = true; 1071 if (keepUnenryptedEntries) { 1072 Blob blob; 1073 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId); 1074 1075 /* get can fail if the blob is encrypted and the state is 1076 * not unlocked, only skip deleting blobs that were loaded and 1077 * who are not encrypted. If there are blobs we fail to read for 1078 * other reasons err on the safe side and delete them since we 1079 * can't tell if they're encrypted. 1080 */ 1081 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted()); 1082 } 1083 if (shouldDelete) { 1084 del(filename, ::TYPE_ANY, userId); 1085 } 1086 } 1087 if (!userState->deleteMasterKey()) { 1088 ALOGE("Failed to delete user %d's master key", userId); 1089 } 1090 if (!keepUnenryptedEntries) { 1091 if(!userState->reset()) { 1092 ALOGE("Failed to remove user %d's directory", userId); 1093 } 1094 } 1095 } 1096 1097 bool isEmpty(uid_t userId) const { 1098 const UserState* userState = getUserState(userId); 1099 if (userState == NULL) { 1100 return true; 1101 } 1102 1103 DIR* dir = opendir(userState->getUserDirName()); 1104 if (!dir) { 1105 return true; 1106 } 1107 1108 bool result = true; 1109 struct dirent* file; 1110 while ((file = readdir(dir)) != NULL) { 1111 // We only care about files. 1112 if (file->d_type != DT_REG) { 1113 continue; 1114 } 1115 1116 // Skip anything that starts with a "." 1117 if (file->d_name[0] == '.') { 1118 continue; 1119 } 1120 1121 result = false; 1122 break; 1123 } 1124 closedir(dir); 1125 return result; 1126 } 1127 1128 void lock(uid_t userId) { 1129 UserState* userState = getUserState(userId); 1130 userState->zeroizeMasterKeysInMemory(); 1131 userState->setState(STATE_LOCKED); 1132 } 1133 1134 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) { 1135 UserState* userState = getUserState(userId); 1136 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(), 1137 userState->getState()); 1138 if (rc != NO_ERROR) { 1139 return rc; 1140 } 1141 1142 const uint8_t version = keyBlob->getVersion(); 1143 if (version < CURRENT_BLOB_VERSION) { 1144 /* If we upgrade the key, we need to write it to disk again. Then 1145 * it must be read it again since the blob is encrypted each time 1146 * it's written. 1147 */ 1148 if (upgradeBlob(filename, keyBlob, version, type, userId)) { 1149 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR 1150 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(), 1151 userState->getState())) != NO_ERROR) { 1152 return rc; 1153 } 1154 } 1155 } 1156 1157 /* 1158 * This will upgrade software-backed keys to hardware-backed keys when 1159 * the HAL for the device supports the newer key types. 1160 */ 1161 if (rc == NO_ERROR && type == TYPE_KEY_PAIR 1162 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 1163 && keyBlob->isFallback()) { 1164 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename, 1165 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); 1166 1167 // The HAL allowed the import, reget the key to have the "fresh" 1168 // version. 1169 if (imported == NO_ERROR) { 1170 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId); 1171 } 1172 } 1173 1174 if (type != TYPE_ANY && keyBlob->getType() != type) { 1175 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type); 1176 return KEY_NOT_FOUND; 1177 } 1178 1179 return rc; 1180 } 1181 1182 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) { 1183 UserState* userState = getUserState(userId); 1184 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(), 1185 mEntropy); 1186 } 1187 1188 ResponseCode del(const char *filename, const BlobType type, uid_t userId) { 1189 Blob keyBlob; 1190 ResponseCode rc = get(filename, &keyBlob, type, userId); 1191 if (rc != ::NO_ERROR) { 1192 return rc; 1193 } 1194 1195 if (keyBlob.getType() == ::TYPE_KEY_PAIR) { 1196 // A device doesn't have to implement delete_keypair. 1197 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) { 1198 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) { 1199 rc = ::SYSTEM_ERROR; 1200 } 1201 } 1202 } 1203 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) { 1204 keymaster1_device_t* dev = getDeviceForBlob(keyBlob); 1205 if (dev->delete_key) { 1206 keymaster_key_blob_t blob; 1207 blob.key_material = keyBlob.getValue(); 1208 blob.key_material_size = keyBlob.getLength(); 1209 dev->delete_key(dev, &blob); 1210 } 1211 } 1212 if (rc != ::NO_ERROR) { 1213 return rc; 1214 } 1215 1216 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR; 1217 } 1218 1219 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches, 1220 uid_t userId) { 1221 1222 UserState* userState = getUserState(userId); 1223 size_t n = prefix.length(); 1224 1225 DIR* dir = opendir(userState->getUserDirName()); 1226 if (!dir) { 1227 ALOGW("can't open directory for user: %s", strerror(errno)); 1228 return ::SYSTEM_ERROR; 1229 } 1230 1231 struct dirent* file; 1232 while ((file = readdir(dir)) != NULL) { 1233 // We only care about files. 1234 if (file->d_type != DT_REG) { 1235 continue; 1236 } 1237 1238 // Skip anything that starts with a "." 1239 if (file->d_name[0] == '.') { 1240 continue; 1241 } 1242 1243 if (!strncmp(prefix.string(), file->d_name, n)) { 1244 const char* p = &file->d_name[n]; 1245 size_t plen = strlen(p); 1246 1247 size_t extra = decode_key_length(p, plen); 1248 char *match = (char*) malloc(extra + 1); 1249 if (match != NULL) { 1250 decode_key(match, p, plen); 1251 matches->push(android::String16(match, extra)); 1252 free(match); 1253 } else { 1254 ALOGW("could not allocate match of size %zd", extra); 1255 } 1256 } 1257 } 1258 closedir(dir); 1259 return ::NO_ERROR; 1260 } 1261 1262 void addGrant(const char* filename, uid_t granteeUid) { 1263 const grant_t* existing = getGrant(filename, granteeUid); 1264 if (existing == NULL) { 1265 grant_t* grant = new grant_t; 1266 grant->uid = granteeUid; 1267 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename)); 1268 mGrants.add(grant); 1269 } 1270 } 1271 1272 bool removeGrant(const char* filename, uid_t granteeUid) { 1273 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); 1274 it != mGrants.end(); it++) { 1275 grant_t* grant = *it; 1276 if (grant->uid == granteeUid 1277 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) { 1278 mGrants.erase(it); 1279 return true; 1280 } 1281 } 1282 return false; 1283 } 1284 1285 bool hasGrant(const char* filename, const uid_t uid) const { 1286 return getGrant(filename, uid) != NULL; 1287 } 1288 1289 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId, 1290 int32_t flags) { 1291 uint8_t* data; 1292 size_t dataLength; 1293 int rc; 1294 1295 if (mDevice->import_keypair == NULL) { 1296 ALOGE("Keymaster doesn't support import!"); 1297 return SYSTEM_ERROR; 1298 } 1299 1300 bool isFallback = false; 1301 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength); 1302 if (rc) { 1303 /* 1304 * Maybe the device doesn't support this type of key. Try to use the 1305 * software fallback keymaster implementation. This is a little bit 1306 * lazier than checking the PKCS#8 key type, but the software 1307 * implementation will do that anyway. 1308 */ 1309 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength); 1310 isFallback = true; 1311 1312 if (rc) { 1313 ALOGE("Error while importing keypair: %d", rc); 1314 return SYSTEM_ERROR; 1315 } 1316 } 1317 1318 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR); 1319 free(data); 1320 1321 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 1322 keyBlob.setFallback(isFallback); 1323 1324 return put(filename, &keyBlob, userId); 1325 } 1326 1327 bool isHardwareBacked(const android::String16& keyType) const { 1328 if (mDevice == NULL) { 1329 ALOGW("can't get keymaster device"); 1330 return false; 1331 } 1332 1333 if (sRSAKeyType == keyType) { 1334 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0; 1335 } else { 1336 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 1337 && (mDevice->common.module->module_api_version 1338 >= KEYMASTER_MODULE_API_VERSION_0_2); 1339 } 1340 } 1341 1342 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid, 1343 const BlobType type) { 1344 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid)); 1345 uid_t userId = get_user_id(uid); 1346 1347 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId); 1348 if (responseCode == NO_ERROR) { 1349 return responseCode; 1350 } 1351 1352 // If this is one of the legacy UID->UID mappings, use it. 1353 uid_t euid = get_keystore_euid(uid); 1354 if (euid != uid) { 1355 filepath8 = getKeyNameForUidWithDir(keyName, euid); 1356 responseCode = get(filepath8.string(), keyBlob, type, userId); 1357 if (responseCode == NO_ERROR) { 1358 return responseCode; 1359 } 1360 } 1361 1362 // They might be using a granted key. 1363 android::String8 filename8 = getKeyName(keyName); 1364 char* end; 1365 strtoul(filename8.string(), &end, 10); 1366 if (end[0] != '_' || end[1] == 0) { 1367 return KEY_NOT_FOUND; 1368 } 1369 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(), 1370 filename8.string()); 1371 if (!hasGrant(filepath8.string(), uid)) { 1372 return responseCode; 1373 } 1374 1375 // It is a granted key. Try to load it. 1376 return get(filepath8.string(), keyBlob, type, userId); 1377 } 1378 1379 /** 1380 * Returns any existing UserState or creates it if it doesn't exist. 1381 */ 1382 UserState* getUserState(uid_t userId) { 1383 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); 1384 it != mMasterKeys.end(); it++) { 1385 UserState* state = *it; 1386 if (state->getUserId() == userId) { 1387 return state; 1388 } 1389 } 1390 1391 UserState* userState = new UserState(userId); 1392 if (!userState->initialize()) { 1393 /* There's not much we can do if initialization fails. Trying to 1394 * unlock the keystore for that user will fail as well, so any 1395 * subsequent request for this user will just return SYSTEM_ERROR. 1396 */ 1397 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId); 1398 } 1399 mMasterKeys.add(userState); 1400 return userState; 1401 } 1402 1403 /** 1404 * Returns any existing UserState or creates it if it doesn't exist. 1405 */ 1406 UserState* getUserStateByUid(uid_t uid) { 1407 uid_t userId = get_user_id(uid); 1408 return getUserState(userId); 1409 } 1410 1411 /** 1412 * Returns NULL if the UserState doesn't already exist. 1413 */ 1414 const UserState* getUserState(uid_t userId) const { 1415 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin()); 1416 it != mMasterKeys.end(); it++) { 1417 UserState* state = *it; 1418 if (state->getUserId() == userId) { 1419 return state; 1420 } 1421 } 1422 1423 return NULL; 1424 } 1425 1426 /** 1427 * Returns NULL if the UserState doesn't already exist. 1428 */ 1429 const UserState* getUserStateByUid(uid_t uid) const { 1430 uid_t userId = get_user_id(uid); 1431 return getUserState(userId); 1432 } 1433 1434private: 1435 static const char* sOldMasterKey; 1436 static const char* sMetaDataFile; 1437 static const android::String16 sRSAKeyType; 1438 Entropy* mEntropy; 1439 1440 keymaster1_device_t* mDevice; 1441 keymaster1_device_t* mFallbackDevice; 1442 1443 android::Vector<UserState*> mMasterKeys; 1444 1445 android::Vector<grant_t*> mGrants; 1446 1447 typedef struct { 1448 uint32_t version; 1449 } keystore_metadata_t; 1450 1451 keystore_metadata_t mMetaData; 1452 1453 const grant_t* getGrant(const char* filename, uid_t uid) const { 1454 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); 1455 it != mGrants.end(); it++) { 1456 grant_t* grant = *it; 1457 if (grant->uid == uid 1458 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) { 1459 return grant; 1460 } 1461 } 1462 return NULL; 1463 } 1464 1465 /** 1466 * Upgrade code. This will upgrade the key from the current version 1467 * to whatever is newest. 1468 */ 1469 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion, 1470 const BlobType type, uid_t uid) { 1471 bool updated = false; 1472 uint8_t version = oldVersion; 1473 1474 /* From V0 -> V1: All old types were unknown */ 1475 if (version == 0) { 1476 ALOGV("upgrading to version 1 and setting type %d", type); 1477 1478 blob->setType(type); 1479 if (type == TYPE_KEY_PAIR) { 1480 importBlobAsKey(blob, filename, uid); 1481 } 1482 version = 1; 1483 updated = true; 1484 } 1485 1486 /* From V1 -> V2: All old keys were encrypted */ 1487 if (version == 1) { 1488 ALOGV("upgrading to version 2"); 1489 1490 blob->setEncrypted(true); 1491 version = 2; 1492 updated = true; 1493 } 1494 1495 /* 1496 * If we've updated, set the key blob to the right version 1497 * and write it. 1498 */ 1499 if (updated) { 1500 ALOGV("updated and writing file %s", filename); 1501 blob->setVersion(version); 1502 } 1503 1504 return updated; 1505 } 1506 1507 /** 1508 * Takes a blob that is an PEM-encoded RSA key as a byte array and 1509 * converts it to a DER-encoded PKCS#8 for import into a keymaster. 1510 * Then it overwrites the original blob with the new blob 1511 * format that is returned from the keymaster. 1512 */ 1513 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) { 1514 // We won't even write to the blob directly with this BIO, so const_cast is okay. 1515 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength())); 1516 if (b.get() == NULL) { 1517 ALOGE("Problem instantiating BIO"); 1518 return SYSTEM_ERROR; 1519 } 1520 1521 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL)); 1522 if (pkey.get() == NULL) { 1523 ALOGE("Couldn't read old PEM file"); 1524 return SYSTEM_ERROR; 1525 } 1526 1527 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get())); 1528 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL); 1529 if (len < 0) { 1530 ALOGE("Couldn't measure PKCS#8 length"); 1531 return SYSTEM_ERROR; 1532 } 1533 1534 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]); 1535 uint8_t* tmp = pkcs8key.get(); 1536 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) { 1537 ALOGE("Couldn't convert to PKCS#8"); 1538 return SYSTEM_ERROR; 1539 } 1540 1541 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid), 1542 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); 1543 if (rc != NO_ERROR) { 1544 return rc; 1545 } 1546 1547 return get(filename, blob, TYPE_KEY_PAIR, uid); 1548 } 1549 1550 void readMetaData() { 1551 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY)); 1552 if (in < 0) { 1553 return; 1554 } 1555 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData)); 1556 if (fileLength != sizeof(mMetaData)) { 1557 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, 1558 sizeof(mMetaData)); 1559 } 1560 close(in); 1561 } 1562 1563 void writeMetaData() { 1564 const char* tmpFileName = ".metadata.tmp"; 1565 int out = TEMP_FAILURE_RETRY(open(tmpFileName, 1566 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)); 1567 if (out < 0) { 1568 ALOGE("couldn't write metadata file: %s", strerror(errno)); 1569 return; 1570 } 1571 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData)); 1572 if (fileLength != sizeof(mMetaData)) { 1573 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength, 1574 sizeof(mMetaData)); 1575 } 1576 close(out); 1577 rename(tmpFileName, sMetaDataFile); 1578 } 1579 1580 bool upgradeKeystore() { 1581 bool upgraded = false; 1582 1583 if (mMetaData.version == 0) { 1584 UserState* userState = getUserStateByUid(0); 1585 1586 // Initialize first so the directory is made. 1587 userState->initialize(); 1588 1589 // Migrate the old .masterkey file to user 0. 1590 if (access(sOldMasterKey, R_OK) == 0) { 1591 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) { 1592 ALOGE("couldn't migrate old masterkey: %s", strerror(errno)); 1593 return false; 1594 } 1595 } 1596 1597 // Initialize again in case we had a key. 1598 userState->initialize(); 1599 1600 // Try to migrate existing keys. 1601 DIR* dir = opendir("."); 1602 if (!dir) { 1603 // Give up now; maybe we can upgrade later. 1604 ALOGE("couldn't open keystore's directory; something is wrong"); 1605 return false; 1606 } 1607 1608 struct dirent* file; 1609 while ((file = readdir(dir)) != NULL) { 1610 // We only care about files. 1611 if (file->d_type != DT_REG) { 1612 continue; 1613 } 1614 1615 // Skip anything that starts with a "." 1616 if (file->d_name[0] == '.') { 1617 continue; 1618 } 1619 1620 // Find the current file's user. 1621 char* end; 1622 unsigned long thisUid = strtoul(file->d_name, &end, 10); 1623 if (end[0] != '_' || end[1] == 0) { 1624 continue; 1625 } 1626 UserState* otherUser = getUserStateByUid(thisUid); 1627 if (otherUser->getUserId() != 0) { 1628 unlinkat(dirfd(dir), file->d_name, 0); 1629 } 1630 1631 // Rename the file into user directory. 1632 DIR* otherdir = opendir(otherUser->getUserDirName()); 1633 if (otherdir == NULL) { 1634 ALOGW("couldn't open user directory for rename"); 1635 continue; 1636 } 1637 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) { 1638 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno)); 1639 } 1640 closedir(otherdir); 1641 } 1642 closedir(dir); 1643 1644 mMetaData.version = 1; 1645 upgraded = true; 1646 } 1647 1648 return upgraded; 1649 } 1650}; 1651 1652const char* KeyStore::sOldMasterKey = ".masterkey"; 1653const char* KeyStore::sMetaDataFile = ".metadata"; 1654 1655const android::String16 KeyStore::sRSAKeyType("RSA"); 1656 1657namespace android { 1658class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient { 1659public: 1660 KeyStoreProxy(KeyStore* keyStore) 1661 : mKeyStore(keyStore), 1662 mOperationMap(this) 1663 { 1664 } 1665 1666 void binderDied(const wp<IBinder>& who) { 1667 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get()); 1668 for (auto token: operations) { 1669 abort(token); 1670 } 1671 } 1672 1673 int32_t getState(int32_t userId) { 1674 if (!checkBinderPermission(P_GET_STATE)) { 1675 return ::PERMISSION_DENIED; 1676 } 1677 1678 return mKeyStore->getState(userId); 1679 } 1680 1681 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) { 1682 if (!checkBinderPermission(P_GET)) { 1683 return ::PERMISSION_DENIED; 1684 } 1685 1686 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1687 String8 name8(name); 1688 Blob keyBlob; 1689 1690 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 1691 TYPE_GENERIC); 1692 if (responseCode != ::NO_ERROR) { 1693 ALOGW("Could not read %s", name8.string()); 1694 *item = NULL; 1695 *itemLength = 0; 1696 return responseCode; 1697 } 1698 1699 *item = (uint8_t*) malloc(keyBlob.getLength()); 1700 memcpy(*item, keyBlob.getValue(), keyBlob.getLength()); 1701 *itemLength = keyBlob.getLength(); 1702 1703 return ::NO_ERROR; 1704 } 1705 1706 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid, 1707 int32_t flags) { 1708 targetUid = getEffectiveUid(targetUid); 1709 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, 1710 flags & KEYSTORE_FLAG_ENCRYPTED); 1711 if (result != ::NO_ERROR) { 1712 return result; 1713 } 1714 1715 String8 name8(name); 1716 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1717 1718 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC); 1719 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 1720 1721 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid)); 1722 } 1723 1724 int32_t del(const String16& name, int targetUid) { 1725 targetUid = getEffectiveUid(targetUid); 1726 if (!checkBinderPermission(P_DELETE, targetUid)) { 1727 return ::PERMISSION_DENIED; 1728 } 1729 String8 name8(name); 1730 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1731 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid)); 1732 } 1733 1734 int32_t exist(const String16& name, int targetUid) { 1735 targetUid = getEffectiveUid(targetUid); 1736 if (!checkBinderPermission(P_EXIST, targetUid)) { 1737 return ::PERMISSION_DENIED; 1738 } 1739 1740 String8 name8(name); 1741 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 1742 1743 if (access(filename.string(), R_OK) == -1) { 1744 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND; 1745 } 1746 return ::NO_ERROR; 1747 } 1748 1749 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) { 1750 targetUid = getEffectiveUid(targetUid); 1751 if (!checkBinderPermission(P_LIST, targetUid)) { 1752 return ::PERMISSION_DENIED; 1753 } 1754 const String8 prefix8(prefix); 1755 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid)); 1756 1757 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) { 1758 return ::SYSTEM_ERROR; 1759 } 1760 return ::NO_ERROR; 1761 } 1762 1763 int32_t reset() { 1764 if (!checkBinderPermission(P_RESET)) { 1765 return ::PERMISSION_DENIED; 1766 } 1767 1768 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 1769 mKeyStore->resetUser(get_user_id(callingUid), false); 1770 return ::NO_ERROR; 1771 } 1772 1773 int32_t onUserPasswordChanged(int32_t userId, const String16& password) { 1774 if (!checkBinderPermission(P_PASSWORD)) { 1775 return ::PERMISSION_DENIED; 1776 } 1777 1778 const String8 password8(password); 1779 // Flush the auth token table to prevent stale tokens from sticking 1780 // around. 1781 mAuthTokenTable.Clear(); 1782 1783 if (password.size() == 0) { 1784 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId); 1785 mKeyStore->resetUser(userId, true); 1786 return ::NO_ERROR; 1787 } else { 1788 switch (mKeyStore->getState(userId)) { 1789 case ::STATE_UNINITIALIZED: { 1790 // generate master key, encrypt with password, write to file, 1791 // initialize mMasterKey*. 1792 return mKeyStore->initializeUser(password8, userId); 1793 } 1794 case ::STATE_NO_ERROR: { 1795 // rewrite master key with new password. 1796 return mKeyStore->writeMasterKey(password8, userId); 1797 } 1798 case ::STATE_LOCKED: { 1799 ALOGE("Changing user %d's password while locked, clearing old encryption", 1800 userId); 1801 mKeyStore->resetUser(userId, true); 1802 return mKeyStore->initializeUser(password8, userId); 1803 } 1804 } 1805 return ::SYSTEM_ERROR; 1806 } 1807 } 1808 1809 int32_t onUserAdded(int32_t userId, int32_t parentId) { 1810 if (!checkBinderPermission(P_USER_CHANGED)) { 1811 return ::PERMISSION_DENIED; 1812 } 1813 1814 // Sanity check that the new user has an empty keystore. 1815 if (!mKeyStore->isEmpty(userId)) { 1816 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId); 1817 } 1818 // Unconditionally clear the keystore, just to be safe. 1819 mKeyStore->resetUser(userId, false); 1820 1821 // If the user has a parent user then use the parent's 1822 // masterkey/password, otherwise there's nothing to do. 1823 if (parentId != -1) { 1824 return mKeyStore->copyMasterKey(parentId, userId); 1825 } else { 1826 return ::NO_ERROR; 1827 } 1828 } 1829 1830 int32_t onUserRemoved(int32_t userId) { 1831 if (!checkBinderPermission(P_USER_CHANGED)) { 1832 return ::PERMISSION_DENIED; 1833 } 1834 1835 mKeyStore->resetUser(userId, false); 1836 return ::NO_ERROR; 1837 } 1838 1839 int32_t lock(int32_t userId) { 1840 if (!checkBinderPermission(P_LOCK)) { 1841 return ::PERMISSION_DENIED; 1842 } 1843 1844 State state = mKeyStore->getState(userId); 1845 if (state != ::STATE_NO_ERROR) { 1846 ALOGD("calling lock in state: %d", state); 1847 return state; 1848 } 1849 1850 mKeyStore->lock(userId); 1851 return ::NO_ERROR; 1852 } 1853 1854 int32_t unlock(int32_t userId, const String16& pw) { 1855 if (!checkBinderPermission(P_UNLOCK)) { 1856 return ::PERMISSION_DENIED; 1857 } 1858 1859 State state = mKeyStore->getState(userId); 1860 if (state != ::STATE_LOCKED) { 1861 ALOGI("calling unlock when not locked, ignoring."); 1862 return state; 1863 } 1864 1865 const String8 password8(pw); 1866 // read master key, decrypt with password, initialize mMasterKey*. 1867 return mKeyStore->readMasterKey(password8, userId); 1868 } 1869 1870 bool isEmpty(int32_t userId) { 1871 if (!checkBinderPermission(P_IS_EMPTY)) { 1872 return false; 1873 } 1874 1875 return mKeyStore->isEmpty(userId); 1876 } 1877 1878 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize, 1879 int32_t flags, Vector<sp<KeystoreArg> >* args) { 1880 targetUid = getEffectiveUid(targetUid); 1881 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, 1882 flags & KEYSTORE_FLAG_ENCRYPTED); 1883 if (result != ::NO_ERROR) { 1884 return result; 1885 } 1886 uint8_t* data; 1887 size_t dataLength; 1888 int rc; 1889 bool isFallback = false; 1890 1891 const keymaster1_device_t* device = mKeyStore->getDevice(); 1892 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice(); 1893 if (device == NULL) { 1894 return ::SYSTEM_ERROR; 1895 } 1896 1897 if (device->generate_keypair == NULL) { 1898 return ::SYSTEM_ERROR; 1899 } 1900 1901 if (keyType == EVP_PKEY_DSA) { 1902 keymaster_dsa_keygen_params_t dsa_params; 1903 memset(&dsa_params, '\0', sizeof(dsa_params)); 1904 1905 if (keySize == -1) { 1906 keySize = DSA_DEFAULT_KEY_SIZE; 1907 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE 1908 || keySize > DSA_MAX_KEY_SIZE) { 1909 ALOGI("invalid key size %d", keySize); 1910 return ::SYSTEM_ERROR; 1911 } 1912 dsa_params.key_size = keySize; 1913 1914 if (args->size() == 3) { 1915 sp<KeystoreArg> gArg = args->itemAt(0); 1916 sp<KeystoreArg> pArg = args->itemAt(1); 1917 sp<KeystoreArg> qArg = args->itemAt(2); 1918 1919 if (gArg != NULL && pArg != NULL && qArg != NULL) { 1920 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data()); 1921 dsa_params.generator_len = gArg->size(); 1922 1923 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data()); 1924 dsa_params.prime_p_len = pArg->size(); 1925 1926 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data()); 1927 dsa_params.prime_q_len = qArg->size(); 1928 } else { 1929 ALOGI("not all DSA parameters were read"); 1930 return ::SYSTEM_ERROR; 1931 } 1932 } else if (args->size() != 0) { 1933 ALOGI("DSA args must be 3"); 1934 return ::SYSTEM_ERROR; 1935 } 1936 1937 if (isKeyTypeSupported(device, TYPE_DSA)) { 1938 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength); 1939 } else { 1940 isFallback = true; 1941 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data, 1942 &dataLength); 1943 } 1944 } else if (keyType == EVP_PKEY_EC) { 1945 keymaster_ec_keygen_params_t ec_params; 1946 memset(&ec_params, '\0', sizeof(ec_params)); 1947 1948 if (keySize == -1) { 1949 keySize = EC_DEFAULT_KEY_SIZE; 1950 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) { 1951 ALOGI("invalid key size %d", keySize); 1952 return ::SYSTEM_ERROR; 1953 } 1954 ec_params.field_size = keySize; 1955 1956 if (isKeyTypeSupported(device, TYPE_EC)) { 1957 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength); 1958 } else { 1959 isFallback = true; 1960 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength); 1961 } 1962 } else if (keyType == EVP_PKEY_RSA) { 1963 keymaster_rsa_keygen_params_t rsa_params; 1964 memset(&rsa_params, '\0', sizeof(rsa_params)); 1965 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT; 1966 1967 if (keySize == -1) { 1968 keySize = RSA_DEFAULT_KEY_SIZE; 1969 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) { 1970 ALOGI("invalid key size %d", keySize); 1971 return ::SYSTEM_ERROR; 1972 } 1973 rsa_params.modulus_size = keySize; 1974 1975 if (args->size() > 1) { 1976 ALOGI("invalid number of arguments: %zu", args->size()); 1977 return ::SYSTEM_ERROR; 1978 } else if (args->size() == 1) { 1979 sp<KeystoreArg> pubExpBlob = args->itemAt(0); 1980 if (pubExpBlob != NULL) { 1981 Unique_BIGNUM pubExpBn( 1982 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()), 1983 pubExpBlob->size(), NULL)); 1984 if (pubExpBn.get() == NULL) { 1985 ALOGI("Could not convert public exponent to BN"); 1986 return ::SYSTEM_ERROR; 1987 } 1988 unsigned long pubExp = BN_get_word(pubExpBn.get()); 1989 if (pubExp == 0xFFFFFFFFL) { 1990 ALOGI("cannot represent public exponent as a long value"); 1991 return ::SYSTEM_ERROR; 1992 } 1993 rsa_params.public_exponent = pubExp; 1994 } 1995 } 1996 1997 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength); 1998 } else { 1999 ALOGW("Unsupported key type %d", keyType); 2000 rc = -1; 2001 } 2002 2003 if (rc) { 2004 return ::SYSTEM_ERROR; 2005 } 2006 2007 String8 name8(name); 2008 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 2009 2010 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR); 2011 free(data); 2012 2013 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 2014 keyBlob.setFallback(isFallback); 2015 2016 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid)); 2017 } 2018 2019 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid, 2020 int32_t flags) { 2021 targetUid = getEffectiveUid(targetUid); 2022 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, 2023 flags & KEYSTORE_FLAG_ENCRYPTED); 2024 if (result != ::NO_ERROR) { 2025 return result; 2026 } 2027 String8 name8(name); 2028 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 2029 2030 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid), 2031 flags); 2032 } 2033 2034 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out, 2035 size_t* outLength) { 2036 if (!checkBinderPermission(P_SIGN)) { 2037 return ::PERMISSION_DENIED; 2038 } 2039 2040 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2041 Blob keyBlob; 2042 String8 name8(name); 2043 2044 ALOGV("sign %s from uid %d", name8.string(), callingUid); 2045 2046 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2047 ::TYPE_KEY_PAIR); 2048 if (responseCode != ::NO_ERROR) { 2049 return responseCode; 2050 } 2051 2052 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob); 2053 if (device == NULL) { 2054 ALOGE("no keymaster device; cannot sign"); 2055 return ::SYSTEM_ERROR; 2056 } 2057 2058 if (device->sign_data == NULL) { 2059 ALOGE("device doesn't implement signing"); 2060 return ::SYSTEM_ERROR; 2061 } 2062 2063 keymaster_rsa_sign_params_t params; 2064 params.digest_type = DIGEST_NONE; 2065 params.padding_type = PADDING_NONE; 2066 int rc = device->sign_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, 2067 length, out, outLength); 2068 if (rc) { 2069 ALOGW("device couldn't sign data"); 2070 return ::SYSTEM_ERROR; 2071 } 2072 2073 return ::NO_ERROR; 2074 } 2075 2076 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength, 2077 const uint8_t* signature, size_t signatureLength) { 2078 if (!checkBinderPermission(P_VERIFY)) { 2079 return ::PERMISSION_DENIED; 2080 } 2081 2082 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2083 Blob keyBlob; 2084 String8 name8(name); 2085 int rc; 2086 2087 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2088 TYPE_KEY_PAIR); 2089 if (responseCode != ::NO_ERROR) { 2090 return responseCode; 2091 } 2092 2093 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob); 2094 if (device == NULL) { 2095 return ::SYSTEM_ERROR; 2096 } 2097 2098 if (device->verify_data == NULL) { 2099 return ::SYSTEM_ERROR; 2100 } 2101 2102 keymaster_rsa_sign_params_t params; 2103 params.digest_type = DIGEST_NONE; 2104 params.padding_type = PADDING_NONE; 2105 2106 rc = device->verify_data(device, ¶ms, keyBlob.getValue(), keyBlob.getLength(), data, 2107 dataLength, signature, signatureLength); 2108 if (rc) { 2109 return ::SYSTEM_ERROR; 2110 } else { 2111 return ::NO_ERROR; 2112 } 2113 } 2114 2115 /* 2116 * TODO: The abstraction between things stored in hardware and regular blobs 2117 * of data stored on the filesystem should be moved down to keystore itself. 2118 * Unfortunately the Java code that calls this has naming conventions that it 2119 * knows about. Ideally keystore shouldn't be used to store random blobs of 2120 * data. 2121 * 2122 * Until that happens, it's necessary to have a separate "get_pubkey" and 2123 * "del_key" since the Java code doesn't really communicate what it's 2124 * intentions are. 2125 */ 2126 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) { 2127 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2128 if (!checkBinderPermission(P_GET)) { 2129 ALOGW("permission denied for %d: get_pubkey", callingUid); 2130 return ::PERMISSION_DENIED; 2131 } 2132 2133 Blob keyBlob; 2134 String8 name8(name); 2135 2136 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid); 2137 2138 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2139 TYPE_KEY_PAIR); 2140 if (responseCode != ::NO_ERROR) { 2141 return responseCode; 2142 } 2143 2144 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob); 2145 if (device == NULL) { 2146 return ::SYSTEM_ERROR; 2147 } 2148 2149 if (device->get_keypair_public == NULL) { 2150 ALOGE("device has no get_keypair_public implementation!"); 2151 return ::SYSTEM_ERROR; 2152 } 2153 2154 int rc; 2155 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey, 2156 pubkeyLength); 2157 if (rc) { 2158 return ::SYSTEM_ERROR; 2159 } 2160 2161 return ::NO_ERROR; 2162 } 2163 2164 int32_t grant(const String16& name, int32_t granteeUid) { 2165 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2166 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT); 2167 if (result != ::NO_ERROR) { 2168 return result; 2169 } 2170 2171 String8 name8(name); 2172 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid)); 2173 2174 if (access(filename.string(), R_OK) == -1) { 2175 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND; 2176 } 2177 2178 mKeyStore->addGrant(filename.string(), granteeUid); 2179 return ::NO_ERROR; 2180 } 2181 2182 int32_t ungrant(const String16& name, int32_t granteeUid) { 2183 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2184 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT); 2185 if (result != ::NO_ERROR) { 2186 return result; 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 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND; 2197 } 2198 2199 int64_t getmtime(const String16& name) { 2200 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2201 if (!checkBinderPermission(P_GET)) { 2202 ALOGW("permission denied for %d: getmtime", callingUid); 2203 return -1L; 2204 } 2205 2206 String8 name8(name); 2207 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid)); 2208 2209 if (access(filename.string(), R_OK) == -1) { 2210 ALOGW("could not access %s for getmtime", filename.string()); 2211 return -1L; 2212 } 2213 2214 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY)); 2215 if (fd < 0) { 2216 ALOGW("could not open %s for getmtime", filename.string()); 2217 return -1L; 2218 } 2219 2220 struct stat s; 2221 int ret = fstat(fd, &s); 2222 close(fd); 2223 if (ret == -1) { 2224 ALOGW("could not stat %s for getmtime", filename.string()); 2225 return -1L; 2226 } 2227 2228 return static_cast<int64_t>(s.st_mtime); 2229 } 2230 2231 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey, 2232 int32_t destUid) { 2233 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2234 pid_t spid = IPCThreadState::self()->getCallingPid(); 2235 if (!has_permission(callingUid, P_DUPLICATE, spid)) { 2236 ALOGW("permission denied for %d: duplicate", callingUid); 2237 return -1L; 2238 } 2239 2240 State state = mKeyStore->getState(get_user_id(callingUid)); 2241 if (!isKeystoreUnlocked(state)) { 2242 ALOGD("calling duplicate in state: %d", state); 2243 return state; 2244 } 2245 2246 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) { 2247 srcUid = callingUid; 2248 } else if (!is_granted_to(callingUid, srcUid)) { 2249 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid); 2250 return ::PERMISSION_DENIED; 2251 } 2252 2253 if (destUid == -1) { 2254 destUid = callingUid; 2255 } 2256 2257 if (srcUid != destUid) { 2258 if (static_cast<uid_t>(srcUid) != callingUid) { 2259 ALOGD("can only duplicate from caller to other or to same uid: " 2260 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid); 2261 return ::PERMISSION_DENIED; 2262 } 2263 2264 if (!is_granted_to(callingUid, destUid)) { 2265 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid); 2266 return ::PERMISSION_DENIED; 2267 } 2268 } 2269 2270 String8 source8(srcKey); 2271 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid)); 2272 2273 String8 target8(destKey); 2274 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid)); 2275 2276 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) { 2277 ALOGD("destination already exists: %s", targetFile.string()); 2278 return ::SYSTEM_ERROR; 2279 } 2280 2281 Blob keyBlob; 2282 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, 2283 get_user_id(srcUid)); 2284 if (responseCode != ::NO_ERROR) { 2285 return responseCode; 2286 } 2287 2288 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid)); 2289 } 2290 2291 int32_t is_hardware_backed(const String16& keyType) { 2292 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0; 2293 } 2294 2295 int32_t clear_uid(int64_t targetUid64) { 2296 uid_t targetUid = getEffectiveUid(targetUid64); 2297 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) { 2298 return ::PERMISSION_DENIED; 2299 } 2300 2301 String8 prefix = String8::format("%u_", targetUid); 2302 Vector<String16> aliases; 2303 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) { 2304 return ::SYSTEM_ERROR; 2305 } 2306 2307 for (uint32_t i = 0; i < aliases.size(); i++) { 2308 String8 name8(aliases[i]); 2309 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid)); 2310 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid)); 2311 } 2312 return ::NO_ERROR; 2313 } 2314 2315 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) { 2316 const keymaster1_device_t* device = mKeyStore->getDevice(); 2317 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice(); 2318 int32_t devResult = KM_ERROR_UNIMPLEMENTED; 2319 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED; 2320 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 && 2321 device->add_rng_entropy != NULL) { 2322 devResult = device->add_rng_entropy(device, data, dataLength); 2323 } 2324 if (fallback->add_rng_entropy) { 2325 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength); 2326 } 2327 if (devResult) { 2328 return devResult; 2329 } 2330 if (fallbackResult) { 2331 return fallbackResult; 2332 } 2333 return ::NO_ERROR; 2334 } 2335 2336 int32_t generateKey(const String16& name, const KeymasterArguments& params, 2337 const uint8_t* entropy, size_t entropyLength, int uid, int flags, 2338 KeyCharacteristics* outCharacteristics) { 2339 uid = getEffectiveUid(uid); 2340 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, 2341 flags & KEYSTORE_FLAG_ENCRYPTED); 2342 if (rc != ::NO_ERROR) { 2343 return rc; 2344 } 2345 2346 rc = KM_ERROR_UNIMPLEMENTED; 2347 bool isFallback = false; 2348 keymaster_key_blob_t blob; 2349 keymaster_key_characteristics_t *out = NULL; 2350 2351 const keymaster1_device_t* device = mKeyStore->getDevice(); 2352 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice(); 2353 if (device == NULL) { 2354 return ::SYSTEM_ERROR; 2355 } 2356 // TODO: Seed from Linux RNG before this. 2357 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 && 2358 device->generate_key != NULL) { 2359 if (!entropy) { 2360 rc = KM_ERROR_OK; 2361 } else if (device->add_rng_entropy) { 2362 rc = device->add_rng_entropy(device, entropy, entropyLength); 2363 } else { 2364 rc = KM_ERROR_UNIMPLEMENTED; 2365 } 2366 if (rc == KM_ERROR_OK) { 2367 rc = device->generate_key(device, params.params.data(), params.params.size(), 2368 &blob, &out); 2369 } 2370 } 2371 // If the HW device didn't support generate_key or generate_key failed 2372 // fall back to the software implementation. 2373 if (rc && fallback->generate_key != NULL) { 2374 isFallback = true; 2375 if (!entropy) { 2376 rc = KM_ERROR_OK; 2377 } else if (fallback->add_rng_entropy) { 2378 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength); 2379 } else { 2380 rc = KM_ERROR_UNIMPLEMENTED; 2381 } 2382 if (rc == KM_ERROR_OK) { 2383 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(), 2384 &blob, 2385 &out); 2386 } 2387 } 2388 2389 if (out) { 2390 if (outCharacteristics) { 2391 outCharacteristics->characteristics = *out; 2392 } else { 2393 keymaster_free_characteristics(out); 2394 } 2395 free(out); 2396 } 2397 2398 if (rc) { 2399 return rc; 2400 } 2401 2402 String8 name8(name); 2403 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid)); 2404 2405 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10); 2406 keyBlob.setFallback(isFallback); 2407 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 2408 2409 free(const_cast<uint8_t*>(blob.key_material)); 2410 2411 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid)); 2412 } 2413 2414 int32_t getKeyCharacteristics(const String16& name, 2415 const keymaster_blob_t* clientId, 2416 const keymaster_blob_t* appData, 2417 KeyCharacteristics* outCharacteristics) { 2418 if (!outCharacteristics) { 2419 return KM_ERROR_UNEXPECTED_NULL_POINTER; 2420 } 2421 2422 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2423 2424 Blob keyBlob; 2425 String8 name8(name); 2426 int rc; 2427 2428 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2429 TYPE_KEYMASTER_10); 2430 if (responseCode != ::NO_ERROR) { 2431 return responseCode; 2432 } 2433 keymaster_key_blob_t key; 2434 key.key_material_size = keyBlob.getLength(); 2435 key.key_material = keyBlob.getValue(); 2436 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob); 2437 keymaster_key_characteristics_t *out = NULL; 2438 if (!dev->get_key_characteristics) { 2439 ALOGW("device does not implement get_key_characteristics"); 2440 return KM_ERROR_UNIMPLEMENTED; 2441 } 2442 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out); 2443 if (out) { 2444 outCharacteristics->characteristics = *out; 2445 free(out); 2446 } 2447 return rc ? rc : ::NO_ERROR; 2448 } 2449 2450 int32_t importKey(const String16& name, const KeymasterArguments& params, 2451 keymaster_key_format_t format, const uint8_t *keyData, 2452 size_t keyLength, int uid, int flags, 2453 KeyCharacteristics* outCharacteristics) { 2454 uid = getEffectiveUid(uid); 2455 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, 2456 flags & KEYSTORE_FLAG_ENCRYPTED); 2457 if (rc != ::NO_ERROR) { 2458 return rc; 2459 } 2460 2461 rc = KM_ERROR_UNIMPLEMENTED; 2462 bool isFallback = false; 2463 keymaster_key_blob_t blob; 2464 keymaster_key_characteristics_t *out = NULL; 2465 2466 const keymaster1_device_t* device = mKeyStore->getDevice(); 2467 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice(); 2468 if (device == NULL) { 2469 return ::SYSTEM_ERROR; 2470 } 2471 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 && 2472 device->import_key != NULL) { 2473 rc = device->import_key(device, params.params.data(), params.params.size(), 2474 format, keyData, keyLength, &blob, &out); 2475 } 2476 if (rc && fallback->import_key != NULL) { 2477 isFallback = true; 2478 rc = fallback->import_key(fallback, params.params.data(), params.params.size(), 2479 format, keyData, keyLength, &blob, &out); 2480 } 2481 if (out) { 2482 if (outCharacteristics) { 2483 outCharacteristics->characteristics = *out; 2484 } else { 2485 keymaster_free_characteristics(out); 2486 } 2487 free(out); 2488 } 2489 if (rc) { 2490 return rc; 2491 } 2492 2493 String8 name8(name); 2494 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid)); 2495 2496 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10); 2497 keyBlob.setFallback(isFallback); 2498 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 2499 2500 free((void*) blob.key_material); 2501 2502 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid)); 2503 } 2504 2505 void exportKey(const String16& name, keymaster_key_format_t format, 2506 const keymaster_blob_t* clientId, 2507 const keymaster_blob_t* appData, ExportResult* result) { 2508 2509 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2510 2511 Blob keyBlob; 2512 String8 name8(name); 2513 int rc; 2514 2515 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2516 TYPE_KEYMASTER_10); 2517 if (responseCode != ::NO_ERROR) { 2518 result->resultCode = responseCode; 2519 return; 2520 } 2521 keymaster_key_blob_t key; 2522 key.key_material_size = keyBlob.getLength(); 2523 key.key_material = keyBlob.getValue(); 2524 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob); 2525 if (!dev->export_key) { 2526 result->resultCode = KM_ERROR_UNIMPLEMENTED; 2527 return; 2528 } 2529 uint8_t* ptr = NULL; 2530 rc = dev->export_key(dev, format, &key, clientId, appData, 2531 &ptr, &result->dataLength); 2532 result->exportData.reset(ptr); 2533 result->resultCode = rc ? rc : ::NO_ERROR; 2534 } 2535 2536 2537 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose, 2538 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy, 2539 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) { 2540 if (!result || !outParams) { 2541 ALOGE("Unexpected null arguments to begin()"); 2542 return; 2543 } 2544 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2545 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) { 2546 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid); 2547 result->resultCode = ::PERMISSION_DENIED; 2548 return; 2549 } 2550 if (!checkAllowedOperationParams(params.params)) { 2551 result->resultCode = KM_ERROR_INVALID_ARGUMENT; 2552 return; 2553 } 2554 Blob keyBlob; 2555 String8 name8(name); 2556 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, 2557 TYPE_KEYMASTER_10); 2558 if (responseCode != ::NO_ERROR) { 2559 result->resultCode = responseCode; 2560 return; 2561 } 2562 keymaster_key_blob_t key; 2563 key.key_material_size = keyBlob.getLength(); 2564 key.key_material = keyBlob.getValue(); 2565 keymaster_key_param_t* out; 2566 size_t outSize; 2567 keymaster_operation_handle_t handle; 2568 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob); 2569 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED; 2570 std::vector<keymaster_key_param_t> opParams(params.params); 2571 Unique_keymaster_key_characteristics characteristics; 2572 characteristics.reset(new keymaster_key_characteristics_t); 2573 err = getOperationCharacteristics(key, dev, opParams, characteristics.get()); 2574 if (err) { 2575 result->resultCode = err; 2576 return; 2577 } 2578 const hw_auth_token_t* authToken = NULL; 2579 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken, 2580 /*failOnTokenMissing*/ false); 2581 // If per-operation auth is needed we need to begin the operation and 2582 // the client will need to authorize that operation before calling 2583 // update. Any other auth issues stop here. 2584 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) { 2585 result->resultCode = authResult; 2586 return; 2587 } 2588 addAuthToParams(&opParams, authToken); 2589 // Add entropy to the device first. 2590 if (entropy) { 2591 if (dev->add_rng_entropy) { 2592 err = dev->add_rng_entropy(dev, entropy, entropyLength); 2593 } else { 2594 err = KM_ERROR_UNIMPLEMENTED; 2595 } 2596 if (err) { 2597 result->resultCode = err; 2598 return; 2599 } 2600 } 2601 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize, 2602 &handle); 2603 2604 // If there are too many operations abort the oldest operation that was 2605 // started as pruneable and try again. 2606 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) { 2607 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation(); 2608 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get()); 2609 if (abort(oldest) != ::NO_ERROR) { 2610 break; 2611 } 2612 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize, 2613 &handle); 2614 } 2615 if (err) { 2616 result->resultCode = err; 2617 return; 2618 } 2619 if (out) { 2620 outParams->params.assign(out, out + outSize); 2621 free(out); 2622 } 2623 2624 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken, 2625 characteristics.release(), 2626 pruneable); 2627 if (authToken) { 2628 mOperationMap.setOperationAuthToken(operationToken, authToken); 2629 } 2630 // Return the authentication lookup result. If this is a per operation 2631 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the 2632 // application should get an auth token using the handle before the 2633 // first call to update, which will fail if keystore hasn't received the 2634 // auth token. 2635 result->resultCode = authResult; 2636 result->token = operationToken; 2637 result->handle = handle; 2638 } 2639 2640 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data, 2641 size_t dataLength, OperationResult* result) { 2642 if (!checkAllowedOperationParams(params.params)) { 2643 result->resultCode = KM_ERROR_INVALID_ARGUMENT; 2644 return; 2645 } 2646 const keymaster1_device_t* dev; 2647 keymaster_operation_handle_t handle; 2648 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) { 2649 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE; 2650 return; 2651 } 2652 uint8_t* output_buf = NULL; 2653 size_t output_length = 0; 2654 size_t consumed = 0; 2655 std::vector<keymaster_key_param_t> opParams(params.params); 2656 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams); 2657 if (authResult != ::NO_ERROR) { 2658 result->resultCode = authResult; 2659 return; 2660 } 2661 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data, 2662 dataLength, &consumed, &output_buf, &output_length); 2663 result->data.reset(output_buf); 2664 result->dataLength = output_length; 2665 result->inputConsumed = consumed; 2666 result->resultCode = err ? (int32_t) err : ::NO_ERROR; 2667 } 2668 2669 void finish(const sp<IBinder>& token, const KeymasterArguments& params, 2670 const uint8_t* signature, size_t signatureLength, 2671 const uint8_t* entropy, size_t entropyLength, OperationResult* result) { 2672 if (!checkAllowedOperationParams(params.params)) { 2673 result->resultCode = KM_ERROR_INVALID_ARGUMENT; 2674 return; 2675 } 2676 const keymaster1_device_t* dev; 2677 keymaster_operation_handle_t handle; 2678 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) { 2679 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE; 2680 return; 2681 } 2682 uint8_t* output_buf = NULL; 2683 size_t output_length = 0; 2684 std::vector<keymaster_key_param_t> opParams(params.params); 2685 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams); 2686 if (authResult != ::NO_ERROR) { 2687 result->resultCode = authResult; 2688 return; 2689 } 2690 keymaster_error_t err; 2691 if (entropy) { 2692 if (dev->add_rng_entropy) { 2693 err = dev->add_rng_entropy(dev, entropy, entropyLength); 2694 } else { 2695 err = KM_ERROR_UNIMPLEMENTED; 2696 } 2697 if (err) { 2698 result->resultCode = err; 2699 return; 2700 } 2701 } 2702 2703 err = dev->finish(dev, handle, opParams.data(), opParams.size(), 2704 signature, signatureLength, &output_buf, 2705 &output_length); 2706 // Remove the operation regardless of the result 2707 mOperationMap.removeOperation(token); 2708 mAuthTokenTable.MarkCompleted(handle); 2709 result->data.reset(output_buf); 2710 result->dataLength = output_length; 2711 result->resultCode = err ? (int32_t) err : ::NO_ERROR; 2712 } 2713 2714 int32_t abort(const sp<IBinder>& token) { 2715 const keymaster1_device_t* dev; 2716 keymaster_operation_handle_t handle; 2717 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) { 2718 return KM_ERROR_INVALID_OPERATION_HANDLE; 2719 } 2720 mOperationMap.removeOperation(token); 2721 int32_t rc; 2722 if (!dev->abort) { 2723 rc = KM_ERROR_UNIMPLEMENTED; 2724 } else { 2725 rc = dev->abort(dev, handle); 2726 } 2727 mAuthTokenTable.MarkCompleted(handle); 2728 if (rc) { 2729 return rc; 2730 } 2731 return ::NO_ERROR; 2732 } 2733 2734 bool isOperationAuthorized(const sp<IBinder>& token) { 2735 const keymaster1_device_t* dev; 2736 keymaster_operation_handle_t handle; 2737 const keymaster_key_characteristics_t* characteristics; 2738 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) { 2739 return false; 2740 } 2741 const hw_auth_token_t* authToken = NULL; 2742 mOperationMap.getOperationAuthToken(token, &authToken); 2743 std::vector<keymaster_key_param_t> ignored; 2744 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored); 2745 return authResult == ::NO_ERROR; 2746 } 2747 2748 int32_t addAuthToken(const uint8_t* token, size_t length) { 2749 if (!checkBinderPermission(P_ADD_AUTH)) { 2750 ALOGW("addAuthToken: permission denied for %d", 2751 IPCThreadState::self()->getCallingUid()); 2752 return ::PERMISSION_DENIED; 2753 } 2754 if (length != sizeof(hw_auth_token_t)) { 2755 return KM_ERROR_INVALID_ARGUMENT; 2756 } 2757 hw_auth_token_t* authToken = new hw_auth_token_t; 2758 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t)); 2759 // The table takes ownership of authToken. 2760 mAuthTokenTable.AddAuthenticationToken(authToken); 2761 return ::NO_ERROR; 2762 } 2763 2764private: 2765 static const int32_t UID_SELF = -1; 2766 2767 /** 2768 * Get the effective target uid for a binder operation that takes an 2769 * optional uid as the target. 2770 */ 2771 inline uid_t getEffectiveUid(int32_t targetUid) { 2772 if (targetUid == UID_SELF) { 2773 return IPCThreadState::self()->getCallingUid(); 2774 } 2775 return static_cast<uid_t>(targetUid); 2776 } 2777 2778 /** 2779 * Check if the caller of the current binder method has the required 2780 * permission and if acting on other uids the grants to do so. 2781 */ 2782 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) { 2783 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2784 pid_t spid = IPCThreadState::self()->getCallingPid(); 2785 if (!has_permission(callingUid, permission, spid)) { 2786 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid); 2787 return false; 2788 } 2789 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) { 2790 ALOGW("uid %d not granted to act for %d", callingUid, targetUid); 2791 return false; 2792 } 2793 return true; 2794 } 2795 2796 /** 2797 * Check if the caller of the current binder method has the required 2798 * permission and the target uid is the caller or the caller is system. 2799 */ 2800 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) { 2801 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2802 pid_t spid = IPCThreadState::self()->getCallingPid(); 2803 if (!has_permission(callingUid, permission, spid)) { 2804 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid); 2805 return false; 2806 } 2807 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM; 2808 } 2809 2810 /** 2811 * Check if the caller of the current binder method has the required 2812 * permission or the target of the operation is the caller's uid. This is 2813 * for operation where the permission is only for cross-uid activity and all 2814 * uids are allowed to act on their own (ie: clearing all entries for a 2815 * given uid). 2816 */ 2817 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) { 2818 uid_t callingUid = IPCThreadState::self()->getCallingUid(); 2819 if (getEffectiveUid(targetUid) == callingUid) { 2820 return true; 2821 } else { 2822 return checkBinderPermission(permission, targetUid); 2823 } 2824 } 2825 2826 /** 2827 * Helper method to check that the caller has the required permission as 2828 * well as the keystore is in the unlocked state if checkUnlocked is true. 2829 * 2830 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and 2831 * otherwise the state of keystore when not unlocked and checkUnlocked is 2832 * true. 2833 */ 2834 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1, 2835 bool checkUnlocked = true) { 2836 if (!checkBinderPermission(permission, targetUid)) { 2837 return ::PERMISSION_DENIED; 2838 } 2839 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid))); 2840 if (checkUnlocked && !isKeystoreUnlocked(state)) { 2841 return state; 2842 } 2843 2844 return ::NO_ERROR; 2845 2846 } 2847 2848 inline bool isKeystoreUnlocked(State state) { 2849 switch (state) { 2850 case ::STATE_NO_ERROR: 2851 return true; 2852 case ::STATE_UNINITIALIZED: 2853 case ::STATE_LOCKED: 2854 return false; 2855 } 2856 return false; 2857 } 2858 2859 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) { 2860 const int32_t device_api = device->common.module->module_api_version; 2861 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) { 2862 switch (keyType) { 2863 case TYPE_RSA: 2864 case TYPE_DSA: 2865 case TYPE_EC: 2866 return true; 2867 default: 2868 return false; 2869 } 2870 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) { 2871 switch (keyType) { 2872 case TYPE_RSA: 2873 return true; 2874 case TYPE_DSA: 2875 return device->flags & KEYMASTER_SUPPORTS_DSA; 2876 case TYPE_EC: 2877 return device->flags & KEYMASTER_SUPPORTS_EC; 2878 default: 2879 return false; 2880 } 2881 } else { 2882 return keyType == TYPE_RSA; 2883 } 2884 } 2885 2886 /** 2887 * Check that all keymaster_key_param_t's provided by the application are 2888 * allowed. Any parameter that keystore adds itself should be disallowed here. 2889 */ 2890 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) { 2891 for (auto param: params) { 2892 switch (param.tag) { 2893 case KM_TAG_AUTH_TOKEN: 2894 return false; 2895 default: 2896 break; 2897 } 2898 } 2899 return true; 2900 } 2901 2902 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key, 2903 const keymaster1_device_t* dev, 2904 const std::vector<keymaster_key_param_t>& params, 2905 keymaster_key_characteristics_t* out) { 2906 UniquePtr<keymaster_blob_t> appId; 2907 UniquePtr<keymaster_blob_t> appData; 2908 for (auto param : params) { 2909 if (param.tag == KM_TAG_APPLICATION_ID) { 2910 appId.reset(new keymaster_blob_t); 2911 appId->data = param.blob.data; 2912 appId->data_length = param.blob.data_length; 2913 } else if (param.tag == KM_TAG_APPLICATION_DATA) { 2914 appData.reset(new keymaster_blob_t); 2915 appData->data = param.blob.data; 2916 appData->data_length = param.blob.data_length; 2917 } 2918 } 2919 keymaster_key_characteristics_t* result = NULL; 2920 if (!dev->get_key_characteristics) { 2921 return KM_ERROR_UNIMPLEMENTED; 2922 } 2923 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(), 2924 appData.get(), &result); 2925 if (result) { 2926 *out = *result; 2927 free(result); 2928 } 2929 return error; 2930 } 2931 2932 /** 2933 * Get the auth token for this operation from the auth token table. 2934 * 2935 * Returns ::NO_ERROR if the auth token was set or none was required. 2936 * ::OP_AUTH_NEEDED if it is a per op authorization, no 2937 * authorization token exists for that operation and 2938 * failOnTokenMissing is false. 2939 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth 2940 * token for the operation 2941 */ 2942 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics, 2943 keymaster_operation_handle_t handle, 2944 const hw_auth_token_t** authToken, 2945 bool failOnTokenMissing = true) { 2946 2947 std::vector<keymaster_key_param_t> allCharacteristics; 2948 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) { 2949 allCharacteristics.push_back(characteristics->sw_enforced.params[i]); 2950 } 2951 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) { 2952 allCharacteristics.push_back(characteristics->hw_enforced.params[i]); 2953 } 2954 keymaster::AuthTokenTable::Error err = 2955 mAuthTokenTable.FindAuthorization(allCharacteristics.data(), 2956 allCharacteristics.size(), handle, authToken); 2957 switch (err) { 2958 case keymaster::AuthTokenTable::OK: 2959 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED: 2960 return ::NO_ERROR; 2961 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND: 2962 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED: 2963 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID: 2964 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED; 2965 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED: 2966 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED : 2967 (int32_t) ::OP_AUTH_NEEDED; 2968 default: 2969 ALOGE("Unexpected FindAuthorization return value %d", err); 2970 return KM_ERROR_INVALID_ARGUMENT; 2971 } 2972 } 2973 2974 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params, 2975 const hw_auth_token_t* token) { 2976 if (token) { 2977 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN, 2978 reinterpret_cast<const uint8_t*>(token), 2979 sizeof(hw_auth_token_t))); 2980 } 2981 } 2982 2983 /** 2984 * Add the auth token for the operation to the param list if the operation 2985 * requires authorization. Uses the cached result in the OperationMap if available 2986 * otherwise gets the token from the AuthTokenTable and caches the result. 2987 * 2988 * Returns ::NO_ERROR if the auth token was added or not needed. 2989 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not 2990 * authenticated. 2991 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid 2992 * operation token. 2993 */ 2994 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token, 2995 std::vector<keymaster_key_param_t>* params) { 2996 const hw_auth_token_t* authToken = NULL; 2997 mOperationMap.getOperationAuthToken(token, &authToken); 2998 if (!authToken) { 2999 const keymaster1_device_t* dev; 3000 keymaster_operation_handle_t handle; 3001 const keymaster_key_characteristics_t* characteristics = NULL; 3002 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) { 3003 return KM_ERROR_INVALID_OPERATION_HANDLE; 3004 } 3005 int32_t result = getAuthToken(characteristics, handle, &authToken); 3006 if (result != ::NO_ERROR) { 3007 return result; 3008 } 3009 if (authToken) { 3010 mOperationMap.setOperationAuthToken(token, authToken); 3011 } 3012 } 3013 addAuthToParams(params, authToken); 3014 return ::NO_ERROR; 3015 } 3016 3017 ::KeyStore* mKeyStore; 3018 OperationMap mOperationMap; 3019 keymaster::AuthTokenTable mAuthTokenTable; 3020}; 3021 3022}; // namespace android 3023 3024int main(int argc, char* argv[]) { 3025 if (argc < 2) { 3026 ALOGE("A directory must be specified!"); 3027 return 1; 3028 } 3029 if (chdir(argv[1]) == -1) { 3030 ALOGE("chdir: %s: %s", argv[1], strerror(errno)); 3031 return 1; 3032 } 3033 3034 Entropy entropy; 3035 if (!entropy.open()) { 3036 return 1; 3037 } 3038 3039 keymaster0_device_t* dev; 3040 if (keymaster_device_initialize(&dev)) { 3041 ALOGE("keystore keymaster could not be initialized; exiting"); 3042 return 1; 3043 } 3044 3045 keymaster1_device_t* fallback; 3046 if (fallback_keymaster_device_initialize(&fallback)) { 3047 ALOGE("software keymaster could not be initialized; exiting"); 3048 return 1; 3049 } 3050 3051 ks_is_selinux_enabled = is_selinux_enabled(); 3052 if (ks_is_selinux_enabled) { 3053 union selinux_callback cb; 3054 cb.func_log = selinux_log_callback; 3055 selinux_set_callback(SELINUX_CB_LOG, cb); 3056 if (getcon(&tctx) != 0) { 3057 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n"); 3058 return -1; 3059 } 3060 } else { 3061 ALOGI("SELinux: Keystore SELinux is disabled.\n"); 3062 } 3063 3064 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback); 3065 keyStore.initialize(); 3066 android::sp<android::IServiceManager> sm = android::defaultServiceManager(); 3067 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore); 3068 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy); 3069 if (ret != android::OK) { 3070 ALOGE("Couldn't register binder service!"); 3071 return -1; 3072 } 3073 3074 /* 3075 * We're the only thread in existence, so we're just going to process 3076 * Binder transaction as a single-threaded program. 3077 */ 3078 android::IPCThreadState::self()->joinThreadPool(); 3079 3080 keymaster_device_release(dev); 3081 return 1; 3082} 3083