keystore.cpp 24.8 KB
Newer Older
1
/*
Shawn Willden's avatar
Shawn Willden committed
2
 * Copyright (C) 2016 The Android Open Source Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Shawn Willden's avatar
Shawn Willden committed
17
#include "keystore.h"
Kenny Root's avatar
Kenny Root committed
18

19 20
#include <dirent.h>
#include <fcntl.h>
21

Shawn Willden's avatar
Shawn Willden committed
22
#include <openssl/bio.h>
23

Shawn Willden's avatar
Shawn Willden committed
24
#include <utils/String16.h>
25

Kenny Root's avatar
Kenny Root committed
26
#include <keystore/IKeystoreService.h>
27

Shawn Willden's avatar
Shawn Willden committed
28 29
#include "keystore_utils.h"
#include "permissions.h"
30

Shawn Willden's avatar
Shawn Willden committed
31 32
const char* KeyStore::sOldMasterKey = ".masterkey";
const char* KeyStore::sMetaDataFile = ".metadata";
33

Shawn Willden's avatar
Shawn Willden committed
34 35
const android::String16 KeyStore::sRSAKeyType("RSA");
const android::String16 KeyStore::sECKeyType("EC");
36

Shawn Willden's avatar
Shawn Willden committed
37 38 39 40
KeyStore::KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
    : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) {
    memset(&mMetaData, '\0', sizeof(mMetaData));
}
41

Shawn Willden's avatar
Shawn Willden committed
42 43 44
KeyStore::~KeyStore() {
    for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
        delete *it;
45
    }
Shawn Willden's avatar
Shawn Willden committed
46
    mGrants.clear();
47

Shawn Willden's avatar
Shawn Willden committed
48 49 50
    for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
         it++) {
        delete *it;
51
    }
Shawn Willden's avatar
Shawn Willden committed
52 53
    mMasterKeys.clear();
}
54

Shawn Willden's avatar
Shawn Willden committed
55 56 57 58
ResponseCode KeyStore::initialize() {
    readMetaData();
    if (upgradeKeystore()) {
        writeMetaData();
59 60
    }

Shawn Willden's avatar
Shawn Willden committed
61 62
    return ::NO_ERROR;
}
63

Shawn Willden's avatar
Shawn Willden committed
64 65 66
ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
    UserState* userState = getUserState(userId);
    return userState->initialize(pw, mEntropy);
67 68
}

Shawn Willden's avatar
Shawn Willden committed
69 70 71 72 73
ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
    UserState* userState = getUserState(dstUser);
    UserState* initState = getUserState(srcUser);
    return userState->copyMasterKey(initState);
}
74

Shawn Willden's avatar
Shawn Willden committed
75 76 77 78
ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
    UserState* userState = getUserState(userId);
    return userState->writeMasterKey(pw, mEntropy);
}
79

Shawn Willden's avatar
Shawn Willden committed
80 81 82 83
ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
    UserState* userState = getUserState(userId);
    return userState->readMasterKey(pw, mEntropy);
}
84

Shawn Willden's avatar
Shawn Willden committed
85 86 87 88 89 90
/* Here is the encoding of keys. This is necessary in order to allow arbitrary
 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
 * into two bytes. The first byte is one of [+-.] which represents the first
 * two bits of the character. The second byte encodes the rest of the bits into
 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
 * that Base64 cannot be used here due to the need of prefix match on keys. */
91

Shawn Willden's avatar
Shawn Willden committed
92 93 94 95 96 97
static size_t encode_key_length(const android::String8& keyName) {
    const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
    size_t length = keyName.length();
    for (int i = length; i > 0; --i, ++in) {
        if (*in < '0' || *in > '~') {
            ++length;
98
        }
99
    }
Shawn Willden's avatar
Shawn Willden committed
100
    return length;
101 102
}

