keystore.cpp 68.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * 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.
 */

Kenny Root's avatar
Kenny Root committed
17 18 19
//#define LOG_NDEBUG 0
#define LOG_TAG "keystore"

20 21 22 23 24 25 26
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <dirent.h>
Kenny Root's avatar
Kenny Root committed
27
#include <errno.h>
28 29
#include <fcntl.h>
#include <limits.h>
30
#include <assert.h>
31 32 33 34 35 36 37
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <arpa/inet.h>

#include <openssl/aes.h>
38
#include <openssl/bio.h>
39 40
#include <openssl/evp.h>
#include <openssl/md5.h>
41
#include <openssl/pem.h>
42

43 44
#include <hardware/keymaster.h>

Kenny Root's avatar
Kenny Root committed
45
#include <utils/String8.h>
46
#include <utils/UniquePtr.h>
Kenny Root's avatar
Kenny Root committed
47
#include <utils/Vector.h>
48

Kenny Root's avatar
Kenny Root committed
49 50 51 52
#include <keystore/IKeystoreService.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>

53 54 55 56
#include <cutils/log.h>
#include <cutils/sockets.h>
#include <private/android_filesystem_config.h>

Kenny Root's avatar
Kenny Root committed
57
#include <keystore/keystore.h>
58 59 60 61 62 63 64 65 66 67 68

/* KeyStore is a secured storage for key-value pairs. In this implementation,
 * each file stores one key-value pair. Keys are encoded in file names, and
 * values are encrypted with checksums. The encryption key is protected by a
 * user-defined password. To keep things simple, buffers are always larger than
 * the maximum space we needed, so boundary checks on buffers are omitted. */

#define KEY_SIZE        ((NAME_MAX - 15) / 2)
#define VALUE_SIZE      32768
#define PASSWORD_SIZE   VALUE_SIZE

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

struct BIO_Delete {
    void operator()(BIO* p) const {
        BIO_free(p);
    }
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;

struct EVP_PKEY_Delete {
    void operator()(EVP_PKEY* p) const {
        EVP_PKEY_free(p);
    }
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;

struct PKCS8_PRIV_KEY_INFO_Delete {
    void operator()(PKCS8_PRIV_KEY_INFO* p) const {
        PKCS8_PRIV_KEY_INFO_free(p);
    }
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;


92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
static int keymaster_device_initialize(keymaster_device_t** dev) {
    int rc;

    const hw_module_t* mod;
    rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
    if (rc) {
        ALOGE("could not find any keystore module");
        goto out;
    }

    rc = keymaster_open(mod, dev);
    if (rc) {
        ALOGE("could not open keymaster device in %s (%s)",
            KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
        goto out;
    }

    return 0;

out:
    *dev = NULL;
    return rc;
}

static void keymaster_device_release(keymaster_device_t* dev) {
    keymaster_close(dev);
}

Kenny Root's avatar
Kenny Root committed
120 121 122 123 124 125
/***************
 * PERMISSIONS *
 ***************/

/* Here are the permissions, actions, users, and the main function. */
typedef enum {
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    P_TEST      = 1 << 0,
    P_GET       = 1 << 1,
    P_INSERT    = 1 << 2,
    P_DELETE    = 1 << 3,
    P_EXIST     = 1 << 4,
    P_SAW       = 1 << 5,
    P_RESET     = 1 << 6,
    P_PASSWORD  = 1 << 7,
    P_LOCK      = 1 << 8,
    P_UNLOCK    = 1 << 9,
    P_ZERO      = 1 << 10,
    P_SIGN      = 1 << 11,
    P_VERIFY    = 1 << 12,
    P_GRANT     = 1 << 13,
    P_DUPLICATE = 1 << 14,
141
    P_CLEAR_UID = 1 << 15,
Kenny Root's avatar
Kenny Root committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
} perm_t;

static struct user_euid {
    uid_t uid;
    uid_t euid;
} user_euids[] = {
    {AID_VPN, AID_SYSTEM},
    {AID_WIFI, AID_SYSTEM},
    {AID_ROOT, AID_SYSTEM},
};

static struct user_perm {
    uid_t uid;
    perm_t perms;
} user_perms[] = {
    {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
    {AID_VPN,    static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
    {AID_WIFI,   static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
    {AID_ROOT,   static_cast<perm_t>(P_GET) },
};

static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
        | P_VERIFY);

Kenny Root's avatar
Kenny Root committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/**
 * Returns the app ID (in the Android multi-user sense) for the current
 * UNIX UID.
 */
static uid_t get_app_id(uid_t uid) {
    return uid % AID_USER;
}

/**
 * Returns the user ID (in the Android multi-user sense) for the current
 * UNIX UID.
 */
static uid_t get_user_id(uid_t uid) {
    return uid / AID_USER;
}


Kenny Root's avatar
Kenny Root committed
183
static bool has_permission(uid_t uid, perm_t perm) {
Kenny Root's avatar
Kenny Root committed
184 185 186 187 188
    // All system users are equivalent for multi-user support.
    if (get_app_id(uid) == AID_SYSTEM) {
        uid = AID_SYSTEM;
    }

Kenny Root's avatar
Kenny Root committed
189 190 191 192 193 194 195 196 197 198
    for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
        struct user_perm user = user_perms[i];
        if (user.uid == uid) {
            return user.perms & perm;
        }
    }

    return DEFAULT_PERMS & perm;
}

199 200 201 202 203
/**
 * Returns the UID that the callingUid should act as. This is here for
 * legacy support of the WiFi and VPN systems and should be removed
 * when WiFi can operate in its own namespace.
 */
Kenny Root's avatar
Kenny Root committed
204 205 206 207 208 209 210 211 212 213 214
static uid_t get_keystore_euid(uid_t uid) {
    for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
        struct user_euid user = user_euids[i];
        if (user.uid == uid) {
            return user.euid;
        }
    }

    return uid;
}

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/**
 * Returns true if the callingUid is allowed to interact in the targetUid's
 * namespace.
 */
static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
    for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
        struct user_euid user = user_euids[i];
        if (user.euid == callingUid && user.uid == targetUid) {
            return true;
        }
    }

    return false;
}

230 231 232 233 234 235 236
/* 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. */

Kenny Root's avatar
Kenny Root committed
237 238 239 240 241 242 243 244 245 246 247
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;
        }
    }
    return length;
}

Kenny Root's avatar
Kenny Root committed
248 249 250
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();
251
    for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root's avatar
Kenny Root committed
252
        if (*in < '0' || *in > '~') {
253 254 255
            *out = '+' + (*in >> 6);
            *++out = '0' + (*in & 0x3F);
            ++length;
Kenny Root's avatar
Kenny Root committed
256 257
        } else {
            *out = *in;
258 259 260
        }
    }
    *out = '\0';
261 262 263
    return length;
}

Kenny Root's avatar
Kenny Root committed
264
static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
265 266 267
    int n = snprintf(out, NAME_MAX, "%u_", uid);
    out += n;

Kenny Root's avatar
Kenny Root committed
268
    return n + encode_key(out, keyName);
269 270
}

