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