Shawn Willden's avatar
Shawn Willden committed
103 104 105 106 107 108 109 110 111 112 113
static int encode_key(char* out, const android::String8& keyName) {
    const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
    size_t length = keyName.length();
    for (int i = length; i > 0; --i, ++in, ++out) {
        if (*in < '0' || *in > '~') {
            *out = '+' + (*in >> 6);
            *++out = '0' + (*in & 0x3F);
            ++length;
        } else {
            *out = *in;
        }
114
    }
Shawn Willden's avatar
Shawn Willden committed
115 116
    *out = '\0';
    return length;
117 118
}

Shawn Willden's avatar
Shawn Willden committed
119 120 121 122
android::String8 KeyStore::getKeyName(const android::String8& keyName) {
    char encoded[encode_key_length(keyName) + 1];  // add 1 for null char
    encode_key(encoded, keyName);
    return android::String8(encoded);
123 124
}

Shawn Willden's avatar
Shawn Willden committed
125 126 127 128
android::String8 KeyStore::getKeyNameForUid(const android::String8& keyName, uid_t uid) {
    char encoded[encode_key_length(keyName) + 1];  // add 1 for null char
    encode_key(encoded, keyName);
    return android::String8::format("%u_%s", uid, encoded);
129 130
}

Shawn Willden's avatar
Shawn Willden committed
131 132 133 134 135
android::String8 KeyStore::getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
    char encoded[encode_key_length(keyName) + 1];  // add 1 for null char
    encode_key(encoded, keyName);
    return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
                                    encoded);
136 137
}

Shawn Willden's avatar
Shawn Willden committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
    android::String8 prefix("");
    android::Vector<android::String16> aliases;
    UserState* userState = getUserState(userId);
    if (list(prefix, &aliases, userId) != ::NO_ERROR) {
        return;
    }
    for (uint32_t i = 0; i < aliases.size(); i++) {
        android::String8 filename(aliases[i]);
        filename = android::String8::format("%s/%s", userState->getUserDirName(),
                                            getKeyName(filename).string());
        bool shouldDelete = true;
        if (keepUnenryptedEntries) {
            Blob blob;
            ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);

            /* get can fail if the blob is encrypted and the state is
             * not unlocked, only skip deleting blobs that were loaded and
             * who are not encrypted. If there are blobs we fail to read for
             * other reasons err on the safe side and delete them since we
             * can't tell if they're encrypted.
             */
            shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
        }
        if (shouldDelete) {
            del(filename, ::TYPE_ANY, userId);
        }
    }
    if (!userState->deleteMasterKey()) {
        ALOGE("Failed to delete user %d's master key", userId);
    }
    if (!keepUnenryptedEntries) {
        if (!userState->reset()) {
            ALOGE("Failed to remove user %d's directory", userId);
        }
173 174 175
    }
}

Shawn Willden's avatar
Shawn Willden committed
176 177 178 179
bool KeyStore::isEmpty(uid_t userId) const {
    const UserState* userState = getUserState(userId);
    if (userState == NULL) {
        return true;
180 181
    }

Shawn Willden's avatar
Shawn Willden committed
182 183
    DIR* dir = opendir(userState->getUserDirName());
    if (!dir) {
184 185 186
        return true;
    }

Shawn Willden's avatar
Shawn Willden committed
187 188 189 190 191 192 193
    bool result = true;
    struct dirent* file;
    while ((file = readdir(dir)) != NULL) {
        // We only care about files.
        if (file->d_type != DT_REG) {
            continue;
        }
194

Shawn Willden's avatar
Shawn Willden committed
195 196 197 198
        // Skip anything that starts with a "."
        if (file->d_name[0] == '.') {
            continue;
        }
199

Shawn Willden's avatar
Shawn Willden committed
200 201
        result = false;
        break;
202
    }
Shawn Willden's avatar
Shawn Willden committed
203 204 205
    closedir(dir);
    return result;
}
206

Shawn Willden's avatar
Shawn Willden committed
207 208 209 210
void KeyStore::lock(uid_t userId) {
    UserState* userState = getUserState(userId);
    userState->zeroizeMasterKeysInMemory();
    userState->setState(STATE_LOCKED);
211 212
}