Kenny Root's avatar
Kenny Root committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
/*
 * 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;
301
        } else {
Kenny Root's avatar
Kenny Root committed
302
            *out++ = *in;
303 304 305 306 307 308 309 310
        }
    }
    *out = '\0';
}

static size_t readFully(int fd, uint8_t* data, size_t size) {
    size_t remaining = size;
    while (remaining > 0) {
311
        ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root's avatar
Kenny Root committed
312
        if (n <= 0) {
313
            return size - remaining;
314 315 316 317 318 319 320 321 322 323
        }
        data += n;
        remaining -= n;
    }
    return size;
}

static size_t writeFully(int fd, uint8_t* data, size_t size) {
    size_t remaining = size;
    while (remaining > 0) {
324 325 326 327
        ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
        if (n < 0) {
            ALOGW("write failed: %s", strerror(errno));
            return size - remaining;
328 329 330 331 332 333 334 335 336 337 338
        }
        data += n;
        remaining -= n;
    }
    return size;
}

class Entropy {
public:
    Entropy() : mRandom(-1) {}
    ~Entropy() {
339
        if (mRandom >= 0) {
340 341 342 343 344 345
            close(mRandom);
        }
    }

    bool open() {
        const char* randomDevice = "/dev/urandom";
346 347
        mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
        if (mRandom < 0) {
348 349 350 351 352 353
            ALOGE("open: %s: %s", randomDevice, strerror(errno));
            return false;
        }
        return true;
    }

Kenny Root's avatar
Kenny Root committed
354
    bool generate_random_data(uint8_t* data, size_t size) const {
355 356 357 358 359 360 361 362 363 364 365
        return (readFully(mRandom, data, size) == size);
    }

private:
    int mRandom;
};

/* Here is the file format. There are two parts in blob.value, the secret and
 * the description. The secret is stored in ciphertext, and its original size
 * can be found in blob.length. The description is stored after the secret in
 * plaintext, and its size is specified in blob.info. The total size of the two
366
 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
367
 * the second is the blob's type, and the third byte is flags. Fields other
368 369 370
 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
 * and decryptBlob(). Thus they should not be accessed from outside. */

371 372 373 374 375 376 377 378 379 380 381 382 383 384
/* ** Note to future implementors of encryption: **
 * Currently this is the construction:
 *   metadata || Enc(MD5(data) || data)
 *
 * This should be the construction used for encrypting if re-implementing:
 *
 *   Derive independent keys for encryption and MAC:
 *     Kenc = AES_encrypt(masterKey, "Encrypt")
 *     Kmac = AES_encrypt(masterKey, "MAC")
 *
 *   Store this:
 *     metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
 *             HMAC(Kmac, metadata || Enc(data))
 */
385
struct __attribute__((packed)) blob {
386 387
    uint8_t version;
    uint8_t type;
388
    uint8_t flags;
389 390
    uint8_t info;
    uint8_t vector[AES_BLOCK_SIZE];
391
    uint8_t encrypted[0]; // Marks offset to encrypted data.
392
    uint8_t digest[MD5_DIGEST_LENGTH];
393
    uint8_t digested[0]; // Marks offset to digested data.
394 395 396 397
    int32_t length; // in network byte order when encrypted
    uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
};

398
typedef enum {
399
    TYPE_ANY = 0, // meta type that matches anything
400 401 402 403 404
    TYPE_GENERIC = 1,
    TYPE_MASTER_KEY = 2,
    TYPE_KEY_PAIR = 3,
} BlobType;

405
static const uint8_t CURRENT_BLOB_VERSION = 2;
406

407 408
class Blob {
public:
Kenny Root's avatar
Kenny Root committed
409 410
    Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
            BlobType type) {
411 412 413 414 415
        mBlob.length = valueLength;
        memcpy(mBlob.value, value, valueLength);

        mBlob.info = infoLength;
        memcpy(mBlob.value + valueLength, info, infoLength);
416

Kenny Root's avatar
Kenny Root committed
417
        mBlob.version = CURRENT_BLOB_VERSION;
418
        mBlob.type = uint8_t(type);
419 420

        mBlob.flags = KEYSTORE_FLAG_NONE;
421 422 423 424 425 426 427 428
    }

    Blob(blob b) {
        mBlob = b;
    }

    Blob() {}

Kenny Root's avatar
Kenny Root committed
429
    const uint8_t* getValue() const {
430 431 432
        return mBlob.value;
    }

Kenny Root's avatar
Kenny Root committed
433
    int32_t getLength() const {
434 435 436
        return mBlob.length;
    }

Kenny Root's avatar
Kenny Root committed
437 438 439 440 441
    const uint8_t* getInfo() const {
        return mBlob.value + mBlob.length;
    }

    uint8_t getInfoLength() const {
442 443 444
        return mBlob.info;
    }

445 446 447 448
    uint8_t getVersion() const {
        return mBlob.version;
    }

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    bool isEncrypted() const {
        if (mBlob.version < 2) {
            return true;
        }

        return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
    }

    void setEncrypted(bool encrypted) {
        if (encrypted) {
            mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
        } else {
            mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
        }
    }

465 466 467 468 469 470 471 472 473 474 475 476
    void setVersion(uint8_t version) {
        mBlob.version = version;
    }

    BlobType getType() const {
        return BlobType(mBlob.type);
    }

    void setType(BlobType type) {
        mBlob.type = uint8_t(type);
    }

477 478 479 480 481 482 483 484 485 486 487 488
    ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
        ALOGV("writing blob %s", filename);
        if (isEncrypted()) {
            if (state != STATE_NO_ERROR) {
                ALOGD("couldn't insert encrypted blob while not unlocked");
                return LOCKED;
            }

            if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
                ALOGW("Could not read random data for: %s", filename);
                return SYSTEM_ERROR;
            }
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        }

        // data includes the value and the value's length
        size_t dataLength = mBlob.length + sizeof(mBlob.length);
        // pad data to the AES_BLOCK_SIZE
        size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
                                 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
        // encrypted data includes the digest value
        size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
        // move info after space for padding
        memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
        // zero padding area
        memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);

        mBlob.length = htonl(mBlob.length);

505 506 507 508 509 510 511 512
        if (isEncrypted()) {
            MD5(mBlob.digested, digestedLength, mBlob.digest);

            uint8_t vector[AES_BLOCK_SIZE];
            memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
            AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
                            aes_key, vector, AES_ENCRYPT);
        }
513 514 515 516 517

        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
        size_t fileLength = encryptedLength + headerLength + mBlob.info;

        const char* tmpFileName = ".tmp";
518 519 520 521
        int out = TEMP_FAILURE_RETRY(open(tmpFileName,
                O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
        if (out < 0) {
            ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
522 523 524 525 526 527 528
            return SYSTEM_ERROR;
        }
        size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
        if (close(out) != 0) {
            return SYSTEM_ERROR;
        }
        if (writtenBytes != fileLength) {
529
            ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
530 531 532
            unlink(tmpFileName);
            return SYSTEM_ERROR;
        }
533 534 535 536 537
        if (rename(tmpFileName, filename) == -1) {
            ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
            return SYSTEM_ERROR;
        }
        return NO_ERROR;
538 539
    }

540 541
    ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
        ALOGV("reading blob %s", filename);
542 543
        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
        if (in < 0) {
544 545 546 547 548 549 550 551 552
            return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
        }
        // fileLength may be less than sizeof(mBlob) since the in
        // memory version has extra padding to tolerate rounding up to
        // the AES_BLOCK_SIZE
        size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
        if (close(in) != 0) {
            return SYSTEM_ERROR;
        }
553 554 555 556 557

        if (isEncrypted() && (state != STATE_NO_ERROR)) {
            return LOCKED;
        }

558 559 560 561 562 563
        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
        if (fileLength < headerLength) {
            return VALUE_CORRUPTED;
        }

        ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
564
        if (encryptedLength < 0) {
565 566
            return VALUE_CORRUPTED;
        }
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

        ssize_t digestedLength;
        if (isEncrypted()) {
            if (encryptedLength % AES_BLOCK_SIZE != 0) {
                return VALUE_CORRUPTED;
            }

            AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
                            mBlob.vector, AES_DECRYPT);
            digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
            uint8_t computedDigest[MD5_DIGEST_LENGTH];
            MD5(mBlob.digested, digestedLength, computedDigest);
            if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
                return VALUE_CORRUPTED;
            }
        } else {
            digestedLength = encryptedLength;
584 585 586 587 588 589 590 591 592 593 594
        }

        ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
        mBlob.length = ntohl(mBlob.length);
        if (mBlob.length < 0 || mBlob.length > maxValueLength) {
            return VALUE_CORRUPTED;
        }
        if (mBlob.info != 0) {
            // move info from after padding to after data
            memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
        }
Kenny Root's avatar
Kenny Root committed
595
        return ::NO_ERROR;
