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