Shawn Willden's avatar
Shawn Willden committed
213 214 215 216 217 218
ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
    UserState* userState = getUserState(userId);
    ResponseCode rc =
        keyBlob->readBlob(filename, userState->getDecryptionKey(), userState->getState());
    if (rc != NO_ERROR) {
        return rc;
Kenny Root's avatar
Kenny Root committed
219 220
    }

Shawn Willden's avatar
Shawn Willden committed
221 222 223 224 225 226 227 228 229 230 231 232
    const uint8_t version = keyBlob->getVersion();
    if (version < CURRENT_BLOB_VERSION) {
        /* If we upgrade the key, we need to write it to disk again. Then
         * it must be read it again since the blob is encrypted each time
         * it's written.
         */
        if (upgradeBlob(filename, keyBlob, version, type, userId)) {
            if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR ||
                (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                                        userState->getState())) != NO_ERROR) {
                return rc;
            }
Kenny Root's avatar
Kenny Root committed
233 234 235
        }
    }

Shawn Willden's avatar
Shawn Willden committed
236 237 238 239 240 241 242 243 244 245
    /*
     * This will upgrade software-backed keys to hardware-backed keys when
     * the HAL for the device supports the newer key types.
     */
    if (rc == NO_ERROR && type == TYPE_KEY_PAIR &&
        mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 &&
        keyBlob->isFallback()) {
        ResponseCode imported =
            importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
                      keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root's avatar
Kenny Root committed
246

Shawn Willden's avatar
Shawn Willden committed
247 248 249 250
        // The HAL allowed the import, reget the key to have the "fresh"
        // version.
        if (imported == NO_ERROR) {
            rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root's avatar
Kenny Root committed
251 252 253
        }
    }

Shawn Willden's avatar
Shawn Willden committed
254 255 256 257
    // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
    if (keyBlob->getType() == TYPE_KEY_PAIR) {
        keyBlob->setType(TYPE_KEYMASTER_10);
        rc = this->put(filename, keyBlob, userId);
258
    }
Shawn Willden's avatar
Shawn Willden committed
259 260 261 262

    if (type != TYPE_ANY && keyBlob->getType() != type) {
        ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
        return KEY_NOT_FOUND;
263 264
    }

Shawn Willden's avatar
Shawn Willden committed
265
    return rc;
266 267
}

Shawn Willden's avatar
Shawn Willden committed
268 269 270 271 272
ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
    UserState* userState = getUserState(userId);
    return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
                              mEntropy);
}
273

Shawn Willden's avatar
Shawn Willden committed
274 275 276 277 278 279 280 281 282
ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
    Blob keyBlob;
    ResponseCode rc = get(filename, &keyBlob, type, userId);
    if (rc == ::VALUE_CORRUPTED) {
        // The file is corrupt, the best we can do is rm it.
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
    }
    if (rc != ::NO_ERROR) {
        return rc;
Kenny Root's avatar
Kenny Root committed
283 284
    }

Shawn Willden's avatar
Shawn Willden committed
285 286 287 288 289 290 291 292
    if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
        // A device doesn't have to implement delete_key.
        if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
            keymaster_key_blob_t blob = {keyBlob.getValue(),
                                         static_cast<size_t>(keyBlob.getLength())};
            if (mDevice->delete_key(mDevice, &blob)) {
                rc = ::SYSTEM_ERROR;
            }
293 294
        }
    }
Shawn Willden's avatar
Shawn Willden committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308
    if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
        keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
        if (dev->delete_key) {
            keymaster_key_blob_t blob;
            blob.key_material = keyBlob.getValue();
            blob.key_material_size = keyBlob.getLength();
            dev->delete_key(dev, &blob);
        }
    }
    if (rc != ::NO_ERROR) {
        return rc;
    }

    return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
309 310
}

Kenny Root's avatar
Kenny Root committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
/*
 * Converts from the "escaped" format on disk to actual name.
 * This will be smaller than the input string.
 *
 * Characters that should combine with the next at the end will be truncated.
 */
