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