596 597 598 599 600 601
    }

private:
    struct blob mBlob;
};

Kenny Root's avatar
Kenny Root committed
602 603 604 605 606 607
class UserState {
public:
    UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
        asprintf(&mUserDir, "user_%u", mUserId);
        asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
    }
608

Kenny Root's avatar
Kenny Root committed
609 610 611 612
    ~UserState() {
        free(mUserDir);
        free(mMasterKeyFile);
    }
613

Kenny Root's avatar
Kenny Root committed
614 615 616 617 618 619 620
    bool initialize() {
        if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
            ALOGE("Could not create directory '%s'", mUserDir);
            return false;
        }

        if (access(mMasterKeyFile, R_OK) == 0) {
621 622 623 624
            setState(STATE_LOCKED);
        } else {
            setState(STATE_UNINITIALIZED);
        }
625

Kenny Root's avatar
Kenny Root committed
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
        return true;
    }

    uid_t getUserId() const {
        return mUserId;
    }

    const char* getUserDirName() const {
        return mUserDir;
    }

    const char* getMasterKeyFileName() const {
        return mMasterKeyFile;
    }

    void setState(State state) {
        mState = state;
        if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
            mRetry = MAX_RETRY;
        }
646 647
    }

Kenny Root's avatar
Kenny Root committed
648
    State getState() const {
649 650 651
        return mState;
    }

Kenny Root's avatar
Kenny Root committed
652
    int8_t getRetry() const {
653 654 655
        return mRetry;
    }

Kenny Root's avatar
Kenny Root committed
656 657 658 659 660
    void zeroizeMasterKeysInMemory() {
        memset(mMasterKey, 0, sizeof(mMasterKey));
        memset(mSalt, 0, sizeof(mSalt));
        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
661 662
    }

Kenny Root's avatar
Kenny Root committed
663 664
    ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
        if (!generateMasterKey(entropy)) {
665 666
            return SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
667
        ResponseCode response = writeMasterKey(pw, entropy);
668 669 670 671
        if (response != NO_ERROR) {
            return response;
        }
        setupMasterKeys();
Kenny Root's avatar
Kenny Root committed
672
        return ::NO_ERROR;
673 674
    }

Kenny Root's avatar
Kenny Root committed
675
    ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
676 677 678 679
        uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
        generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
        AES_KEY passwordAesKey;
        AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
680
        Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
681
        return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
682 683
    }

Kenny Root's avatar
Kenny Root committed
684 685
    ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
        int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
686
        if (in < 0) {
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
            return SYSTEM_ERROR;
        }

        // we read the raw blob to just to get the salt to generate
        // the AES key, then we create the Blob to use with decryptBlob
        blob rawBlob;
        size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
        if (close(in) != 0) {
            return SYSTEM_ERROR;
        }
        // find salt at EOF if present, otherwise we have an old file
        uint8_t* salt;
        if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
            salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
        } else {
            salt = NULL;
        }
        uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
        generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
        AES_KEY passwordAesKey;
        AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
        Blob masterKeyBlob(rawBlob);
709 710
        ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
                STATE_NO_ERROR);
711
        if (response == SYSTEM_ERROR) {
712
            return response;
713 714 715 716
        }
        if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
            // if salt was missing, generate one and write a new master key file with the salt.
            if (salt == NULL) {
Kenny Root's avatar
Kenny Root committed
717
                if (!generateSalt(entropy)) {
718 719
                    return SYSTEM_ERROR;
                }
Kenny Root's avatar
Kenny Root committed
720
                response = writeMasterKey(pw, entropy);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
            }
            if (response == NO_ERROR) {
                memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
                setupMasterKeys();
            }
            return response;
        }
        if (mRetry <= 0) {
            reset();
            return UNINITIALIZED;
        }
        --mRetry;
        switch (mRetry) {
            case 0: return WRONG_PASSWORD_0;
            case 1: return WRONG_PASSWORD_1;
            case 2: return WRONG_PASSWORD_2;
            case 3: return WRONG_PASSWORD_3;
            default: return WRONG_PASSWORD_3;
        }
    }

Kenny Root's avatar
Kenny Root committed
742 743 744
    AES_KEY* getEncryptionKey() {
        return &mMasterKeyEncryption;
    }
745

Kenny Root's avatar
Kenny Root committed
746 747 748
    AES_KEY* getDecryptionKey() {
        return &mMasterKeyDecryption;
    }
749

Kenny Root's avatar
Kenny Root committed
750 751
    bool reset() {
        DIR* dir = opendir(getUserDirName());
752
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
753
            ALOGW("couldn't open user directory: %s", strerror(errno));
754 755
            return false;
        }
Kenny Root's avatar
Kenny Root committed
756 757

        struct dirent* file;
758
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
            // We only care about files.
            if (file->d_type != DT_REG) {
                continue;
            }

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

            // Find the current file's UID.
            char* end;
            unsigned long thisUid = strtoul(file->d_name, &end, 10);
            if (end[0] != '_' || end[1] == 0) {
                continue;
            }

            // Skip if this is not our user.
            if (get_user_id(thisUid) != mUserId) {
                continue;
            }

            unlinkat(dirfd(dir), file->d_name, 0);
782 783 784 785 786
        }
        closedir(dir);
        return true;
    }

Kenny Root's avatar
Kenny Root committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
private:
    static const int MASTER_KEY_SIZE_BYTES = 16;
    static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;

    static const int MAX_RETRY = 4;
    static const size_t SALT_SIZE = 16;

    void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
            uint8_t* salt) {
        size_t saltSize;
        if (salt != NULL) {
            saltSize = SALT_SIZE;
        } else {
            // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
            salt = (uint8_t*) "keystore";
            // sizeof = 9, not strlen = 8
            saltSize = sizeof("keystore");
        }

        PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
                saltSize, 8192, keySize, key);
    }

    bool generateSalt(Entropy* entropy) {
        return entropy->generate_random_data(mSalt, sizeof(mSalt));
    }

    bool generateMasterKey(Entropy* entropy) {
        if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
            return false;
        }
        if (!generateSalt(entropy)) {
            return false;
        }
        return true;
    }

    void setupMasterKeys() {
        AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
        AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
        setState(STATE_NO_ERROR);
    }

    uid_t mUserId;

    char* mUserDir;
    char* mMasterKeyFile;

    State mState;
    int8_t mRetry;

    uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
    uint8_t mSalt[SALT_SIZE];

    AES_KEY mMasterKeyEncryption;
    AES_KEY mMasterKeyDecryption;
};

typedef struct {
    uint32_t uid;
    const uint8_t* filename;
} grant_t;

class KeyStore {
public:
    KeyStore(Entropy* entropy, keymaster_device_t* device)
        : mEntropy(entropy)
        , mDevice(device)
    {
        memset(&mMetaData, '\0', sizeof(mMetaData));
    }

    ~KeyStore() {
        for (android::Vector<grant_t*>::iterator it(mGrants.begin());
                it != mGrants.end(); it++) {
            delete *it;
            mGrants.erase(it);
        }

        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
                it != mMasterKeys.end(); it++) {
            delete *it;
            mMasterKeys.erase(it);
        }
    }

    keymaster_device_t* getDevice() const {
        return mDevice;
    }

    ResponseCode initialize() {
        readMetaData();
        if (upgradeKeystore()) {
            writeMetaData();
        }

        return ::NO_ERROR;
    }

    State getState(uid_t uid) {
        return getUserState(uid)->getState();
    }

    ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
        UserState* userState = getUserState(uid);
        return userState->initialize(pw, mEntropy);
    }

    ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
        uid_t user_id = get_user_id(uid);
        UserState* userState = getUserState(user_id);
        return userState->writeMasterKey(pw, mEntropy);
    }

    ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
        uid_t user_id = get_user_id(uid);
        UserState* userState = getUserState(user_id);
        return userState->readMasterKey(pw, mEntropy);
    }

    android::String8 getKeyName(const android::String8& keyName) {
908
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
909 910 911 912 913
        encode_key(encoded, keyName);
        return android::String8(encoded);
    }

    android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