static size_t decode_key_length(const char* in, size_t length) {
    size_t outLength = 0;

    for (const char* end = in + length; in < end; in++) {
        /* This combines with the next character. */
        if (*in < '0' || *in > '~') {
            continue;
        }

        outLength++;
    }
    return outLength;
}

static void decode_key(char* out, const char* in, size_t length) {
    for (const char* end = in + length; in < end; in++) {
        if (*in < '0' || *in > '~') {
            /* Truncate combining characters at the end. */
            if (in + 1 >= end) {
                break;
            }

            *out = (*in++ - '+') << 6;
            *out++ |= (*in - '0') & 0x3F;
341
        } else {
Kenny Root's avatar
Kenny Root committed
342
            *out++ = *in;
343 344 345 346 347
        }
    }
    *out = '\0';
}

Shawn Willden's avatar
Shawn Willden committed
348 349 350 351 352 353 354 355 356 357
ResponseCode KeyStore::list(const android::String8& prefix,
                            android::Vector<android::String16>* matches, uid_t userId) {

    UserState* userState = getUserState(userId);
    size_t n = prefix.length();

    DIR* dir = opendir(userState->getUserDirName());
    if (!dir) {
        ALOGW("can't open directory for user: %s", strerror(errno));
        return ::SYSTEM_ERROR;
358 359
    }

Shawn Willden's avatar
Shawn Willden committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    struct dirent* file;
    while ((file = readdir(dir)) != NULL) {
        // We only care about files.
        if (file->d_type != DT_REG) {
            continue;
        }

        // Skip anything that starts with a "."
        if (file->d_name[0] == '.') {
            continue;
        }

        if (!strncmp(prefix.string(), file->d_name, n)) {
            const char* p = &file->d_name[n];
            size_t plen = strlen(p);

            size_t extra = decode_key_length(p, plen);
            char* match = (char*)malloc(extra + 1);
            if (match != NULL) {
                decode_key(match, p, plen);
                matches->push(android::String16(match, extra));
                free(match);
            } else {
                ALOGW("could not allocate match of size %zd", extra);
            }
385 386
        }
    }
Shawn Willden's avatar
Shawn Willden committed
387 388
    closedir(dir);
    return ::NO_ERROR;
389 390
}

Shawn Willden's avatar
Shawn Willden committed
391 392 393 394 395 396 397
void KeyStore::addGrant(const char* filename, uid_t granteeUid) {
    const grant_t* existing = getGrant(filename, granteeUid);
    if (existing == NULL) {
        grant_t* grant = new grant_t;
        grant->uid = granteeUid;
        grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
        mGrants.add(grant);
398
    }
Shawn Willden's avatar
Shawn Willden committed
399
}
400

Shawn Willden's avatar
Shawn Willden committed
401 402 403 404 405 406 407
bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
    for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
        grant_t* grant = *it;
        if (grant->uid == granteeUid &&
            !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
            mGrants.erase(it);
            return true;
408 409
        }
    }
Shawn Willden's avatar
Shawn Willden committed
410 411
    return false;
}
412

Shawn Willden's avatar
Shawn Willden committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
                                 uid_t userId, int32_t flags) {
    Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
    if (!pkcs8.get()) {
        return ::SYSTEM_ERROR;
    }
    Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
    if (!pkey.get()) {
        return ::SYSTEM_ERROR;
    }
    int type = EVP_PKEY_type(pkey->type);
    android::KeymasterArguments params;
    add_legacy_key_authorizations(type, &params.params);
    switch (type) {
    case EVP_PKEY_RSA:
        params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
        break;
    case EVP_PKEY_EC:
        params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
        break;
    default:
        ALOGW("Unsupported key type %d", type);
        return ::SYSTEM_ERROR;
436 437
    }

Shawn Willden's avatar
Shawn Willden committed
438 439 440 441 442 443 444 445 446
    std::vector<keymaster_key_param_t> opParams(params.params);
    const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
    keymaster_blob_t input = {key, keyLen};
    keymaster_key_blob_t blob = {nullptr, 0};
    bool isFallback = false;
    keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input,
                                                  &blob, NULL /* characteristics */);
    if (error != KM_ERROR_OK) {
        ALOGE("Keymaster error %d importing key pair, falling back", error);
447

Shawn Willden's avatar
Shawn Willden committed
448 449 450 451 452 453 454 455 456
        /*
         * There should be no way to get here.  Fallback shouldn't ever really happen
         * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
         * provide full support of the API.  In any case, we'll do the fallback just for
         * consistency... and I suppose to cover for broken HW implementations.
         */
        error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input,
                                            &blob, NULL /* characteristics */);
        isFallback = true;
