1/* 2 * Copyright (C) 2016 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#include "keystore.h" 18 19#include <dirent.h> 20#include <fcntl.h> 21 22#include <openssl/bio.h> 23 24#include <utils/String16.h> 25 26#include <keystore/IKeystoreService.h> 27 28#include "keystore_utils.h" 29#include "permissions.h" 30 31const char* KeyStore::sOldMasterKey = ".masterkey"; 32const char* KeyStore::sMetaDataFile = ".metadata"; 33 34const android::String16 KeyStore::sRSAKeyType("RSA"); 35 36KeyStore::KeyStore(Entropy* entropy, keymaster2_device_t* device, keymaster2_device_t* fallback) 37 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) { 38 memset(&mMetaData, '\0', sizeof(mMetaData)); 39} 40 41KeyStore::~KeyStore() { 42 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) { 43 delete *it; 44 } 45 mGrants.clear(); 46 47 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end(); 48 it++) { 49 delete *it; 50 } 51 mMasterKeys.clear(); 52} 53 54ResponseCode KeyStore::initialize() { 55 readMetaData(); 56 if (upgradeKeystore()) { 57 writeMetaData(); 58 } 59 60 return ::NO_ERROR; 61} 62 63ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) { 64 UserState* userState = getUserState(userId); 65 return userState->initialize(pw, mEntropy); 66} 67 68ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) { 69 UserState* userState = getUserState(dstUser); 70 UserState* initState = getUserState(srcUser); 71 return userState->copyMasterKey(initState); 72} 73 74ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) { 75 UserState* userState = getUserState(userId); 76 return userState->writeMasterKey(pw, mEntropy); 77} 78 79ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) { 80 UserState* userState = getUserState(userId); 81 return userState->readMasterKey(pw, mEntropy); 82} 83 84/* Here is the encoding of keys. This is necessary in order to allow arbitrary 85 * characters in keys. Characters in [0-~] are not encoded. Others are encoded 86 * into two bytes. The first byte is one of [+-.] which represents the first 87 * two bits of the character. The second byte encodes the rest of the bits into 88 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note 89 * that Base64 cannot be used here due to the need of prefix match on keys. */ 90 91static size_t encode_key_length(const android::String8& keyName) { 92 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string()); 93 size_t length = keyName.length(); 94 for (int i = length; i > 0; --i, ++in) { 95 if (*in < '0' || *in > '~') { 96 ++length; 97 } 98 } 99 return length; 100} 101 102static int encode_key(char* out, const android::String8& keyName) { 103 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string()); 104 size_t length = keyName.length(); 105 for (int i = length; i > 0; --i, ++in, ++out) { 106 if (*in < '0' || *in > '~') { 107 *out = '+' + (*in >> 6); 108 *++out = '0' + (*in & 0x3F); 109 ++length; 110 } else { 111 *out = *in; 112 } 113 } 114 *out = '\0'; 115 return length; 116} 117 118android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) { 119 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 120 encode_key(encoded, keyName); 121 if (type == TYPE_KEY_CHARACTERISTICS) { 122 return android::String8::format(".chr_%s", encoded); 123 } else { 124 return android::String8(encoded); 125 } 126} 127 128android::String8 KeyStore::getKeyNameForUid( 129 const android::String8& keyName, uid_t uid, const BlobType type) { 130 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 131 encode_key(encoded, keyName); 132 if (type == TYPE_KEY_CHARACTERISTICS) { 133 return android::String8::format(".%u_chr_%s", uid, encoded); 134 } else { 135 return android::String8::format("%u_%s", uid, encoded); 136 } 137} 138 139android::String8 KeyStore::getKeyNameForUidWithDir( 140 const android::String8& keyName, uid_t uid, const BlobType type) { 141 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char 142 encode_key(encoded, keyName); 143 144 if (type == TYPE_KEY_CHARACTERISTICS) { 145 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(), 146 uid, encoded); 147 } else { 148 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid, 149 encoded); 150 } 151} 152 153void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) { 154 android::String8 prefix(""); 155 android::Vector<android::String16> aliases; 156 UserState* userState = getUserState(userId); 157 if (list(prefix, &aliases, userId) != ::NO_ERROR) { 158 return; 159 } 160 for (uint32_t i = 0; i < aliases.size(); i++) { 161 android::String8 filename(aliases[i]); 162 filename = android::String8::format("%s/%s", userState->getUserDirName(), 163 getKeyName(filename, TYPE_ANY).string()); 164 bool shouldDelete = true; 165 if (keepUnenryptedEntries) { 166 Blob blob; 167 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId); 168 169 /* get can fail if the blob is encrypted and the state is 170 * not unlocked, only skip deleting blobs that were loaded and 171 * who are not encrypted. If there are blobs we fail to read for 172 * other reasons err on the safe side and delete them since we 173 * can't tell if they're encrypted. 174 */ 175 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted()); 176 } 177 if (shouldDelete) { 178 del(filename, ::TYPE_ANY, userId); 179 180 // del() will fail silently if no cached characteristics are present for this alias. 181 android::String8 chr_filename(aliases[i]); 182 chr_filename = android::String8::format("%s/%s", userState->getUserDirName(), 183 getKeyName(chr_filename, 184 TYPE_KEY_CHARACTERISTICS).string()); 185 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId); 186 } 187 } 188 if (!userState->deleteMasterKey()) { 189 ALOGE("Failed to delete user %d's master key", userId); 190 } 191 if (!keepUnenryptedEntries) { 192 if (!userState->reset()) { 193 ALOGE("Failed to remove user %d's directory", userId); 194 } 195 } 196} 197 198bool KeyStore::isEmpty(uid_t userId) const { 199 const UserState* userState = getUserState(userId); 200 if (userState == NULL) { 201 return true; 202 } 203 204 DIR* dir = opendir(userState->getUserDirName()); 205 if (!dir) { 206 return true; 207 } 208 209 bool result = true; 210 struct dirent* file; 211 while ((file = readdir(dir)) != NULL) { 212 // We only care about files. 213 if (file->d_type != DT_REG) { 214 continue; 215 } 216 217 // Skip anything that starts with a "." 218 if (file->d_name[0] == '.') { 219 continue; 220 } 221 222 result = false; 223 break; 224 } 225 closedir(dir); 226 return result; 227} 228 229void KeyStore::lock(uid_t userId) { 230 UserState* userState = getUserState(userId); 231 userState->zeroizeMasterKeysInMemory(); 232 userState->setState(STATE_LOCKED); 233} 234 235ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) { 236 UserState* userState = getUserState(userId); 237 ResponseCode rc = 238 keyBlob->readBlob(filename, userState->getDecryptionKey(), userState->getState()); 239 if (rc != NO_ERROR) { 240 return rc; 241 } 242 243 const uint8_t version = keyBlob->getVersion(); 244 if (version < CURRENT_BLOB_VERSION) { 245 /* If we upgrade the key, we need to write it to disk again. Then 246 * it must be read it again since the blob is encrypted each time 247 * it's written. 248 */ 249 if (upgradeBlob(filename, keyBlob, version, type, userId)) { 250 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR || 251 (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(), 252 userState->getState())) != NO_ERROR) { 253 return rc; 254 } 255 } 256 } 257 258 /* 259 * This will upgrade software-backed keys to hardware-backed keys when 260 * the HAL for the device supports the newer key types. 261 */ 262 if (rc == NO_ERROR && type == TYPE_KEY_PAIR && 263 mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 && 264 keyBlob->isFallback()) { 265 ResponseCode imported = 266 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId, 267 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); 268 269 // The HAL allowed the import, reget the key to have the "fresh" 270 // version. 271 if (imported == NO_ERROR) { 272 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId); 273 } 274 } 275 276 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade. 277 if (keyBlob->getType() == TYPE_KEY_PAIR) { 278 keyBlob->setType(TYPE_KEYMASTER_10); 279 rc = this->put(filename, keyBlob, userId); 280 } 281 282 if (type != TYPE_ANY && keyBlob->getType() != type) { 283 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type); 284 return KEY_NOT_FOUND; 285 } 286 287 return rc; 288} 289 290ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) { 291 UserState* userState = getUserState(userId); 292 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(), 293 mEntropy); 294} 295 296ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) { 297 Blob keyBlob; 298 ResponseCode rc = get(filename, &keyBlob, type, userId); 299 if (rc == ::VALUE_CORRUPTED) { 300 // The file is corrupt, the best we can do is rm it. 301 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR; 302 } 303 if (rc != ::NO_ERROR) { 304 return rc; 305 } 306 307 if (keyBlob.getType() == ::TYPE_KEY_PAIR) { 308 // A device doesn't have to implement delete_key. 309 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) { 310 keymaster_key_blob_t blob = {keyBlob.getValue(), 311 static_cast<size_t>(keyBlob.getLength())}; 312 if (mDevice->delete_key(mDevice, &blob)) { 313 rc = ::SYSTEM_ERROR; 314 } 315 } 316 } 317 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) { 318 auto* dev = getDeviceForBlob(keyBlob); 319 if (dev->delete_key) { 320 keymaster_key_blob_t blob; 321 blob.key_material = keyBlob.getValue(); 322 blob.key_material_size = keyBlob.getLength(); 323 dev->delete_key(dev, &blob); 324 } 325 } 326 if (rc != ::NO_ERROR) { 327 return rc; 328 } 329 330 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR; 331} 332 333/* 334 * Converts from the "escaped" format on disk to actual name. 335 * This will be smaller than the input string. 336 * 337 * Characters that should combine with the next at the end will be truncated. 338 */ 339static size_t decode_key_length(const char* in, size_t length) { 340 size_t outLength = 0; 341 342 for (const char* end = in + length; in < end; in++) { 343 /* This combines with the next character. */ 344 if (*in < '0' || *in > '~') { 345 continue; 346 } 347 348 outLength++; 349 } 350 return outLength; 351} 352 353static void decode_key(char* out, const char* in, size_t length) { 354 for (const char* end = in + length; in < end; in++) { 355 if (*in < '0' || *in > '~') { 356 /* Truncate combining characters at the end. */ 357 if (in + 1 >= end) { 358 break; 359 } 360 361 *out = (*in++ - '+') << 6; 362 *out++ |= (*in - '0') & 0x3F; 363 } else { 364 *out++ = *in; 365 } 366 } 367 *out = '\0'; 368} 369 370ResponseCode KeyStore::list(const android::String8& prefix, 371 android::Vector<android::String16>* matches, uid_t userId) { 372 373 UserState* userState = getUserState(userId); 374 size_t n = prefix.length(); 375 376 DIR* dir = opendir(userState->getUserDirName()); 377 if (!dir) { 378 ALOGW("can't open directory for user: %s", strerror(errno)); 379 return ::SYSTEM_ERROR; 380 } 381 382 struct dirent* file; 383 while ((file = readdir(dir)) != NULL) { 384 // We only care about files. 385 if (file->d_type != DT_REG) { 386 continue; 387 } 388 389 // Skip anything that starts with a "." 390 if (file->d_name[0] == '.') { 391 continue; 392 } 393 394 if (!strncmp(prefix.string(), file->d_name, n)) { 395 const char* p = &file->d_name[n]; 396 size_t plen = strlen(p); 397 398 size_t extra = decode_key_length(p, plen); 399 char* match = (char*)malloc(extra + 1); 400 if (match != NULL) { 401 decode_key(match, p, plen); 402 matches->push(android::String16(match, extra)); 403 free(match); 404 } else { 405 ALOGW("could not allocate match of size %zd", extra); 406 } 407 } 408 } 409 closedir(dir); 410 return ::NO_ERROR; 411} 412 413void KeyStore::addGrant(const char* filename, uid_t granteeUid) { 414 const grant_t* existing = getGrant(filename, granteeUid); 415 if (existing == NULL) { 416 grant_t* grant = new grant_t; 417 grant->uid = granteeUid; 418 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename)); 419 mGrants.add(grant); 420 } 421} 422 423bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) { 424 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) { 425 grant_t* grant = *it; 426 if (grant->uid == granteeUid && 427 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) { 428 mGrants.erase(it); 429 return true; 430 } 431 } 432 return false; 433} 434 435ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename, 436 uid_t userId, int32_t flags) { 437 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen)); 438 if (!pkcs8.get()) { 439 return ::SYSTEM_ERROR; 440 } 441 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get())); 442 if (!pkey.get()) { 443 return ::SYSTEM_ERROR; 444 } 445 int type = EVP_PKEY_type(pkey->type); 446 android::KeymasterArguments params; 447 add_legacy_key_authorizations(type, ¶ms.params); 448 switch (type) { 449 case EVP_PKEY_RSA: 450 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA)); 451 break; 452 case EVP_PKEY_EC: 453 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC)); 454 break; 455 default: 456 ALOGW("Unsupported key type %d", type); 457 return ::SYSTEM_ERROR; 458 } 459 460 std::vector<keymaster_key_param_t> opParams(params.params); 461 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()}; 462 keymaster_blob_t input = {key, keyLen}; 463 keymaster_key_blob_t blob = {nullptr, 0}; 464 bool isFallback = false; 465 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input, 466 &blob, NULL /* characteristics */); 467 if (error != KM_ERROR_OK) { 468 ALOGE("Keymaster error %d importing key pair, falling back", error); 469 470 /* 471 * There should be no way to get here. Fallback shouldn't ever really happen 472 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must 473 * provide full support of the API. In any case, we'll do the fallback just for 474 * consistency... and I suppose to cover for broken HW implementations. 475 */ 476 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input, 477 &blob, NULL /* characteristics */); 478 isFallback = true; 479 480 if (error) { 481 ALOGE("Keymaster error while importing key pair with fallback: %d", error); 482 return SYSTEM_ERROR; 483 } 484 } 485 486 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10); 487 free(const_cast<uint8_t*>(blob.key_material)); 488 489 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED); 490 keyBlob.setFallback(isFallback); 491 492 return put(filename, &keyBlob, userId); 493} 494 495bool KeyStore::isHardwareBacked(const android::String16& keyType) const { 496 if (mDevice == NULL) { 497 ALOGW("can't get keymaster device"); 498 return false; 499 } 500 501 if (sRSAKeyType == keyType) { 502 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0; 503 } else { 504 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 && 505 (mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2); 506 } 507} 508 509ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName, 510 const uid_t uid, const BlobType type) { 511 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type)); 512 uid_t userId = get_user_id(uid); 513 514 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId); 515 if (responseCode == NO_ERROR) { 516 return responseCode; 517 } 518 519 // If this is one of the legacy UID->UID mappings, use it. 520 uid_t euid = get_keystore_euid(uid); 521 if (euid != uid) { 522 filepath8 = getKeyNameForUidWithDir(keyName, euid, type); 523 responseCode = get(filepath8.string(), keyBlob, type, userId); 524 if (responseCode == NO_ERROR) { 525 return responseCode; 526 } 527 } 528 529 // They might be using a granted key. 530 android::String8 filename8 = getKeyName(keyName, type); 531 char* end; 532 strtoul(filename8.string(), &end, 10); 533 if (end[0] != '_' || end[1] == 0) { 534 return KEY_NOT_FOUND; 535 } 536 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(), 537 filename8.string()); 538 if (!hasGrant(filepath8.string(), uid)) { 539 return responseCode; 540 } 541 542 // It is a granted key. Try to load it. 543 return get(filepath8.string(), keyBlob, type, userId); 544} 545 546UserState* KeyStore::getUserState(uid_t userId) { 547 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end(); 548 it++) { 549 UserState* state = *it; 550 if (state->getUserId() == userId) { 551 return state; 552 } 553 } 554 555 UserState* userState = new UserState(userId); 556 if (!userState->initialize()) { 557 /* There's not much we can do if initialization fails. Trying to 558 * unlock the keystore for that user will fail as well, so any 559 * subsequent request for this user will just return SYSTEM_ERROR. 560 */ 561 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId); 562 } 563 mMasterKeys.add(userState); 564 return userState; 565} 566 567UserState* KeyStore::getUserStateByUid(uid_t uid) { 568 uid_t userId = get_user_id(uid); 569 return getUserState(userId); 570} 571 572const UserState* KeyStore::getUserState(uid_t userId) const { 573 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin()); 574 it != mMasterKeys.end(); it++) { 575 UserState* state = *it; 576 if (state->getUserId() == userId) { 577 return state; 578 } 579 } 580 581 return NULL; 582} 583 584const UserState* KeyStore::getUserStateByUid(uid_t uid) const { 585 uid_t userId = get_user_id(uid); 586 return getUserState(userId); 587} 588 589const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const { 590 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) { 591 grant_t* grant = *it; 592 if (grant->uid == uid && 593 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) { 594 return grant; 595 } 596 } 597 return NULL; 598} 599 600bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion, 601 const BlobType type, uid_t uid) { 602 bool updated = false; 603 uint8_t version = oldVersion; 604 605 /* From V0 -> V1: All old types were unknown */ 606 if (version == 0) { 607 ALOGV("upgrading to version 1 and setting type %d", type); 608 609 blob->setType(type); 610 if (type == TYPE_KEY_PAIR) { 611 importBlobAsKey(blob, filename, uid); 612 } 613 version = 1; 614 updated = true; 615 } 616 617 /* From V1 -> V2: All old keys were encrypted */ 618 if (version == 1) { 619 ALOGV("upgrading to version 2"); 620 621 blob->setEncrypted(true); 622 version = 2; 623 updated = true; 624 } 625 626 /* 627 * If we've updated, set the key blob to the right version 628 * and write it. 629 */ 630 if (updated) { 631 ALOGV("updated and writing file %s", filename); 632 blob->setVersion(version); 633 } 634 635 return updated; 636} 637 638struct BIO_Delete { 639 void operator()(BIO* p) const { BIO_free(p); } 640}; 641typedef UniquePtr<BIO, BIO_Delete> Unique_BIO; 642 643ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) { 644 // We won't even write to the blob directly with this BIO, so const_cast is okay. 645 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength())); 646 if (b.get() == NULL) { 647 ALOGE("Problem instantiating BIO"); 648 return SYSTEM_ERROR; 649 } 650 651 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL)); 652 if (pkey.get() == NULL) { 653 ALOGE("Couldn't read old PEM file"); 654 return SYSTEM_ERROR; 655 } 656 657 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get())); 658 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL); 659 if (len < 0) { 660 ALOGE("Couldn't measure PKCS#8 length"); 661 return SYSTEM_ERROR; 662 } 663 664 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]); 665 uint8_t* tmp = pkcs8key.get(); 666 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) { 667 ALOGE("Couldn't convert to PKCS#8"); 668 return SYSTEM_ERROR; 669 } 670 671 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid), 672 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE); 673 if (rc != NO_ERROR) { 674 return rc; 675 } 676 677 return get(filename, blob, TYPE_KEY_PAIR, uid); 678} 679 680void KeyStore::readMetaData() { 681 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY)); 682 if (in < 0) { 683 return; 684 } 685 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData)); 686 if (fileLength != sizeof(mMetaData)) { 687 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData)); 688 } 689 close(in); 690} 691 692void KeyStore::writeMetaData() { 693 const char* tmpFileName = ".metadata.tmp"; 694 int out = 695 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)); 696 if (out < 0) { 697 ALOGE("couldn't write metadata file: %s", strerror(errno)); 698 return; 699 } 700 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData)); 701 if (fileLength != sizeof(mMetaData)) { 702 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength, 703 sizeof(mMetaData)); 704 } 705 close(out); 706 rename(tmpFileName, sMetaDataFile); 707} 708 709bool KeyStore::upgradeKeystore() { 710 bool upgraded = false; 711 712 if (mMetaData.version == 0) { 713 UserState* userState = getUserStateByUid(0); 714 715 // Initialize first so the directory is made. 716 userState->initialize(); 717 718 // Migrate the old .masterkey file to user 0. 719 if (access(sOldMasterKey, R_OK) == 0) { 720 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) { 721 ALOGE("couldn't migrate old masterkey: %s", strerror(errno)); 722 return false; 723 } 724 } 725 726 // Initialize again in case we had a key. 727 userState->initialize(); 728 729 // Try to migrate existing keys. 730 DIR* dir = opendir("."); 731 if (!dir) { 732 // Give up now; maybe we can upgrade later. 733 ALOGE("couldn't open keystore's directory; something is wrong"); 734 return false; 735 } 736 737 struct dirent* file; 738 while ((file = readdir(dir)) != NULL) { 739 // We only care about files. 740 if (file->d_type != DT_REG) { 741 continue; 742 } 743 744 // Skip anything that starts with a "." 745 if (file->d_name[0] == '.') { 746 continue; 747 } 748 749 // Find the current file's user. 750 char* end; 751 unsigned long thisUid = strtoul(file->d_name, &end, 10); 752 if (end[0] != '_' || end[1] == 0) { 753 continue; 754 } 755 UserState* otherUser = getUserStateByUid(thisUid); 756 if (otherUser->getUserId() != 0) { 757 unlinkat(dirfd(dir), file->d_name, 0); 758 } 759 760 // Rename the file into user directory. 761 DIR* otherdir = opendir(otherUser->getUserDirName()); 762 if (otherdir == NULL) { 763 ALOGW("couldn't open user directory for rename"); 764 continue; 765 } 766 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) { 767 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno)); 768 } 769 closedir(otherdir); 770 } 771 closedir(dir); 772 773 mMetaData.version = 1; 774 upgraded = true; 775 } 776 777 return upgraded; 778} 779