914
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
915 916 917 918 919
        encode_key(encoded, keyName);
        return android::String8::format("%u_%s", uid, encoded);
    }

    android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
920
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
        encode_key(encoded, keyName);
        return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
                encoded);
    }

    bool reset(uid_t uid) {
        UserState* userState = getUserState(uid);
        userState->zeroizeMasterKeysInMemory();
        userState->setState(STATE_UNINITIALIZED);
        return userState->reset();
    }

    bool isEmpty(uid_t uid) const {
        const UserState* userState = getUserState(uid);
        if (userState == NULL) {
            return true;
        }

        DIR* dir = opendir(userState->getUserDirName());
940 941 942 943 944
        struct dirent* file;
        if (!dir) {
            return true;
        }
        bool result = true;
Kenny Root's avatar
Kenny Root committed
945 946 947 948

        char filename[NAME_MAX];
        int n = snprintf(filename, sizeof(filename), "%u_", uid);

949
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
950 951 952 953 954 955 956 957 958 959 960
            // 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(file->d_name, filename, n)) {
961 962 963 964 965 966 967 968
                result = false;
                break;
            }
        }
        closedir(dir);
        return result;
    }

Kenny Root's avatar
Kenny Root committed
969 970 971 972
    void lock(uid_t uid) {
        UserState* userState = getUserState(uid);
        userState->zeroizeMasterKeysInMemory();
        userState->setState(STATE_LOCKED);
973 974
    }

Kenny Root's avatar
Kenny Root committed
975 976
    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
        UserState* userState = getUserState(uid);
977 978
        ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                userState->getState());
979 980 981 982 983
        if (rc != NO_ERROR) {
            return rc;
        }

        const uint8_t version = keyBlob->getVersion();
Kenny Root's avatar
Kenny Root committed
984
        if (version < CURRENT_BLOB_VERSION) {
Kenny Root's avatar
Kenny Root committed
985 986 987 988
            /* 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.
             */
Kenny Root's avatar
Kenny Root committed
989 990
            if (upgradeBlob(filename, keyBlob, version, type, uid)) {
                if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
991 992
                        || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                                userState->getState())) != NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
993 994 995
                    return rc;
                }
            }
996 997
        }

998
        if (type != TYPE_ANY && keyBlob->getType() != type) {
999 1000 1001 1002 1003
            ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
            return KEY_NOT_FOUND;
        }

        return rc;
1004 1005
    }

Kenny Root's avatar
Kenny Root committed
1006 1007
    ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
        UserState* userState = getUserState(uid);
1008 1009
        return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
                mEntropy);
1010 1011
    }

Kenny Root's avatar
Kenny Root committed
1012
    void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root's avatar
Kenny Root committed
1013 1014 1015
        const grant_t* existing = getGrant(filename, granteeUid);
        if (existing == NULL) {
            grant_t* grant = new grant_t;
Kenny Root's avatar
Kenny Root committed
1016
            grant->uid = granteeUid;
1017
            grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root's avatar
Kenny Root committed
1018
            mGrants.add(grant);
1019 1020 1021
        }
    }

Kenny Root's avatar
Kenny Root committed
1022
    bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root's avatar
Kenny Root committed
1023 1024 1025 1026 1027 1028 1029 1030
        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;
            }
1031 1032 1033 1034
        }
        return false;
    }

1035 1036
    bool hasGrant(const char* filename, const uid_t uid) const {
        return getGrant(filename, uid) != NULL;
1037 1038
    }

1039 1040
    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
            int32_t flags) {
1041 1042 1043 1044 1045 1046 1047 1048 1049
        uint8_t* data;
        size_t dataLength;
        int rc;

        if (mDevice->import_keypair == NULL) {
            ALOGE("Keymaster doesn't support import!");
            return SYSTEM_ERROR;
        }

Kenny Root's avatar
Kenny Root committed
1050
        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
1051 1052 1053 1054 1055 1056 1057 1058
        if (rc) {
            ALOGE("Error while importing keypair: %d", rc);
            return SYSTEM_ERROR;
        }

        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
        free(data);

1059 1060
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);

Kenny Root's avatar
Kenny Root committed
1061
        return put(filename, &keyBlob, uid);
1062 1063
    }

1064
    bool isHardwareBacked() const {
1065
        return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1066 1067
    }

Kenny Root's avatar
Kenny Root committed
1068 1069 1070 1071
    ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
            const BlobType type) {
        char filename[NAME_MAX];
        encode_key_for_uid(filename, uid, keyName);
1072

Kenny Root's avatar
Kenny Root committed
1073 1074
        UserState* userState = getUserState(uid);
        android::String8 filepath8;
1075

Kenny Root's avatar
Kenny Root committed
1076 1077 1078 1079 1080
        filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
        if (filepath8.string() == NULL) {
            ALOGW("can't create filepath for key %s", filename);
            return SYSTEM_ERROR;
        }
1081

Kenny Root's avatar
Kenny Root committed
1082 1083 1084 1085
        ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
        if (responseCode == NO_ERROR) {
            return responseCode;
        }
1086

Kenny Root's avatar
Kenny Root committed
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        // If this is one of the legacy UID->UID mappings, use it.
        uid_t euid = get_keystore_euid(uid);
        if (euid != uid) {
            encode_key_for_uid(filename, euid, keyName);
            filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
            responseCode = get(filepath8.string(), keyBlob, type, uid);
            if (responseCode == NO_ERROR) {
                return responseCode;
            }
        }
1097

Kenny Root's avatar
Kenny Root committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
        // They might be using a granted key.
        encode_key(filename, keyName);
        char* end;
        strtoul(filename, &end, 10);
        if (end[0] != '_' || end[1] == 0) {
            return KEY_NOT_FOUND;
        }
        filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
        if (!hasGrant(filepath8.string(), uid)) {
            return responseCode;
1108 1109
        }

Kenny Root's avatar
Kenny Root committed
1110 1111
        // It is a granted key. Try to load it.
        return get(filepath8.string(), keyBlob, type, uid);
1112 1113
    }

Kenny Root's avatar
Kenny Root committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    /**
     * Returns any existing UserState or creates it if it doesn't exist.
     */
    UserState* getUserState(uid_t uid) {
        uid_t userId = get_user_id(uid);

        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
                it != mMasterKeys.end(); it++) {
            UserState* state = *it;
            if (state->getUserId() == userId) {
                return state;
            }
1126
        }
Kenny Root's avatar
Kenny Root committed
1127 1128 1129 1130 1131 1132 1133 1134

        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);
1135
        }
Kenny Root's avatar
Kenny Root committed
1136 1137
        mMasterKeys.add(userState);
        return userState;
1138 1139
    }

Kenny Root's avatar
Kenny Root committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    /**
     * Returns NULL if the UserState doesn't already exist.
     */
    const UserState* getUserState(uid_t uid) const {
        uid_t userId = get_user_id(uid);

        for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
                it != mMasterKeys.end(); it++) {
            UserState* state = *it;
            if (state->getUserId() == userId) {
                return state;
            }
        }
1153

Kenny Root's avatar
Kenny Root committed
1154
        return NULL;
1155 1156
    }

Kenny Root's avatar
Kenny Root committed
1157 1158 1159 1160
private:
    static const char* sOldMasterKey;
    static const char* sMetaDataFile;
    Entropy* mEntropy;
Kenny Root's avatar
Kenny Root committed
1161

Kenny Root's avatar
Kenny Root committed
1162
    keymaster_device_t* mDevice;
1163

Kenny Root's avatar
Kenny Root committed
1164 1165 1166
    android::Vector<UserState*> mMasterKeys;

    android::Vector<grant_t*> mGrants;
1167

Kenny Root's avatar
Kenny Root committed
1168 1169 1170
    typedef struct {
        uint32_t version;
    } keystore_metadata_t;
1171