457

Shawn Willden's avatar
Shawn Willden committed
458 459 460
        if (error) {
            ALOGE("Keymaster error while importing key pair with fallback: %d", error);
            return SYSTEM_ERROR;
461
        }
Shawn Willden's avatar
Shawn Willden committed
462
    }
463

Shawn Willden's avatar
Shawn Willden committed
464 465
    Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
    free(const_cast<uint8_t*>(blob.key_material));
466

Shawn Willden's avatar
Shawn Willden committed
467 468
    keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
    keyBlob.setFallback(isFallback);
469

Shawn Willden's avatar
Shawn Willden committed
470 471
    return put(filename, &keyBlob, userId);
}
472

Shawn Willden's avatar
Shawn Willden committed
473 474 475 476
bool KeyStore::isHardwareBacked(const android::String16& keyType) const {
    if (mDevice == NULL) {
        ALOGW("can't get keymaster device");
        return false;
477 478
    }

Shawn Willden's avatar
Shawn Willden committed
479 480 481 482 483
    if (sRSAKeyType == keyType) {
        return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
    } else {
        return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 &&
               (mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2);
484
    }
Shawn Willden's avatar
Shawn Willden committed
485
}
486

Shawn Willden's avatar
Shawn Willden committed
487 488 489 490
ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
                                     const uid_t uid, const BlobType type) {
    android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
    uid_t userId = get_user_id(uid);
491

Shawn Willden's avatar
Shawn Willden committed
492 493 494
    ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
    if (responseCode == NO_ERROR) {
        return responseCode;
495 496
    }

Shawn Willden's avatar
Shawn Willden committed
497 498 499 500 501 502 503 504
    // If this is one of the legacy UID->UID mappings, use it.
    uid_t euid = get_keystore_euid(uid);
    if (euid != uid) {
        filepath8 = getKeyNameForUidWithDir(keyName, euid);
        responseCode = get(filepath8.string(), keyBlob, type, userId);
        if (responseCode == NO_ERROR) {
            return responseCode;
        }
Kenny Root's avatar
Kenny Root committed
505 506
    }

Shawn Willden's avatar
Shawn Willden committed
507 508 509 510 511 512
    // They might be using a granted key.
    android::String8 filename8 = getKeyName(keyName);
    char* end;
    strtoul(filename8.string(), &end, 10);
    if (end[0] != '_' || end[1] == 0) {
        return KEY_NOT_FOUND;
513
    }
Shawn Willden's avatar
Shawn Willden committed
514 515 516 517
    filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
                                         filename8.string());
    if (!hasGrant(filepath8.string(), uid)) {
        return responseCode;
518 519
    }

Shawn Willden's avatar
Shawn Willden committed
520 521 522
    // It is a granted key. Try to load it.
    return get(filepath8.string(), keyBlob, type, userId);
}
523

Shawn Willden's avatar
Shawn Willden committed
524 525 526 527 528 529
UserState* KeyStore::getUserState(uid_t userId) {
    for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
         it++) {
        UserState* state = *it;
        if (state->getUserId() == userId) {
            return state;
530 531 532
        }
    }

Shawn Willden's avatar
Shawn Willden committed
533 534 535 536 537 538 539
    UserState* userState = new UserState(userId);
    if (!userState->initialize()) {
        /* There's not much we can do if initialization fails. Trying to
         * unlock the keystore for that user will fail as well, so any
         * subsequent request for this user will just return SYSTEM_ERROR.
         */
        ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
540
    }