Kenny Root's avatar
Kenny Root committed
1172 1173 1174 1175 1176 1177
    keystore_metadata_t mMetaData;

    const grant_t* 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;
1178
            if (grant->uid == uid
Kenny Root's avatar
Kenny Root committed
1179
                    && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1180 1181 1182 1183 1184 1185
                return grant;
            }
        }
        return NULL;
    }

1186 1187 1188 1189
    /**
     * Upgrade code. This will upgrade the key from the current version
     * to whatever is newest.
     */
Kenny Root's avatar
Kenny Root committed
1190 1191
    bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
            const BlobType type, uid_t uid) {
1192 1193 1194 1195 1196 1197 1198 1199 1200
        bool updated = false;
        uint8_t version = oldVersion;

        /* From V0 -> V1: All old types were unknown */
        if (version == 0) {
            ALOGV("upgrading to version 1 and setting type %d", type);

            blob->setType(type);
            if (type == TYPE_KEY_PAIR) {
Kenny Root's avatar
Kenny Root committed
1201
                importBlobAsKey(blob, filename, uid);
1202 1203 1204 1205 1206
            }
            version = 1;
            updated = true;
        }

1207 1208 1209 1210 1211 1212 1213 1214 1215
        /* From V1 -> V2: All old keys were encrypted */
        if (version == 1) {
            ALOGV("upgrading to version 2");

            blob->setEncrypted(true);
            version = 2;
            updated = true;
        }

1216 1217 1218
        /*
         * If we've updated, set the key blob to the right version
         * and write it.
Kenny Root's avatar
Kenny Root committed
1219
         */
1220 1221 1222 1223
        if (updated) {
            ALOGV("updated and writing file %s", filename);
            blob->setVersion(version);
        }
Kenny Root's avatar
Kenny Root committed
1224 1225

        return updated;
1226 1227 1228 1229 1230 1231 1232 1233
    }

    /**
     * Takes a blob that is an PEM-encoded RSA key as a byte array and
     * converts it to a DER-encoded PKCS#8 for import into a keymaster.
     * Then it overwrites the original blob with the new blob
     * format that is returned from the keymaster.
     */
Kenny Root's avatar
Kenny Root committed
1234
    ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
        // 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;
        }

        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;
        }

        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;
        }

1255 1256
        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
        uint8_t* tmp = pkcs8key.get();
1257 1258 1259 1260 1261
        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
            ALOGE("Couldn't convert to PKCS#8");
            return SYSTEM_ERROR;
        }

1262 1263
        ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
                blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1264 1265 1266 1267
        if (rc != NO_ERROR) {
            return rc;
        }

Kenny Root's avatar
Kenny Root committed
1268
        return get(filename, blob, TYPE_KEY_PAIR, uid);
1269
    }
1270

Kenny Root's avatar
Kenny Root committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    void readMetaData() {
        int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
        if (in < 0) {
            return;
        }
        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));
        }
        close(in);
1282 1283
    }

Kenny Root's avatar
Kenny Root committed
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    void 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));
1296
        }
Kenny Root's avatar
Kenny Root committed
1297 1298
        close(out);
        rename(tmpFileName, sMetaDataFile);
1299 1300
    }

Kenny Root's avatar
Kenny Root committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    bool upgradeKeystore() {
        bool upgraded = false;

        if (mMetaData.version == 0) {
            UserState* userState = getUserState(0);

            // Initialize first so the directory is made.
            userState->initialize();

            // 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;
                }
            }

            // Initialize again in case we had a key.
            userState->initialize();

            // Try to migrate existing keys.
            DIR* dir = opendir(".");
            if (!dir) {
                // Give up now; maybe we can upgrade later.
                ALOGE("couldn't open keystore's directory; something is wrong");
                return false;
            }

            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;
                }

                // Find the current file's user.
                char* end;
                unsigned long thisUid = strtoul(file->d_name, &end, 10);
                if (end[0] != '_' || end[1] == 0) {
                    continue;
                }
                UserState* otherUser = getUserState(thisUid);
                if (otherUser->getUserId() != 0) {
                    unlinkat(dirfd(dir), file->d_name, 0);
                }

                // Rename the file into user directory.
                DIR* otherdir = opendir(otherUser->getUserDirName());
                if (otherdir == NULL) {
                    ALOGW("couldn't open user directory for rename");
                    continue;
                }
                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));
                }
                closedir(otherdir);
            }
            closedir(dir);

            mMetaData.version = 1;
            upgraded = true;
        }

        return upgraded;
1370
    }
Kenny Root's avatar
Kenny Root committed
1371
};
1372

Kenny Root's avatar
Kenny Root committed
1373 1374
const char* KeyStore::sOldMasterKey = ".masterkey";
const char* KeyStore::sMetaDataFile = ".metadata";
1375

Kenny Root's avatar
Kenny Root committed
1376 1377 1378 1379 1380 1381 1382
namespace android {
class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
public:
    KeyStoreProxy(KeyStore* keyStore)
        : mKeyStore(keyStore)
    {
    }
1383

Kenny Root's avatar
Kenny Root committed
1384 1385 1386
    void binderDied(const wp<IBinder>&) {
        ALOGE("binder death detected");
    }
1387

Kenny Root's avatar
Kenny Root committed
1388
    int32_t test() {
1389 1390 1391
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_TEST)) {
            ALOGW("permission denied for %d: test", callingUid);
Kenny Root's avatar
Kenny Root committed
1392 1393
            return ::PERMISSION_DENIED;
        }
1394

Kenny Root's avatar
Kenny Root committed
1395
        return mKeyStore->getState(callingUid);
1396 1397
    }

Kenny Root's avatar
Kenny Root committed
1398
    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
1399 1400 1401
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GET)) {
            ALOGW("permission denied for %d: get", callingUid);
Kenny Root's avatar
Kenny Root committed
1402 1403
            return ::PERMISSION_DENIED;
        }
1404

Kenny Root's avatar
Kenny Root committed
1405 1406
        String8 name8(name);
        Blob keyBlob;
1407

Kenny Root's avatar
Kenny Root committed
1408
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1409
                TYPE_GENERIC);
Kenny Root's avatar
Kenny Root committed
1410
        if (responseCode != ::NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1411
            ALOGW("Could not read %s", name8.string());
Kenny Root's avatar
Kenny Root committed
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            *item = NULL;
            *itemLength = 0;
            return responseCode;
        }

        *item = (uint8_t*) malloc(keyBlob.getLength());
        memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
        *itemLength = keyBlob.getLength();

        return ::NO_ERROR;
1422 1423
    }

1424 1425
    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
            int32_t flags) {
1426 1427 1428
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_INSERT)) {
            ALOGW("permission denied for %d: insert", callingUid);
Kenny Root's avatar
Kenny Root committed
1429 1430 1431
            return ::PERMISSION_DENIED;
        }

1432 1433 1434 1435 1436 1437
        State state = mKeyStore->getState(callingUid);
        if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
            ALOGD("calling get in state: %d", state);
            return state;
        }

1438 1439 1440
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1441 1442 1443
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1444
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1445
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
1446 1447

        Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root's avatar
Kenny Root committed
1448
        return mKeyStore->put(filename.string(), &keyBlob, callingUid);
1449 1450
    }

1451
    int32_t del(const String16& name, int targetUid) {
1452 1453 1454
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_DELETE)) {
            ALOGW("permission denied for %d: del", callingUid);
Kenny Root's avatar
Kenny Root committed
1455 1456 1457
            return ::PERMISSION_DENIED;
        }

1458 1459 1460
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1461 1462 1463
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1464
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1465
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1466

Kenny Root's avatar
Kenny Root committed
1467
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
1468 1469
        ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
                callingUid);
Kenny Root's avatar
Kenny Root committed
1470 1471 1472 1473
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1474 1475
    }

1476
    int32_t exist(const String16& name, int targetUid) {
1477 1478 1479
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_EXIST)) {
            ALOGW("permission denied for %d: exist", callingUid);
Kenny Root's avatar
Kenny Root committed
1480 1481 1482
            return ::PERMISSION_DENIED;
        }

1483 1484 1485
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1486 1487 1488
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1489
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1490
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
1491

Kenny Root's avatar
Kenny Root committed
1492
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
1493 1494 1495
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }
        return ::NO_ERROR;
1496 1497
    }

1498
    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1499 1500 1501
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_SAW)) {
            ALOGW("permission denied for %d: saw", callingUid);
Kenny Root's avatar
Kenny Root committed
1502 1503 1504
            return ::PERMISSION_DENIED;
        }

1505 1506 1507
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1508 1509 1510
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1511 1512
        UserState* userState = mKeyStore->getUserState(targetUid);
        DIR* dir = opendir(userState->getUserDirName());
Kenny Root's avatar
Kenny Root committed
1513
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
1514
            ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root's avatar
Kenny Root committed
1515 1516 1517 1518
            return ::SYSTEM_ERROR;
        }

        const String8 prefix8(prefix);
Kenny Root's avatar
Kenny Root committed
1519 1520
        String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
        size_t n = filename.length();
Kenny Root's avatar
Kenny Root committed
1521 1522 1523

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
            // 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(filename.string(), file->d_name, n)) {
Kenny Root's avatar
Kenny Root committed
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
                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(String16(match, extra));
                    free(match);
                } else {
                    ALOGW("could not allocate match of size %zd", extra);
                }
            }
        }
        closedir(dir);

        return ::NO_ERROR;
1552 1553
    }

Kenny Root's avatar
Kenny Root committed
1554
    int32_t reset() {
1555 1556 1557
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_RESET)) {
            ALOGW("permission denied for %d: reset", callingUid);
Kenny Root's avatar
Kenny Root committed
1558 1559
            return ::PERMISSION_DENIED;
        }
1560

Kenny Root's avatar
Kenny Root committed
1561
        ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
1562

Kenny Root's avatar
Kenny Root committed
1563 1564 1565 1566
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            ALOGE("No keymaster device!");
            return ::SYSTEM_ERROR;
1567
        }
Kenny Root's avatar
Kenny Root committed
1568 1569 1570 1571

        if (device->delete_all == NULL) {
            ALOGV("keymaster device doesn't implement delete_all");
            return rc;
1572
        }
Kenny Root's avatar
Kenny Root committed
1573 1574 1575 1576

        if (device->delete_all(device)) {
            ALOGE("Problem calling keymaster's delete_all");
            return ::SYSTEM_ERROR;
1577
        }
Kenny Root's avatar
Kenny Root committed
1578 1579

        return rc;
1580 1581
    }

Kenny Root's avatar
Kenny Root committed
1582 1583 1584 1585 1586 1587 1588 1589
    /*
     * Here is the history. To improve the security, the parameters to generate the
     * master key has been changed. To make a seamless transition, we update the
     * file using the same password when the user unlock it for the first time. If
     * any thing goes wrong during the transition, the new file will not overwrite
     * the old one. This avoids permanent damages of the existing data.
     */
    int32_t password(const String16& password) {
1590 1591 1592
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_PASSWORD)) {
            ALOGW("permission denied for %d: password", callingUid);
Kenny Root's avatar
Kenny Root committed
1593 1594
            return ::PERMISSION_DENIED;
        }
1595

Kenny Root's avatar
Kenny Root committed
1596
        const String8 password8(password);
1597

Kenny Root's avatar
Kenny Root committed
1598
        switch (mKeyStore->getState(callingUid)) {
Kenny Root's avatar
Kenny Root committed
1599 1600
            case ::STATE_UNINITIALIZED: {
                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root's avatar
Kenny Root committed
1601
                return mKeyStore->initializeUser(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1602 1603 1604
            }
            case ::STATE_NO_ERROR: {
                // rewrite master key with new password.
Kenny Root's avatar
Kenny Root committed
1605
                return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1606 1607 1608
            }
            case ::STATE_LOCKED: {
                // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root's avatar
Kenny Root committed
1609
                return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1610 1611 1612 1613
            }
        }
        return ::SYSTEM_ERROR;
    }
1614

Kenny Root's avatar
Kenny Root committed
1615
    int32_t lock() {
1616 1617 1618
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_LOCK)) {
            ALOGW("permission denied for %d: lock", callingUid);
Kenny Root's avatar
Kenny Root committed
1619 1620 1621
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1622
        State state = mKeyStore->getState(callingUid);
1623
        if (state != ::STATE_NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1624 1625 1626
            ALOGD("calling lock in state: %d", state);
            return state;
        }
1627

Kenny Root's avatar
Kenny Root committed
1628
        mKeyStore->lock(callingUid);
Kenny Root's avatar
Kenny Root committed
1629
        return ::NO_ERROR;
1630
    }
1631

Kenny Root's avatar
Kenny Root committed
1632
    int32_t unlock(const String16& pw) {
1633 1634 1635
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_UNLOCK)) {
            ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root's avatar
Kenny Root committed
1636 1637 1638
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1639
        State state = mKeyStore->getState(callingUid);
1640
        if (state != ::STATE_LOCKED) {
Kenny Root's avatar
Kenny Root committed
1641 1642 1643 1644 1645 1646
            ALOGD("calling unlock when not locked");
            return state;
        }

        const String8 password8(pw);
        return password(pw);
1647 1648
    }

Kenny Root's avatar
Kenny Root committed
1649
    int32_t zero() {
1650 1651 1652
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_ZERO)) {
            ALOGW("permission denied for %d: zero", callingUid);
Kenny Root's avatar
Kenny Root committed
1653 1654
            return -1;
        }
1655

Kenny Root's avatar
Kenny Root committed
1656
        return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
1657 1658
    }

1659
    int32_t generate(const String16& name, int targetUid, int32_t flags) {
1660 1661 1662
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_INSERT)) {
            ALOGW("permission denied for %d: generate", callingUid);
Kenny Root's avatar
Kenny Root committed
1663 1664
            return ::PERMISSION_DENIED;
        }
1665

1666 1667 1668
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1669 1670 1671
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1672
        State state = mKeyStore->getState(callingUid);
1673 1674
        if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
            ALOGW("calling generate in state: %d", state);
Kenny Root's avatar
Kenny Root committed
1675 1676
            return state;
        }
1677

Kenny Root's avatar
Kenny Root committed
1678 1679 1680
        uint8_t* data;
        size_t dataLength;
        int rc;
1681

Kenny Root's avatar
Kenny Root committed
1682 1683 1684 1685
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1686

Kenny Root's avatar
Kenny Root committed
1687 1688 1689
        if (device->generate_keypair == NULL) {
            return ::SYSTEM_ERROR;
        }
1690

Kenny Root's avatar
Kenny Root committed
1691 1692 1693
        keymaster_rsa_keygen_params_t rsa_params;
        rsa_params.modulus_size = 2048;
        rsa_params.public_exponent = 0x10001;
1694

Kenny Root's avatar
Kenny Root committed
1695 1696 1697 1698
        rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
        if (rc) {
            return ::SYSTEM_ERROR;
        }
1699

Kenny Root's avatar
Kenny Root committed
1700 1701
        String8 name8(name);
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1702

Kenny Root's avatar
Kenny Root committed
1703 1704 1705
        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
        free(data);

Kenny Root's avatar
Kenny Root committed
1706
        return mKeyStore->put(filename.string(), &keyBlob, callingUid);
1707 1708
    }

1709 1710
    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
            int32_t flags) {
1711 1712 1713
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_INSERT)) {
            ALOGW("permission denied for %d: import", callingUid);
Kenny Root's avatar
Kenny Root committed
1714 1715
            return ::PERMISSION_DENIED;
        }
1716

1717 1718 1719
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1720 1721 1722
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1723
        State state = mKeyStore->getState(callingUid);
1724
        if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1725 1726 1727
            ALOGD("calling import in state: %d", state);
            return state;
        }
1728