Shawn Willden's avatar
Shawn Willden committed
541 542 543
    mMasterKeys.add(userState);
    return userState;
}
544

Shawn Willden's avatar
Shawn Willden committed
545 546 547 548 549 550 551 552 553 554 555
UserState* KeyStore::getUserStateByUid(uid_t uid) {
    uid_t userId = get_user_id(uid);
    return getUserState(userId);
}

const UserState* KeyStore::getUserState(uid_t userId) const {
    for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
         it != mMasterKeys.end(); it++) {
        UserState* state = *it;
        if (state->getUserId() == userId) {
            return state;
556 557 558
        }
    }

Shawn Willden's avatar
Shawn Willden committed
559 560
    return NULL;
}
561

Shawn Willden's avatar
Shawn Willden committed
562 563 564 565
const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
    uid_t userId = get_user_id(uid);
    return getUserState(userId);
}
566

Shawn Willden's avatar
Shawn Willden committed
567 568 569 570 571 572 573
const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const {
    for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) {
        grant_t* grant = *it;
        if (grant->uid == uid &&
            !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
            return grant;
        }
574
    }
Shawn Willden's avatar
Shawn Willden committed
575 576
    return NULL;
}
577

Shawn Willden's avatar
Shawn Willden committed
578 579 580 581
bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
                           const BlobType type, uid_t uid) {
    bool updated = false;
    uint8_t version = oldVersion;
582

Shawn Willden's avatar
Shawn Willden committed
583 584 585
    /* From V0 -> V1: All old types were unknown */
    if (version == 0) {
        ALOGV("upgrading to version 1 and setting type %d", type);
586

Shawn Willden's avatar
Shawn Willden committed
587 588 589
        blob->setType(type);
        if (type == TYPE_KEY_PAIR) {
            importBlobAsKey(blob, filename, uid);
590
        }
Shawn Willden's avatar
Shawn Willden committed
591 592 593
        version = 1;
        updated = true;
    }
594

Shawn Willden's avatar
Shawn Willden committed
595 596 597
    /* From V1 -> V2: All old keys were encrypted */
    if (version == 1) {
        ALOGV("upgrading to version 2");
598

Shawn Willden's avatar
Shawn Willden committed
599 600 601
        blob->setEncrypted(true);
        version = 2;
        updated = true;
602 603
    }

Shawn Willden's avatar
Shawn Willden committed
604 605 606 607 608 609 610 611
    /*
     * If we've updated, set the key blob to the right version
     * and write it.
     */
    if (updated) {
        ALOGV("updated and writing file %s", filename);
        blob->setVersion(version);
    }
612

Shawn Willden's avatar
Shawn Willden committed
613 614
    return updated;
}
615

Shawn Willden's avatar
Shawn Willden committed
616 617 618 619
struct BIO_Delete {
    void operator()(BIO* p) const { BIO_free(p); }
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
620

Shawn Willden's avatar
Shawn Willden committed
621 622 623 624 625 626 627
ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
    // We won't even write to the blob directly with this BIO, so const_cast is okay.
    Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
    if (b.get() == NULL) {
        ALOGE("Problem instantiating BIO");
        return SYSTEM_ERROR;
    }
628

Shawn Willden's avatar
Shawn Willden committed
629 630 631 632
    Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
    if (pkey.get() == NULL) {
        ALOGE("Couldn't read old PEM file");
        return SYSTEM_ERROR;
633 634
    }

Shawn Willden's avatar
Shawn Willden committed
635 636 637 638 639
    Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
    int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
    if (len < 0) {
        ALOGE("Couldn't measure PKCS#8 length");
        return SYSTEM_ERROR;
640 641
    }

Shawn Willden's avatar
Shawn Willden committed
642 643 644 645 646
    UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
    uint8_t* tmp = pkcs8key.get();
    if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
        ALOGE("Couldn't convert to PKCS#8");
        return SYSTEM_ERROR;
647 648
    }