Kenny Root's avatar
Kenny Root committed
1729
        String8 name8(name);
1730
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1731

1732
        return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
1733 1734
    }

Kenny Root's avatar
Kenny Root committed
1735 1736
    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
            size_t* outLength) {
1737 1738 1739
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_SIGN)) {
            ALOGW("permission denied for %d: saw", callingUid);
Kenny Root's avatar
Kenny Root committed
1740 1741
            return ::PERMISSION_DENIED;
        }
1742

Kenny Root's avatar
Kenny Root committed
1743 1744
        Blob keyBlob;
        String8 name8(name);
1745

1746
        ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root's avatar
Kenny Root committed
1747
        int rc;
1748

Kenny Root's avatar
Kenny Root committed
1749
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1750
                ::TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
1751 1752 1753
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1754

Kenny Root's avatar
Kenny Root committed
1755 1756 1757 1758 1759
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            ALOGE("no keymaster device; cannot sign");
            return ::SYSTEM_ERROR;
        }
1760

Kenny Root's avatar
Kenny Root committed
1761 1762 1763 1764
        if (device->sign_data == NULL) {
            ALOGE("device doesn't implement signing");
            return ::SYSTEM_ERROR;
        }
1765

Kenny Root's avatar
Kenny Root committed
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
        keymaster_rsa_sign_params_t params;
        params.digest_type = DIGEST_NONE;
        params.padding_type = PADDING_NONE;

        rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
                data, length, out, outLength);
        if (rc) {
            ALOGW("device couldn't sign data");
            return ::SYSTEM_ERROR;
        }
1776

Kenny Root's avatar
Kenny Root committed
1777
        return ::NO_ERROR;
1778 1779
    }

Kenny Root's avatar
Kenny Root committed
1780 1781
    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
            const uint8_t* signature, size_t signatureLength) {
1782 1783 1784
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_VERIFY)) {
            ALOGW("permission denied for %d: verify", callingUid);
Kenny Root's avatar
Kenny Root committed
1785 1786
            return ::PERMISSION_DENIED;
        }
1787

Kenny Root's avatar
Kenny Root committed
1788
        State state = mKeyStore->getState(callingUid);
1789
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1790 1791 1792
            ALOGD("calling verify in state: %d", state);
            return state;
        }
1793

Kenny Root's avatar
Kenny Root committed
1794 1795 1796
        Blob keyBlob;
        String8 name8(name);
        int rc;
1797

Kenny Root's avatar
Kenny Root committed
1798
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1799
                TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
1800 1801 1802
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1803

Kenny Root's avatar
Kenny Root committed
1804 1805 1806 1807
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1808

Kenny Root's avatar
Kenny Root committed
1809 1810 1811 1812 1813 1814 1815
        if (device->verify_data == NULL) {
            return ::SYSTEM_ERROR;
        }

        keymaster_rsa_sign_params_t params;
        params.digest_type = DIGEST_NONE;
        params.padding_type = PADDING_NONE;
1816

Kenny Root's avatar
Kenny Root committed
1817 1818 1819 1820 1821 1822 1823
        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
                data, dataLength, signature, signatureLength);
        if (rc) {
            return ::SYSTEM_ERROR;
        } else {
            return ::NO_ERROR;
        }
1824 1825
    }

Kenny Root's avatar
Kenny Root committed
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    /*
     * TODO: The abstraction between things stored in hardware and regular blobs
     * of data stored on the filesystem should be moved down to keystore itself.
     * Unfortunately the Java code that calls this has naming conventions that it
     * knows about. Ideally keystore shouldn't be used to store random blobs of
     * data.
     *
     * Until that happens, it's necessary to have a separate "get_pubkey" and
     * "del_key" since the Java code doesn't really communicate what it's
     * intentions are.
     */
    int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
1838 1839 1840
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GET)) {
            ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root's avatar
Kenny Root committed
1841 1842
            return ::PERMISSION_DENIED;
        }
1843

Kenny Root's avatar
Kenny Root committed
1844 1845
        Blob keyBlob;
        String8 name8(name);
1846

1847
        ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
1848

Kenny Root's avatar
Kenny Root committed
1849
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root's avatar
Kenny Root committed
1850 1851 1852 1853
                TYPE_KEY_PAIR);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1854

Kenny Root's avatar
Kenny Root committed
1855 1856 1857 1858
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1859

Kenny Root's avatar
Kenny Root committed
1860 1861 1862 1863
        if (device->get_keypair_public == NULL) {
            ALOGE("device has no get_keypair_public implementation!");
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
1864

Kenny Root's avatar
Kenny Root committed
1865 1866 1867 1868 1869
        int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
                pubkeyLength);
        if (rc) {
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
1870

Kenny Root's avatar
Kenny Root committed
1871
        return ::NO_ERROR;
Kenny Root's avatar
Kenny Root committed
1872 1873
    }

1874
    int32_t del_key(const String16& name, int targetUid) {
1875 1876 1877
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_DELETE)) {
            ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root's avatar
Kenny Root committed
1878 1879
            return ::PERMISSION_DENIED;
        }
Kenny Root's avatar
Kenny Root committed
1880

1881 1882 1883
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1884 1885 1886
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1887
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1888
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root's avatar
Kenny Root committed
1889

Kenny Root's avatar
Kenny Root committed
1890
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
1891 1892
        ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
                callingUid);
Kenny Root's avatar
Kenny Root committed
1893 1894 1895
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1896

Kenny Root's avatar
Kenny Root committed
1897
        ResponseCode rc = ::NO_ERROR;
1898

Kenny Root's avatar
Kenny Root committed
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            rc = ::SYSTEM_ERROR;
        } else {
            // A device doesn't have to implement delete_keypair.
            if (device->delete_keypair != NULL) {
                if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
                    rc = ::SYSTEM_ERROR;
                }
            }
        }
1910

Kenny Root's avatar
Kenny Root committed
1911 1912 1913
        if (rc != ::NO_ERROR) {
            return rc;
        }
1914

Kenny Root's avatar
Kenny Root committed
1915
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1916
    }
Kenny Root's avatar
Kenny Root committed
1917 1918

    int32_t grant(const String16& name, int32_t granteeUid) {
1919 1920 1921
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GRANT)) {
            ALOGW("permission denied for %d: grant", callingUid);
Kenny Root's avatar
Kenny Root committed
1922 1923 1924
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1925
        State state = mKeyStore->getState(callingUid);
1926
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1927 1928 1929 1930 1931
            ALOGD("calling grant in state: %d", state);
            return state;
        }

        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1932
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root's avatar
Kenny Root committed
1933

Kenny Root's avatar
Kenny Root committed
1934
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
1935 1936 1937
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

Kenny Root's avatar
Kenny Root committed
1938
        mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root's avatar
Kenny Root committed
1939
        return ::NO_ERROR;
1940
    }
Kenny Root's avatar
Kenny Root committed
1941 1942

    int32_t ungrant(const String16& name, int32_t granteeUid) {
1943 1944 1945
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GRANT)) {
            ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root's avatar
Kenny Root committed
1946 1947 1948
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1949
        State state = mKeyStore->getState(callingUid);
1950
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1951 1952 1953 1954 1955
            ALOGD("calling ungrant in state: %d", state);
            return state;
        }

        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1956
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root's avatar
Kenny Root committed
1957

Kenny Root's avatar
Kenny Root committed
1958
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
1959 1960 1961
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

Kenny Root's avatar
Kenny Root committed
1962
        return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1963
    }
Kenny Root's avatar
Kenny Root committed
1964 1965

    int64_t getmtime(const String16& name) {
1966 1967 1968
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GET)) {
            ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root's avatar
Kenny Root committed
1969
            return -1L;
Kenny Root's avatar
Kenny Root committed
1970 1971 1972
        }

        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1973
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root's avatar
Kenny Root committed
1974

Kenny Root's avatar
Kenny Root committed
1975 1976
        if (access(filename.string(), R_OK) == -1) {
            ALOGW("could not access %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
1977
            return -1L;
1978
        }
Kenny Root's avatar
Kenny Root committed
1979

Kenny Root's avatar
Kenny Root committed
1980
        int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root's avatar
Kenny Root committed
1981
        if (fd < 0) {
Kenny Root's avatar
Kenny Root committed
1982
            ALOGW("could not open %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
1983
            return -1L;
Kenny Root's avatar
Kenny Root committed
1984 1985 1986 1987 1988 1989
        }

        struct stat s;
        int ret = fstat(fd, &s);
        close(fd);
        if (ret == -1) {
Kenny Root's avatar
Kenny Root committed
1990
            ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
1991
            return -1L;
Kenny Root's avatar
Kenny Root committed
1992 1993
        }

Kenny Root's avatar
Kenny Root committed
1994
        return static_cast<int64_t>(s.st_mtime);
1995
    }
Kenny Root's avatar
Kenny Root committed
1996

1997 1998
    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
            int32_t destUid) {
Kenny Root's avatar
Kenny Root committed
1999
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2000 2001
        if (!has_permission(callingUid, P_DUPLICATE)) {
            ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root's avatar
Kenny Root committed
2002 2003 2004
            return -1L;
        }

Kenny Root's avatar
Kenny Root committed
2005
        State state = mKeyStore->getState(callingUid);
Kenny Root's avatar
Kenny Root committed
2006
        if (!isKeystoreUnlocked(state)) {
2007
            ALOGD("calling duplicate in state: %d", state);
Kenny Root's avatar
Kenny Root committed
2008 2009 2010
            return state;
        }

2011 2012 2013 2014
        if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
            srcUid = callingUid;
        } else if (!is_granted_to(callingUid, srcUid)) {
            ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root's avatar
Kenny Root committed
2015 2016 2017
            return ::PERMISSION_DENIED;
        }

2018 2019 2020
        if (destUid == -1) {
            destUid = callingUid;
        }
Kenny Root's avatar
Kenny Root committed
2021

2022 2023 2024 2025 2026 2027
        if (srcUid != destUid) {
            if (static_cast<uid_t>(srcUid) != callingUid) {
                ALOGD("can only duplicate from caller to other or to same uid: "
                      "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
                return ::PERMISSION_DENIED;
            }
Kenny Root's avatar
Kenny Root committed
2028

2029 2030 2031 2032
            if (!is_granted_to(callingUid, destUid)) {
                ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
                return ::PERMISSION_DENIED;
            }
Kenny Root's avatar
Kenny Root committed
2033 2034
        }

2035
        String8 source8(srcKey);
Kenny Root's avatar
Kenny Root committed
2036
        String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
2037 2038

        String8 target8(destKey);
Kenny Root's avatar
Kenny Root committed
2039
        String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root's avatar
Kenny Root committed
2040

Kenny Root's avatar
Kenny Root committed
2041 2042
        if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
            ALOGD("destination already exists: %s", targetFile.string());
Kenny Root's avatar
Kenny Root committed
2043 2044 2045
            return ::SYSTEM_ERROR;
        }

2046
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
2047 2048
        ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
                callingUid);
2049 2050
        if (responseCode != ::NO_ERROR) {
            return responseCode;
Kenny Root's avatar
Kenny Root committed
2051
        }
2052

Kenny Root's avatar
Kenny Root committed
2053
        return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root's avatar
Kenny Root committed
2054 2055
    }

2056 2057 2058 2059
    int32_t is_hardware_backed() {
        return mKeyStore->isHardwareBacked() ? 1 : 0;
    }

2060 2061 2062 2063 2064 2065 2066
    int32_t clear_uid(int64_t targetUid) {
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_CLEAR_UID)) {
            ALOGW("permission denied for %d: clear_uid", callingUid);
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
2067
        State state = mKeyStore->getState(callingUid);
2068 2069 2070 2071 2072 2073 2074
        if (!isKeystoreUnlocked(state)) {
            ALOGD("calling clear_uid in state: %d", state);
            return state;
        }

        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
Kenny Root's avatar
Kenny Root committed
2075
            ALOGW("can't get keymaster device");
2076 2077 2078
            return ::SYSTEM_ERROR;
        }

Kenny Root's avatar
Kenny Root committed
2079 2080
        UserState* userState = mKeyStore->getUserState(callingUid);
        DIR* dir = opendir(userState->getUserDirName());
2081
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
2082
            ALOGW("can't open user directory: %s", strerror(errno));
2083 2084 2085
            return ::SYSTEM_ERROR;
        }

Kenny Root's avatar
Kenny Root committed
2086 2087
        char prefix[NAME_MAX];
        int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
2088 2089 2090 2091 2092

        ResponseCode rc = ::NO_ERROR;

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
2093 2094
            // We only care about files.
            if (file->d_type != DT_REG) {
2095 2096 2097
                continue;
            }

Kenny Root's avatar
Kenny Root committed
2098 2099 2100 2101 2102 2103 2104 2105
            // Skip anything that starts with a "."
            if (file->d_name[0] == '.') {
                continue;
            }

            if (strncmp(prefix, file->d_name, n)) {
                continue;
            }
2106

Kenny Root's avatar
Kenny Root committed
2107
            String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
2108
            Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
2109 2110 2111
            if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
                    != ::NO_ERROR) {
                ALOGW("couldn't open %s", filename.string());
2112 2113 2114 2115 2116 2117 2118 2119
                continue;
            }

            if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
                // A device doesn't have to implement delete_keypair.
                if (device->delete_keypair != NULL) {
                    if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
                        rc = ::SYSTEM_ERROR;
Kenny Root's avatar
Kenny Root committed
2120
                        ALOGW("device couldn't remove %s", filename.string());
2121 2122 2123 2124
                    }
                }
            }

Kenny Root's avatar
Kenny Root committed
2125
            if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
2126
                rc = ::SYSTEM_ERROR;
Kenny Root's avatar
Kenny Root committed
2127
                ALOGW("couldn't unlink %s", filename.string());
2128 2129 2130 2131 2132 2133 2134
            }
        }
        closedir(dir);

        return rc;
    }

Kenny Root's avatar
Kenny Root committed
2135
private:
2136 2137 2138 2139 2140 2141 2142 2143 2144
    inline bool isKeystoreUnlocked(State state) {
        switch (state) {
        case ::STATE_NO_ERROR:
            return true;
        case ::STATE_UNINITIALIZED:
        case ::STATE_LOCKED:
            return false;
        }
        return false;
2145
    }
Kenny Root's avatar
Kenny Root committed
2146 2147 2148 2149 2150

    ::KeyStore* mKeyStore;
};

}; // namespace android
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165

int main(int argc, char* argv[]) {
    if (argc < 2) {
        ALOGE("A directory must be specified!");
        return 1;
    }
    if (chdir(argv[1]) == -1) {
        ALOGE("chdir: %s: %s", argv[1], strerror(errno));
        return 1;
    }

    Entropy entropy;
    if (!entropy.open()) {
        return 1;
    }
2166 2167 2168 2169 2170 2171 2172 2173

    keymaster_device_t* dev;
    if (keymaster_device_initialize(&dev)) {
        ALOGE("keystore keymaster could not be initialized; exiting");
        return 1;
    }

    KeyStore keyStore(&entropy, dev);
Kenny Root's avatar
Kenny Root committed
2174
    keyStore.initialize();
Kenny Root's avatar
Kenny Root committed
2175 2176 2177 2178 2179 2180
    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
    android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
    android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
    if (ret != android::OK) {
        ALOGE("Couldn't register binder service!");
        return -1;
2181
    }
2182

Kenny Root's avatar
Kenny Root committed
2183 2184 2185 2186 2187
    /*
     * We're the only thread in existence, so we're just going to process
     * Binder transaction as a single-threaded program.
     */
    android::IPCThreadState::self()->joinThreadPool();
2188

Kenny Root's avatar
Kenny Root committed
2189
    keymaster_device_release(dev);
2190 2191
    return 1;
}