Shawn Willden's avatar
Shawn Willden committed
649 650 651 652
    ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
                                blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
    if (rc != NO_ERROR) {
        return rc;
653 654
    }

Shawn Willden's avatar
Shawn Willden committed
655 656
    return get(filename, blob, TYPE_KEY_PAIR, uid);
}
657

Shawn Willden's avatar
Shawn Willden committed
658 659 660 661
void KeyStore::readMetaData() {
    int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
    if (in < 0) {
        return;
662
    }
Shawn Willden's avatar
Shawn Willden committed
663 664 665
    size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
    if (fileLength != sizeof(mMetaData)) {
        ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
666
    }
Shawn Willden's avatar
Shawn Willden committed
667 668
    close(in);
}
669

Shawn Willden's avatar
Shawn Willden committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
void KeyStore::writeMetaData() {
    const char* tmpFileName = ".metadata.tmp";
    int out =
        TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
    if (out < 0) {
        ALOGE("couldn't write metadata file: %s", strerror(errno));
        return;
    }
    size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
    if (fileLength != sizeof(mMetaData)) {
        ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
              sizeof(mMetaData));
    }
    close(out);
    rename(tmpFileName, sMetaDataFile);
}
686

Shawn Willden's avatar
Shawn Willden committed
687 688
bool KeyStore::upgradeKeystore() {
    bool upgraded = false;
689

Shawn Willden's avatar
Shawn Willden committed
690 691
    if (mMetaData.version == 0) {
        UserState* userState = getUserStateByUid(0);
692

Shawn Willden's avatar
Shawn Willden committed
693 694
        // Initialize first so the directory is made.
        userState->initialize();
695

Shawn Willden's avatar
Shawn Willden committed
696 697 698 699 700
        // Migrate the old .masterkey file to user 0.
        if (access(sOldMasterKey, R_OK) == 0) {
            if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
                ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
                return false;
701 702 703
            }
        }

Shawn Willden's avatar
Shawn Willden committed
704 705
        // Initialize again in case we had a key.
        userState->initialize();
706

Shawn Willden's avatar
Shawn Willden committed
707 708
        // Try to migrate existing keys.
        DIR* dir = opendir(".");
709
        if (!dir) {
Shawn Willden's avatar
Shawn Willden committed
710 711
            // Give up now; maybe we can upgrade later.
            ALOGE("couldn't open keystore's directory; something is wrong");
Kenny Root's avatar
Kenny Root committed
712 713 714
            return false;
        }

715
        struct dirent* file;
716
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
717 718 719 720 721 722 723 724 725 726
            // We only care about files.
            if (file->d_type != DT_REG) {
                continue;
            }

            // Skip anything that starts with a "."
            if (file->d_name[0] == '.') {
                continue;
            }

Shawn Willden's avatar
Shawn Willden committed
727 728 729 730
            // Find the current file's user.
            char* end;
            unsigned long thisUid = strtoul(file->d_name, &end, 10);
            if (end[0] != '_' || end[1] == 0) {
731 732
                continue;
            }
Shawn Willden's avatar
Shawn Willden committed
733 734 735 736
            UserState* otherUser = getUserStateByUid(thisUid);
            if (otherUser->getUserId() != 0) {
                unlinkat(dirfd(dir), file->d_name, 0);
            }
737

Shawn Willden's avatar
Shawn Willden committed
738 739 740 741
            // Rename the file into user directory.
            DIR* otherdir = opendir(otherUser->getUserDirName());
            if (otherdir == NULL) {
                ALOGW("couldn't open user directory for rename");
742 743
                continue;
            }
Shawn Willden's avatar
Shawn Willden committed
744 745
            if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
                ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
746
            }
Shawn Willden's avatar
Shawn Willden committed
747
            closedir(otherdir);
748 749
        }
        closedir(dir);
750

Shawn Willden's avatar
Shawn Willden committed
751 752
        mMetaData.version = 1;
        upgraded = true;
753 754
    }

Shawn Willden's avatar
Shawn Willden committed
755
    return upgraded;
756
}