keystore.cpp 79.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
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <arpa/inet.h>
36
#include <string.h>
37 38

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

44 45
#include <hardware/keymaster.h>

46 47
#include <keymaster/softkeymaster.h>

Kenny Root's avatar
Kenny Root committed
48
#include <UniquePtr.h>
Kenny Root's avatar
Kenny Root committed
49 50
#include <utils/String8.h>
#include <utils/Vector.h>
51

Kenny Root's avatar
Kenny Root committed
52 53 54 55
#include <keystore/IKeystoreService.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>

56 57 58 59
#include <cutils/log.h>
#include <cutils/sockets.h>
#include <private/android_filesystem_config.h>

Kenny Root's avatar
Kenny Root committed
60
#include <keystore/keystore.h>
61

62 63
#include <selinux/android.h>

64 65
#include "defaults.h"

66 67 68 69 70 71 72 73 74 75
/* 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

76

77 78 79 80 81 82 83
struct BIGNUM_Delete {
    void operator()(BIGNUM* p) const {
        BN_free(p);
    }
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
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;


106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
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
134 135 136 137 138 139
/***************
 * PERMISSIONS *
 ***************/

/* Here are the permissions, actions, users, and the main function. */
typedef enum {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    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,
155
    P_CLEAR_UID = 1 << 15,
Kenny Root's avatar
Kenny Root committed
156 157
} perm_t;

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
/* perm_labels associcated with keystore_key SELinux class verbs. */
const char *perm_labels[] = {
    "test",
    "get",
    "insert",
    "delete",
    "exist",
    "saw",
    "reset",
    "password",
    "lock",
    "unlock",
    "zero",
    "sign",
    "verify",
    "grant",
    "duplicate",
    "clear_uid"
};

Kenny Root's avatar
Kenny Root committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
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);

200 201 202 203 204 205 206 207 208 209 210 211
static char *tctx;

static const char *get_perm_label(perm_t perm) {
    unsigned int index = ffs(perm);
    if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
        return perm_labels[index - 1];
    } else {
        ALOGE("Keystore: Failed to retrieve permission label.\n");
        abort();
    }
}

Kenny Root's avatar
Kenny Root committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
/**
 * 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;
}

228
static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root's avatar
Kenny Root committed
229 230 231 232 233
    // All system users are equivalent for multi-user support.
    if (get_app_id(uid) == AID_SYSTEM) {
        uid = AID_SYSTEM;
    }

234 235 236 237 238 239 240 241 242 243 244 245 246
    char *sctx = NULL;
    const char *selinux_class = "keystore_key";
    const char *str_perm = get_perm_label(perm);

    if (!str_perm) {
        return false;
    }

    if (getpidcon(spid, &sctx) != 0) {
        ALOGE("SELinux: Failed to get source pid context.\n");
        return false;
    }

Kenny Root's avatar
Kenny Root committed
247 248 249
    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) {
250 251 252 253
            bool result = (user.perms & perm) && (selinux_check_access(sctx,
                        tctx, selinux_class, str_perm, NULL) == 0);
            freecon(sctx);
            return result;
Kenny Root's avatar
Kenny Root committed
254 255 256
        }
    }

257 258 259 260
    bool result = (DEFAULT_PERMS & perm) && (selinux_check_access(sctx,
            tctx, selinux_class, str_perm, NULL) == 0);
    freecon(sctx);
    return result;
Kenny Root's avatar
Kenny Root committed
261 262
}

263 264 265 266 267
/**
 * 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
268 269 270 271 272 273 274 275 276 277 278
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;
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/**
 * 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;
}

294 295 296 297 298 299 300
/* 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
301 302 303 304 305 306 307 308 309 310 311
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
312 313 314
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();
315
    for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root's avatar
Kenny Root committed
316
        if (*in < '0' || *in > '~') {
317 318 319
            *out = '+' + (*in >> 6);
            *++out = '0' + (*in & 0x3F);
            ++length;
Kenny Root's avatar
Kenny Root committed
320 321
        } else {
            *out = *in;
322 323 324
        }
    }
    *out = '\0';
325 326 327
    return length;
}

Kenny Root's avatar
Kenny Root committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
/*
 * 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;
358
        } else {
Kenny Root's avatar
Kenny Root committed
359
            *out++ = *in;
360 361 362 363 364 365 366 367
        }
    }
    *out = '\0';
}

static size_t readFully(int fd, uint8_t* data, size_t size) {
    size_t remaining = size;
    while (remaining > 0) {
368
        ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root's avatar
Kenny Root committed
369
        if (n <= 0) {
370
            return size - remaining;
371 372 373 374 375 376 377 378 379 380
        }
        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) {
381 382 383 384
        ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
        if (n < 0) {
            ALOGW("write failed: %s", strerror(errno));
            return size - remaining;
385 386 387 388 389 390 391 392 393 394 395
        }
        data += n;
        remaining -= n;
    }
    return size;
}

class Entropy {
public:
    Entropy() : mRandom(-1) {}
    ~Entropy() {
396
        if (mRandom >= 0) {
397 398 399 400 401 402
            close(mRandom);
        }
    }

    bool open() {
        const char* randomDevice = "/dev/urandom";
403 404
        mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
        if (mRandom < 0) {
405 406 407 408 409 410
            ALOGE("open: %s: %s", randomDevice, strerror(errno));
            return false;
        }
        return true;
    }

Kenny Root's avatar
Kenny Root committed
411
    bool generate_random_data(uint8_t* data, size_t size) const {
412 413 414 415 416 417 418 419 420 421 422
        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
423
 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
424
 * the second is the blob's type, and the third byte is flags. Fields other
425 426 427
 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
 * and decryptBlob(). Thus they should not be accessed from outside. */

428 429 430 431 432 433 434 435 436 437 438 439 440 441
/* ** 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))
 */
442
struct __attribute__((packed)) blob {
443 444
    uint8_t version;
    uint8_t type;
445
    uint8_t flags;
446 447
    uint8_t info;
    uint8_t vector[AES_BLOCK_SIZE];
448
    uint8_t encrypted[0]; // Marks offset to encrypted data.
449
    uint8_t digest[MD5_DIGEST_LENGTH];
450
    uint8_t digested[0]; // Marks offset to digested data.
451 452 453 454
    int32_t length; // in network byte order when encrypted
    uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
};

455
typedef enum {
456
    TYPE_ANY = 0, // meta type that matches anything
457 458 459 460 461
    TYPE_GENERIC = 1,
    TYPE_MASTER_KEY = 2,
    TYPE_KEY_PAIR = 3,
} BlobType;

462
static const uint8_t CURRENT_BLOB_VERSION = 2;
463

464 465
class Blob {
public:
Kenny Root's avatar
Kenny Root committed
466 467
    Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
            BlobType type) {
468 469 470 471 472
        mBlob.length = valueLength;
        memcpy(mBlob.value, value, valueLength);

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

Kenny Root's avatar
Kenny Root committed
474
        mBlob.version = CURRENT_BLOB_VERSION;
475
        mBlob.type = uint8_t(type);
476

477 478 479 480 481
        if (type == TYPE_MASTER_KEY) {
            mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
        } else {
            mBlob.flags = KEYSTORE_FLAG_NONE;
        }
482 483 484 485 486 487 488 489
    }

    Blob(blob b) {
        mBlob = b;
    }

    Blob() {}

Kenny Root's avatar
Kenny Root committed
490
    const uint8_t* getValue() const {
491 492 493
        return mBlob.value;
    }

Kenny Root's avatar
Kenny Root committed
494
    int32_t getLength() const {
495 496 497
        return mBlob.length;
    }

Kenny Root's avatar
Kenny Root committed
498 499 500 501 502
    const uint8_t* getInfo() const {
        return mBlob.value + mBlob.length;
    }

    uint8_t getInfoLength() const {
503 504 505
        return mBlob.info;
    }

506 507 508 509
    uint8_t getVersion() const {
        return mBlob.version;
    }

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    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;
        }
    }

526 527 528 529 530 531 532 533 534 535 536 537
    bool isFallback() const {
        return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
    }

    void setFallback(bool fallback) {
        if (fallback) {
            mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
        } else {
            mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
        }
    }

538 539 540 541 542 543 544 545 546 547 548 549
    void setVersion(uint8_t version) {
        mBlob.version = version;
    }

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

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

550 551 552 553 554 555 556 557 558 559 560 561
    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;
            }
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
        }

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

578 579 580 581 582 583 584 585
        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);
        }
586 587 588 589 590

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

        const char* tmpFileName = ".tmp";
591 592 593 594
        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));
595 596 597 598 599 600 601
            return SYSTEM_ERROR;
        }
        size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
        if (close(out) != 0) {
            return SYSTEM_ERROR;
        }
        if (writtenBytes != fileLength) {
602
            ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
603 604 605
            unlink(tmpFileName);
            return SYSTEM_ERROR;
        }
606 607 608 609 610
        if (rename(tmpFileName, filename) == -1) {
            ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
            return SYSTEM_ERROR;
        }
        return NO_ERROR;
611 612
    }

613 614
    ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
        ALOGV("reading blob %s", filename);
615 616
        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
        if (in < 0) {
617 618 619 620 621 622 623 624 625
            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;
        }
626 627 628 629 630

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

631 632 633 634 635 636
        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
        if (fileLength < headerLength) {
            return VALUE_CORRUPTED;
        }

        ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
637
        if (encryptedLength < 0) {
638 639
            return VALUE_CORRUPTED;
        }
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

        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;
657 658 659 660 661 662 663 664 665 666 667
        }

        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
668
        return ::NO_ERROR;
669 670 671 672 673 674
    }

private:
    struct blob mBlob;
};

Kenny Root's avatar
Kenny Root committed
675 676 677 678 679 680
class UserState {
public:
    UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
        asprintf(&mUserDir, "user_%u", mUserId);
        asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
    }
681

Kenny Root's avatar
Kenny Root committed
682 683 684 685
    ~UserState() {
        free(mUserDir);
        free(mMasterKeyFile);
    }
686

Kenny Root's avatar
Kenny Root committed
687 688 689 690 691 692 693
    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) {
694 695 696 697
            setState(STATE_LOCKED);
        } else {
            setState(STATE_UNINITIALIZED);
        }
698

Kenny Root's avatar
Kenny Root committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        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;
        }
719 720
    }

Kenny Root's avatar
Kenny Root committed
721
    State getState() const {
722 723 724
        return mState;
    }

Kenny Root's avatar
Kenny Root committed
725
    int8_t getRetry() const {
726 727 728
        return mRetry;
    }

Kenny Root's avatar
Kenny Root committed
729 730 731 732 733
    void zeroizeMasterKeysInMemory() {
        memset(mMasterKey, 0, sizeof(mMasterKey));
        memset(mSalt, 0, sizeof(mSalt));
        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
734 735
    }

Kenny Root's avatar
Kenny Root committed
736 737
    ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
        if (!generateMasterKey(entropy)) {
738 739
            return SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
740
        ResponseCode response = writeMasterKey(pw, entropy);
741 742 743 744
        if (response != NO_ERROR) {
            return response;
        }
        setupMasterKeys();
Kenny Root's avatar
Kenny Root committed
745
        return ::NO_ERROR;
746 747
    }

Kenny Root's avatar
Kenny Root committed
748
    ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
749 750 751 752
        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);
753
        Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
754
        return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
755 756
    }

Kenny Root's avatar
Kenny Root committed
757 758
    ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
        int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
759
        if (in < 0) {
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
            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);
782 783
        ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
                STATE_NO_ERROR);
784
        if (response == SYSTEM_ERROR) {
785
            return response;
786 787 788 789
        }
        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
790
                if (!generateSalt(entropy)) {
791 792
                    return SYSTEM_ERROR;
                }
Kenny Root's avatar
Kenny Root committed
793
                response = writeMasterKey(pw, entropy);
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
            }
            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
815 816 817
    AES_KEY* getEncryptionKey() {
        return &mMasterKeyEncryption;
    }
818

Kenny Root's avatar
Kenny Root committed
819 820 821
    AES_KEY* getDecryptionKey() {
        return &mMasterKeyDecryption;
    }
822

Kenny Root's avatar
Kenny Root committed
823 824
    bool reset() {
        DIR* dir = opendir(getUserDirName());
825
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
826
            ALOGW("couldn't open user directory: %s", strerror(errno));
827 828
            return false;
        }
Kenny Root's avatar
Kenny Root committed
829 830

        struct dirent* file;
831
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
            // 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);
855 856 857 858 859
        }
        closedir(dir);
        return true;
    }

Kenny Root's avatar
Kenny Root committed
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 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
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;
        }
haitao fang's avatar
haitao fang committed
937
        mGrants.clear();
Kenny Root's avatar
Kenny Root committed
938 939 940 941 942

        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
                it != mMasterKeys.end(); it++) {
            delete *it;
        }
haitao fang's avatar
haitao fang committed
943
        mMasterKeys.clear();
Kenny Root's avatar
Kenny Root committed
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    }

    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) {
981
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
982 983 984 985 986
        encode_key(encoded, keyName);
        return android::String8(encoded);
    }

    android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
987
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
988 989 990 991 992
        encode_key(encoded, keyName);
        return android::String8::format("%u_%s", uid, encoded);
    }

    android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
993
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        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());
1013 1014 1015 1016 1017
        struct dirent* file;
        if (!dir) {
            return true;
        }
        bool result = true;
Kenny Root's avatar
Kenny Root committed
1018 1019 1020 1021

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

1022
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            // 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)) {
1034 1035 1036 1037 1038 1039 1040 1041
                result = false;
                break;
            }
        }
        closedir(dir);
        return result;
    }

Kenny Root's avatar
Kenny Root committed
1042 1043 1044 1045
    void lock(uid_t uid) {
        UserState* userState = getUserState(uid);
        userState->zeroizeMasterKeysInMemory();
        userState->setState(STATE_LOCKED);
1046 1047
    }

Kenny Root's avatar
Kenny Root committed
1048 1049
    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
        UserState* userState = getUserState(uid);
1050 1051
        ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                userState->getState());
1052 1053 1054 1055 1056
        if (rc != NO_ERROR) {
            return rc;
        }

        const uint8_t version = keyBlob->getVersion();
Kenny Root's avatar
Kenny Root committed
1057
        if (version < CURRENT_BLOB_VERSION) {
Kenny Root's avatar
Kenny Root committed
1058 1059 1060 1061
            /* 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
1062 1063
            if (upgradeBlob(filename, keyBlob, version, type, uid)) {
                if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
1064 1065
                        || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                                userState->getState())) != NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1066 1067 1068
                    return rc;
                }
            }
1069 1070
        }

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
        /*
         * This will upgrade software-backed keys to hardware-backed keys when
         * the HAL for the device supports the newer key types.
         */
        if (rc == NO_ERROR && type == TYPE_KEY_PAIR
                && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
                && keyBlob->isFallback()) {
            ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
                    uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);

            // The HAL allowed the import, reget the key to have the "fresh"
            // version.
            if (imported == NO_ERROR) {
                rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
            }
        }

1088
        if (type != TYPE_ANY && keyBlob->getType() != type) {
1089 1090 1091 1092 1093
            ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
            return KEY_NOT_FOUND;
        }

        return rc;
1094 1095
    }

Kenny Root's avatar
Kenny Root committed
1096 1097
    ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
        UserState* userState = getUserState(uid);
1098 1099
        return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
                mEntropy);
1100 1101
    }

Kenny Root's avatar
Kenny Root committed
1102
    void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root's avatar
Kenny Root committed
1103 1104 1105
        const grant_t* existing = getGrant(filename, granteeUid);
        if (existing == NULL) {
            grant_t* grant = new grant_t;
Kenny Root's avatar
Kenny Root committed
1106
            grant->uid = granteeUid;
1107
            grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root's avatar
Kenny Root committed
1108
            mGrants.add(grant);
1109 1110 1111
        }
    }

Kenny Root's avatar
Kenny Root committed
1112
    bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root's avatar
Kenny Root committed
1113 1114 1115 1116 1117 1118 1119 1120
        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;
            }
1121 1122 1123 1124
        }
        return false;
    }

1125 1126
    bool hasGrant(const char* filename, const uid_t uid) const {
        return getGrant(filename, uid) != NULL;
1127 1128
    }

1129 1130
    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
            int32_t flags) {
1131 1132 1133 1134 1135 1136 1137 1138 1139
        uint8_t* data;
        size_t dataLength;
        int rc;

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

1140
        bool isFallback = false;
Kenny Root's avatar
Kenny Root committed
1141
        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
1142
        if (rc) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
            // If this is an old device HAL, try to fall back to an old version
            if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
                rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
                isFallback = true;
            }

            if (rc) {
                ALOGE("Error while importing keypair: %d", rc);
                return SYSTEM_ERROR;
            }
1153 1154 1155 1156 1157
        }

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

1158
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1159
        keyBlob.setFallback(isFallback);
1160

Kenny Root's avatar
Kenny Root committed
1161
        return put(filename, &keyBlob, uid);
1162 1163
    }

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    bool isHardwareBacked(const android::String16& keyType) const {
        if (mDevice == NULL) {
            ALOGW("can't get keymaster device");
            return false;
        }

        if (sRSAKeyType == keyType) {
            return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
        } else {
            return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
                    && (mDevice->common.module->module_api_version
                            >= KEYMASTER_MODULE_API_VERSION_0_2);
        }
1177 1178
    }

Kenny Root's avatar
Kenny Root committed
1179 1180
    ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
            const BlobType type) {
1181
        android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
1182

Kenny Root's avatar
Kenny Root committed
1183 1184 1185 1186
        ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
        if (responseCode == NO_ERROR) {
            return responseCode;
        }
1187

Kenny Root's avatar
Kenny Root committed
1188 1189 1190
        // If this is one of the legacy UID->UID mappings, use it.
        uid_t euid = get_keystore_euid(uid);
        if (euid != uid) {
1191
            filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root's avatar
Kenny Root committed
1192 1193 1194 1195 1196
            responseCode = get(filepath8.string(), keyBlob, type, uid);
            if (responseCode == NO_ERROR) {
                return responseCode;
            }
        }
1197

Kenny Root's avatar
Kenny Root committed
1198
        // They might be using a granted key.
1199
        android::String8 filename8 = getKeyName(keyName);
Kenny Root's avatar
Kenny Root committed
1200
        char* end;
1201
        strtoul(filename8.string(), &end, 10);
Kenny Root's avatar
Kenny Root committed
1202 1203 1204
        if (end[0] != '_' || end[1] == 0) {
            return KEY_NOT_FOUND;
        }
1205 1206
        filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
                filename8.string());
Kenny Root's avatar
Kenny Root committed
1207 1208
        if (!hasGrant(filepath8.string(), uid)) {
            return responseCode;
1209 1210
        }

Kenny Root's avatar
Kenny Root committed
1211 1212
        // It is a granted key. Try to load it.
        return get(filepath8.string(), keyBlob, type, uid);
1213 1214
    }

Kenny Root's avatar
Kenny Root committed
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    /**
     * 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;
            }
1227
        }
Kenny Root's avatar
Kenny Root committed
1228 1229 1230 1231 1232 1233 1234 1235

        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);
1236
        }
Kenny Root's avatar
Kenny Root committed
1237 1238
        mMasterKeys.add(userState);
        return userState;
1239 1240
    }

Kenny Root's avatar
Kenny Root committed
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
    /**
     * 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;
            }
        }
1254

Kenny Root's avatar
Kenny Root committed
1255
        return NULL;
1256 1257
    }

Kenny Root's avatar
Kenny Root committed
1258 1259 1260
private:
    static const char* sOldMasterKey;
    static const char* sMetaDataFile;
1261
    static const android::String16 sRSAKeyType;
Kenny Root's avatar
Kenny Root committed
1262
    Entropy* mEntropy;
Kenny Root's avatar
Kenny Root committed
1263

Kenny Root's avatar
Kenny Root committed
1264
    keymaster_device_t* mDevice;
1265

Kenny Root's avatar
Kenny Root committed
1266 1267 1268
    android::Vector<UserState*> mMasterKeys;

    android::Vector<grant_t*> mGrants;
1269

Kenny Root's avatar
Kenny Root committed
1270 1271 1272
    typedef struct {
        uint32_t version;
    } keystore_metadata_t;
1273

Kenny Root's avatar
Kenny Root committed
1274 1275 1276 1277 1278 1279
    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;
1280
            if (grant->uid == uid
Kenny Root's avatar
Kenny Root committed
1281
                    && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1282 1283 1284 1285 1286 1287
                return grant;
            }
        }
        return NULL;
    }

1288 1289 1290 1291
    /**
     * Upgrade code. This will upgrade the key from the current version
     * to whatever is newest.
     */
Kenny Root's avatar
Kenny Root committed
1292 1293
    bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
            const BlobType type, uid_t uid) {
1294 1295 1296 1297 1298 1299 1300 1301 1302
        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
1303
                importBlobAsKey(blob, filename, uid);
1304 1305 1306 1307 1308
            }
            version = 1;
            updated = true;
        }

1309 1310 1311 1312 1313 1314 1315 1316 1317
        /* From V1 -> V2: All old keys were encrypted */
        if (version == 1) {
            ALOGV("upgrading to version 2");

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

1318 1319 1320
        /*
         * If we've updated, set the key blob to the right version
         * and write it.
Kenny Root's avatar
Kenny Root committed
1321
         */
1322 1323 1324 1325
        if (updated) {
            ALOGV("updated and writing file %s", filename);
            blob->setVersion(version);
        }
Kenny Root's avatar
Kenny Root committed
1326 1327

        return updated;
1328 1329 1330 1331 1332 1333 1334 1335
    }

    /**
     * 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
1336
    ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
        // 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;
        }

1357 1358
        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
        uint8_t* tmp = pkcs8key.get();
1359 1360 1361 1362 1363
        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
            ALOGE("Couldn't convert to PKCS#8");
            return SYSTEM_ERROR;
        }

1364 1365
        ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
                blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1366 1367 1368 1369
        if (rc != NO_ERROR) {
            return rc;
        }

Kenny Root's avatar
Kenny Root committed
1370
        return get(filename, blob, TYPE_KEY_PAIR, uid);
1371
    }
1372

Kenny Root's avatar
Kenny Root committed
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
    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);
1384 1385
    }

Kenny Root's avatar
Kenny Root committed
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    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));
1398
        }
Kenny Root's avatar
Kenny Root committed
1399 1400
        close(out);
        rename(tmpFileName, sMetaDataFile);
1401 1402
    }

Kenny Root's avatar
Kenny Root committed
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    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;
1472
    }
Kenny Root's avatar
Kenny Root committed
1473
};
1474

Kenny Root's avatar
Kenny Root committed
1475 1476
const char* KeyStore::sOldMasterKey = ".masterkey";
const char* KeyStore::sMetaDataFile = ".metadata";
1477

1478 1479
const android::String16 KeyStore::sRSAKeyType("RSA");

Kenny Root's avatar
Kenny Root committed
1480 1481 1482 1483 1484 1485 1486
namespace android {
class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
public:
    KeyStoreProxy(KeyStore* keyStore)
        : mKeyStore(keyStore)
    {
    }
1487

Kenny Root's avatar
Kenny Root committed
1488 1489 1490
    void binderDied(const wp<IBinder>&) {
        ALOGE("binder death detected");
    }
1491

Kenny Root's avatar
Kenny Root committed
1492
    int32_t test() {
1493
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1494 1495
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_TEST, spid)) {
1496
            ALOGW("permission denied for %d: test", callingUid);
Kenny Root's avatar
Kenny Root committed
1497 1498
            return ::PERMISSION_DENIED;
        }
1499

Kenny Root's avatar
Kenny Root committed
1500
        return mKeyStore->getState(callingUid);
1501 1502
    }

Kenny Root's avatar
Kenny Root committed
1503
    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
1504
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1505 1506
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_GET, spid)) {
1507
            ALOGW("permission denied for %d: get", callingUid);
Kenny Root's avatar
Kenny Root committed
1508 1509
            return ::PERMISSION_DENIED;
        }
1510

Kenny Root's avatar
Kenny Root committed
1511 1512
        String8 name8(name);
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
1513
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1514
                TYPE_GENERIC);
Kenny Root's avatar
Kenny Root committed
1515
        if (responseCode != ::NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1516
            ALOGW("Could not read %s", name8.string());
Kenny Root's avatar
Kenny Root committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
            *item = NULL;
            *itemLength = 0;
            return responseCode;
        }

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

        return ::NO_ERROR;
1527 1528
    }

1529 1530
    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
            int32_t flags) {
1531
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1532 1533
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_INSERT, spid)) {
1534
            ALOGW("permission denied for %d: insert", callingUid);
Kenny Root's avatar
Kenny Root committed
1535 1536 1537
            return ::PERMISSION_DENIED;
        }

1538 1539 1540 1541 1542 1543
        State state = mKeyStore->getState(callingUid);
        if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
            ALOGD("calling get in state: %d", state);
            return state;
        }

1544 1545 1546
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1547 1548 1549
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1550
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1551
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
1552 1553

        Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1554 1555
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);

1556
        return mKeyStore->put(filename.string(), &keyBlob, targetUid);
1557 1558
    }

1559
    int32_t del(const String16& name, int targetUid) {
1560
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1561 1562
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_DELETE, spid)) {
1563
            ALOGW("permission denied for %d: del", callingUid);
Kenny Root's avatar
Kenny Root committed
1564 1565 1566
            return ::PERMISSION_DENIED;
        }

1567 1568 1569
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1570 1571 1572
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1573
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1574
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1575

Kenny Root's avatar
Kenny Root committed
1576
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
1577
        ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1578
                targetUid);
Kenny Root's avatar
Kenny Root committed
1579 1580 1581 1582
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1583 1584
    }

1585
    int32_t exist(const String16& name, int targetUid) {
1586
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1587 1588
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_EXIST, spid)) {
1589
            ALOGW("permission denied for %d: exist", callingUid);
Kenny Root's avatar
Kenny Root committed
1590 1591 1592
            return ::PERMISSION_DENIED;
        }

1593 1594 1595
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1596 1597 1598
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1599
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1600
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
1601

Kenny Root's avatar
Kenny Root committed
1602
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
1603 1604 1605
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }
        return ::NO_ERROR;
1606 1607
    }

1608
    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1609
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1610 1611
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_SAW, spid)) {
1612
            ALOGW("permission denied for %d: saw", callingUid);
Kenny Root's avatar
Kenny Root committed
1613 1614 1615
            return ::PERMISSION_DENIED;
        }

1616 1617 1618
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1619 1620 1621
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1622 1623
        UserState* userState = mKeyStore->getUserState(targetUid);
        DIR* dir = opendir(userState->getUserDirName());
Kenny Root's avatar
Kenny Root committed
1624
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
1625
            ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root's avatar
Kenny Root committed
1626 1627 1628 1629
            return ::SYSTEM_ERROR;
        }

        const String8 prefix8(prefix);
Kenny Root's avatar
Kenny Root committed
1630 1631
        String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
        size_t n = filename.length();
Kenny Root's avatar
Kenny Root committed
1632 1633 1634

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
            // 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
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                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;
1663 1664
    }

Kenny Root's avatar
Kenny Root committed
1665
    int32_t reset() {
1666
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1667 1668
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_RESET, spid)) {
1669
            ALOGW("permission denied for %d: reset", callingUid);
Kenny Root's avatar
Kenny Root committed
1670 1671
            return ::PERMISSION_DENIED;
        }
1672

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

Kenny Root's avatar
Kenny Root committed
1675 1676 1677 1678
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            ALOGE("No keymaster device!");
            return ::SYSTEM_ERROR;
1679
        }
Kenny Root's avatar
Kenny Root committed
1680 1681 1682 1683

        if (device->delete_all == NULL) {
            ALOGV("keymaster device doesn't implement delete_all");
            return rc;
1684
        }
Kenny Root's avatar
Kenny Root committed
1685 1686 1687 1688

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

        return rc;
1692 1693
    }

Kenny Root's avatar
Kenny Root committed
1694 1695 1696 1697 1698 1699 1700 1701
    /*
     * 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) {
1702
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1703 1704
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_PASSWORD, spid)) {
1705
            ALOGW("permission denied for %d: password", callingUid);
Kenny Root's avatar
Kenny Root committed
1706 1707
            return ::PERMISSION_DENIED;
        }
1708

Kenny Root's avatar
Kenny Root committed
1709
        const String8 password8(password);
1710

Kenny Root's avatar
Kenny Root committed
1711
        switch (mKeyStore->getState(callingUid)) {
Kenny Root's avatar
Kenny Root committed
1712 1713
            case ::STATE_UNINITIALIZED: {
                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root's avatar
Kenny Root committed
1714
                return mKeyStore->initializeUser(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1715 1716 1717
            }
            case ::STATE_NO_ERROR: {
                // rewrite master key with new password.
Kenny Root's avatar
Kenny Root committed
1718
                return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1719 1720 1721
            }
            case ::STATE_LOCKED: {
                // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root's avatar
Kenny Root committed
1722
                return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1723 1724 1725 1726
            }
        }
        return ::SYSTEM_ERROR;
    }
1727

Kenny Root's avatar
Kenny Root committed
1728
    int32_t lock() {
1729
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1730 1731
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_LOCK, spid)) {
1732
            ALOGW("permission denied for %d: lock", callingUid);
Kenny Root's avatar
Kenny Root committed
1733 1734 1735
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1736
        State state = mKeyStore->getState(callingUid);
1737
        if (state != ::STATE_NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1738 1739 1740
            ALOGD("calling lock in state: %d", state);
            return state;
        }
1741

Kenny Root's avatar
Kenny Root committed
1742
        mKeyStore->lock(callingUid);
Kenny Root's avatar
Kenny Root committed
1743
        return ::NO_ERROR;
1744
    }
1745

Kenny Root's avatar
Kenny Root committed
1746
    int32_t unlock(const String16& pw) {
1747
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1748 1749
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_UNLOCK, spid)) {
1750
            ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root's avatar
Kenny Root committed
1751 1752 1753
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1754
        State state = mKeyStore->getState(callingUid);
1755
        if (state != ::STATE_LOCKED) {
Kenny Root's avatar
Kenny Root committed
1756 1757 1758 1759 1760 1761
            ALOGD("calling unlock when not locked");
            return state;
        }

        const String8 password8(pw);
        return password(pw);
1762 1763
    }

Kenny Root's avatar
Kenny Root committed
1764
    int32_t zero() {
1765
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1766 1767
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_ZERO, spid)) {
1768
            ALOGW("permission denied for %d: zero", callingUid);
Kenny Root's avatar
Kenny Root committed
1769 1770
            return -1;
        }
1771

Kenny Root's avatar
Kenny Root committed
1772
        return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
1773 1774
    }

1775 1776
    int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
            int32_t flags, Vector<sp<KeystoreArg> >* args) {
1777
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1778 1779
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_INSERT, spid)) {
1780
            ALOGW("permission denied for %d: generate", callingUid);
Kenny Root's avatar
Kenny Root committed
1781 1782
            return ::PERMISSION_DENIED;
        }
1783

1784 1785 1786
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1787 1788 1789
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1790
        State state = mKeyStore->getState(callingUid);
1791 1792
        if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
            ALOGW("calling generate in state: %d", state);
Kenny Root's avatar
Kenny Root committed
1793 1794
            return state;
        }
1795

Kenny Root's avatar
Kenny Root committed
1796 1797 1798
        uint8_t* data;
        size_t dataLength;
        int rc;
1799
        bool isFallback = false;
1800

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

Kenny Root's avatar
Kenny Root committed
1806 1807 1808
        if (device->generate_keypair == NULL) {
            return ::SYSTEM_ERROR;
        }
1809

1810
        if (keyType == EVP_PKEY_DSA) {
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
            keymaster_dsa_keygen_params_t dsa_params;
            memset(&dsa_params, '\0', sizeof(dsa_params));

            if (keySize == -1) {
                keySize = DSA_DEFAULT_KEY_SIZE;
            } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
                    || keySize > DSA_MAX_KEY_SIZE) {
                ALOGI("invalid key size %d", keySize);
                return ::SYSTEM_ERROR;
            }
            dsa_params.key_size = keySize;

            if (args->size() == 3) {
                sp<KeystoreArg> gArg = args->itemAt(0);
                sp<KeystoreArg> pArg = args->itemAt(1);
                sp<KeystoreArg> qArg = args->itemAt(2);

                if (gArg != NULL && pArg != NULL && qArg != NULL) {
                    dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
                    dsa_params.generator_len = gArg->size();

                    dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
                    dsa_params.prime_p_len = pArg->size();

                    dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
                    dsa_params.prime_q_len = qArg->size();
                } else {
                    ALOGI("not all DSA parameters were read");
                    return ::SYSTEM_ERROR;
                }
            } else if (args->size() != 0) {
                ALOGI("DSA args must be 3");
                return ::SYSTEM_ERROR;
            }

1846
            if (isKeyTypeSupported(device, TYPE_DSA)) {
1847 1848 1849 1850 1851 1852
                rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
            } else {
                isFallback = true;
                rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
            }
        } else if (keyType == EVP_PKEY_EC) {
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
            keymaster_ec_keygen_params_t ec_params;
            memset(&ec_params, '\0', sizeof(ec_params));

            if (keySize == -1) {
                keySize = EC_DEFAULT_KEY_SIZE;
            } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
                ALOGI("invalid key size %d", keySize);
                return ::SYSTEM_ERROR;
            }
            ec_params.field_size = keySize;

1864
            if (isKeyTypeSupported(device, TYPE_EC)) {
1865 1866 1867 1868 1869
                rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
            } else {
                isFallback = true;
                rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
            }
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
        } else if (keyType == EVP_PKEY_RSA) {
            keymaster_rsa_keygen_params_t rsa_params;
            memset(&rsa_params, '\0', sizeof(rsa_params));
            rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;

            if (keySize == -1) {
                keySize = RSA_DEFAULT_KEY_SIZE;
            } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
                ALOGI("invalid key size %d", keySize);
                return ::SYSTEM_ERROR;
            }
            rsa_params.modulus_size = keySize;

            if (args->size() > 1) {
1884
                ALOGI("invalid number of arguments: %zu", args->size());
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
                return ::SYSTEM_ERROR;
            } else if (args->size() == 1) {
                sp<KeystoreArg> pubExpBlob = args->itemAt(0);
                if (pubExpBlob != NULL) {
                    Unique_BIGNUM pubExpBn(
                            BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
                                    pubExpBlob->size(), NULL));
                    if (pubExpBn.get() == NULL) {
                        ALOGI("Could not convert public exponent to BN");
                        return ::SYSTEM_ERROR;
                    }
                    unsigned long pubExp = BN_get_word(pubExpBn.get());
                    if (pubExp == 0xFFFFFFFFL) {
                        ALOGI("cannot represent public exponent as a long value");
                        return ::SYSTEM_ERROR;
                    }
                    rsa_params.public_exponent = pubExp;
                }
            }

            rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
        } else {
            ALOGW("Unsupported key type %d", keyType);
            rc = -1;
        }
1910

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

Kenny Root's avatar
Kenny Root committed
1915 1916
        String8 name8(name);
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1917

Kenny Root's avatar
Kenny Root committed
1918 1919 1920
        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
        free(data);

1921
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1922 1923
        keyBlob.setFallback(isFallback);

Kenny Root's avatar
Kenny Root committed
1924
        return mKeyStore->put(filename.string(), &keyBlob, callingUid);
1925 1926
    }

1927 1928
    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
            int32_t flags) {
1929
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1930 1931
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_INSERT, spid)) {
1932
            ALOGW("permission denied for %d: import", callingUid);
Kenny Root's avatar
Kenny Root committed
1933 1934
            return ::PERMISSION_DENIED;
        }
1935

1936 1937 1938
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1939 1940 1941
            return ::PERMISSION_DENIED;
        }

1942
        State state = mKeyStore->getState(targetUid);
1943
        if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1944 1945 1946
            ALOGD("calling import in state: %d", state);
            return state;
        }
1947

Kenny Root's avatar
Kenny Root committed
1948
        String8 name8(name);
1949
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1950

1951
        return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
1952 1953
    }

Kenny Root's avatar
Kenny Root committed
1954 1955
    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
            size_t* outLength) {
1956
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1957 1958
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_SIGN, spid)) {
1959
            ALOGW("permission denied for %d: saw", callingUid);
Kenny Root's avatar
Kenny Root committed
1960 1961
            return ::PERMISSION_DENIED;
        }
1962

Kenny Root's avatar
Kenny Root committed
1963 1964
        Blob keyBlob;
        String8 name8(name);
1965

1966
        ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root's avatar
Kenny Root committed
1967
        int rc;
1968

Kenny Root's avatar
Kenny Root committed
1969
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1970
                ::TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
1971 1972 1973
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1974

Kenny Root's avatar
Kenny Root committed
1975 1976 1977 1978 1979
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            ALOGE("no keymaster device; cannot sign");
            return ::SYSTEM_ERROR;
        }
1980

Kenny Root's avatar
Kenny Root committed
1981 1982 1983 1984
        if (device->sign_data == NULL) {
            ALOGE("device doesn't implement signing");
            return ::SYSTEM_ERROR;
        }
1985

Kenny Root's avatar
Kenny Root committed
1986 1987 1988 1989
        keymaster_rsa_sign_params_t params;
        params.digest_type = DIGEST_NONE;
        params.padding_type = PADDING_NONE;

1990 1991 1992 1993 1994 1995 1996
        if (keyBlob.isFallback()) {
            rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
                    length, out, outLength);
        } else {
            rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
                    length, out, outLength);
        }
Kenny Root's avatar
Kenny Root committed
1997 1998 1999 2000
        if (rc) {
            ALOGW("device couldn't sign data");
            return ::SYSTEM_ERROR;
        }
2001

Kenny Root's avatar
Kenny Root committed
2002
        return ::NO_ERROR;
2003 2004
    }

Kenny Root's avatar
Kenny Root committed
2005 2006
    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
            const uint8_t* signature, size_t signatureLength) {
2007
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2008 2009
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_VERIFY, spid)) {
2010
            ALOGW("permission denied for %d: verify", callingUid);
Kenny Root's avatar
Kenny Root committed
2011 2012
            return ::PERMISSION_DENIED;
        }
2013

Kenny Root's avatar
Kenny Root committed
2014
        State state = mKeyStore->getState(callingUid);
2015
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
2016 2017 2018
            ALOGD("calling verify in state: %d", state);
            return state;
        }
2019

Kenny Root's avatar
Kenny Root committed
2020 2021 2022
        Blob keyBlob;
        String8 name8(name);
        int rc;
2023

Kenny Root's avatar
Kenny Root committed
2024
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2025
                TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
2026 2027 2028
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
2029

Kenny Root's avatar
Kenny Root committed
2030 2031 2032 2033
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
2034

Kenny Root's avatar
Kenny Root committed
2035 2036 2037 2038 2039 2040 2041
        if (device->verify_data == NULL) {
            return ::SYSTEM_ERROR;
        }

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

2043 2044 2045 2046 2047 2048 2049
        if (keyBlob.isFallback()) {
            rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
                    dataLength, signature, signatureLength);
        } else {
            rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
                    dataLength, signature, signatureLength);
        }
Kenny Root's avatar
Kenny Root committed
2050 2051 2052 2053 2054
        if (rc) {
            return ::SYSTEM_ERROR;
        } else {
            return ::NO_ERROR;
        }
2055 2056
    }

Kenny Root's avatar
Kenny Root committed
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
    /*
     * 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) {
2069
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2070 2071
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_GET, spid)) {
2072
            ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root's avatar
Kenny Root committed
2073 2074
            return ::PERMISSION_DENIED;
        }
2075

Kenny Root's avatar
Kenny Root committed
2076 2077
        Blob keyBlob;
        String8 name8(name);
2078

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

Kenny Root's avatar
Kenny Root committed
2081
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root's avatar
Kenny Root committed
2082 2083 2084 2085
                TYPE_KEY_PAIR);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
2086

Kenny Root's avatar
Kenny Root committed
2087 2088 2089 2090
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
2091

Kenny Root's avatar
Kenny Root committed
2092 2093 2094 2095
        if (device->get_keypair_public == NULL) {
            ALOGE("device has no get_keypair_public implementation!");
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
2096

2097 2098 2099 2100 2101 2102 2103 2104
        int rc;
        if (keyBlob.isFallback()) {
            rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
                    pubkeyLength);
        } else {
            rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
                    pubkeyLength);
        }
Kenny Root's avatar
Kenny Root committed
2105 2106 2107
        if (rc) {
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
2108

Kenny Root's avatar
Kenny Root committed
2109
        return ::NO_ERROR;
Kenny Root's avatar
Kenny Root committed
2110 2111
    }

2112
    int32_t del_key(const String16& name, int targetUid) {
2113
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2114 2115
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_DELETE, spid)) {
2116
            ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root's avatar
Kenny Root committed
2117 2118
            return ::PERMISSION_DENIED;
        }
Kenny Root's avatar
Kenny Root committed
2119

2120 2121 2122
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
2123 2124 2125
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
2126
        String8 name8(name);
2127
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
2128

Kenny Root's avatar
Kenny Root committed
2129
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
2130
        ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
2131
                targetUid);
Kenny Root's avatar
Kenny Root committed
2132 2133 2134
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
2135

Kenny Root's avatar
Kenny Root committed
2136
        ResponseCode rc = ::NO_ERROR;
2137

Kenny Root's avatar
Kenny Root committed
2138 2139 2140 2141 2142
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            rc = ::SYSTEM_ERROR;
        } else {
            // A device doesn't have to implement delete_keypair.
2143
            if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root's avatar
Kenny Root committed
2144 2145 2146 2147 2148
                if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
                    rc = ::SYSTEM_ERROR;
                }
            }
        }
2149

Kenny Root's avatar
Kenny Root committed
2150 2151 2152
        if (rc != ::NO_ERROR) {
            return rc;
        }
2153

Kenny Root's avatar
Kenny Root committed
2154
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2155
    }
Kenny Root's avatar
Kenny Root committed
2156 2157

    int32_t grant(const String16& name, int32_t granteeUid) {
2158
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2159 2160
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_GRANT, spid)) {
2161
            ALOGW("permission denied for %d: grant", callingUid);
Kenny Root's avatar
Kenny Root committed
2162 2163 2164
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
2165
        State state = mKeyStore->getState(callingUid);
2166
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
2167 2168 2169 2170 2171
            ALOGD("calling grant in state: %d", state);
            return state;
        }

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

Kenny Root's avatar
Kenny Root committed
2174
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
2175 2176 2177
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

Kenny Root's avatar
Kenny Root committed
2178
        mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root's avatar
Kenny Root committed
2179
        return ::NO_ERROR;
2180
    }
Kenny Root's avatar
Kenny Root committed
2181 2182

    int32_t ungrant(const String16& name, int32_t granteeUid) {
2183
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2184 2185
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_GRANT, spid)) {
2186
            ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root's avatar
Kenny Root committed
2187 2188 2189
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
2190
        State state = mKeyStore->getState(callingUid);
2191
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
2192 2193 2194 2195 2196
            ALOGD("calling ungrant in state: %d", state);
            return state;
        }

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

Kenny Root's avatar
Kenny Root committed
2199
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
2200 2201 2202
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

Kenny Root's avatar
Kenny Root committed
2203
        return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
2204
    }
Kenny Root's avatar
Kenny Root committed
2205 2206

    int64_t getmtime(const String16& name) {
2207
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2208 2209
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_GET, spid)) {
2210
            ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root's avatar
Kenny Root committed
2211
            return -1L;
Kenny Root's avatar
Kenny Root committed
2212 2213 2214
        }

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

Kenny Root's avatar
Kenny Root committed
2217 2218
        if (access(filename.string(), R_OK) == -1) {
            ALOGW("could not access %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
2219
            return -1L;
2220
        }
Kenny Root's avatar
Kenny Root committed
2221

Kenny Root's avatar
Kenny Root committed
2222
        int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root's avatar
Kenny Root committed
2223
        if (fd < 0) {
Kenny Root's avatar
Kenny Root committed
2224
            ALOGW("could not open %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
2225
            return -1L;
Kenny Root's avatar
Kenny Root committed
2226 2227 2228 2229 2230 2231
        }

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

Kenny Root's avatar
Kenny Root committed
2236
        return static_cast<int64_t>(s.st_mtime);
2237
    }
Kenny Root's avatar
Kenny Root committed
2238

2239 2240
    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
            int32_t destUid) {
Kenny Root's avatar
Kenny Root committed
2241
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2242 2243
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_DUPLICATE, spid)) {
2244
            ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root's avatar
Kenny Root committed
2245 2246 2247
            return -1L;
        }

Kenny Root's avatar
Kenny Root committed
2248
        State state = mKeyStore->getState(callingUid);
Kenny Root's avatar
Kenny Root committed
2249
        if (!isKeystoreUnlocked(state)) {
2250
            ALOGD("calling duplicate in state: %d", state);
Kenny Root's avatar
Kenny Root committed
2251 2252 2253
            return state;
        }

2254 2255 2256 2257
        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
2258 2259 2260
            return ::PERMISSION_DENIED;
        }

2261 2262 2263
        if (destUid == -1) {
            destUid = callingUid;
        }
Kenny Root's avatar
Kenny Root committed
2264

2265 2266 2267 2268 2269 2270
        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
2271

2272 2273 2274 2275
            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
2276 2277
        }

2278
        String8 source8(srcKey);
Kenny Root's avatar
Kenny Root committed
2279
        String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
2280 2281

        String8 target8(destKey);
2282
        String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root's avatar
Kenny Root committed
2283

Kenny Root's avatar
Kenny Root committed
2284 2285
        if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
            ALOGD("destination already exists: %s", targetFile.string());
Kenny Root's avatar
Kenny Root committed
2286 2287 2288
            return ::SYSTEM_ERROR;
        }

2289
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
2290
        ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2291
                srcUid);
2292 2293
        if (responseCode != ::NO_ERROR) {
            return responseCode;
Kenny Root's avatar
Kenny Root committed
2294
        }
2295

2296
        return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root's avatar
Kenny Root committed
2297 2298
    }

2299 2300
    int32_t is_hardware_backed(const String16& keyType) {
        return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
2301 2302
    }

2303 2304
    int32_t clear_uid(int64_t targetUid64) {
        uid_t targetUid = static_cast<uid_t>(targetUid64);
2305
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2306 2307
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
2308 2309 2310 2311
            ALOGW("permission denied for %d: clear_uid", callingUid);
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
2312
        State state = mKeyStore->getState(callingUid);
2313 2314 2315 2316 2317
        if (!isKeystoreUnlocked(state)) {
            ALOGD("calling clear_uid in state: %d", state);
            return state;
        }

2318 2319 2320 2321 2322 2323
        if (targetUid64 == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
            return ::PERMISSION_DENIED;
        }

2324 2325
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
Kenny Root's avatar
Kenny Root committed
2326
            ALOGW("can't get keymaster device");
2327 2328 2329
            return ::SYSTEM_ERROR;
        }

2330
        UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root's avatar
Kenny Root committed
2331
        DIR* dir = opendir(userState->getUserDirName());
2332
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
2333
            ALOGW("can't open user directory: %s", strerror(errno));
2334 2335 2336
            return ::SYSTEM_ERROR;
        }

Kenny Root's avatar
Kenny Root committed
2337
        char prefix[NAME_MAX];
2338
        int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
2339 2340 2341 2342 2343

        ResponseCode rc = ::NO_ERROR;

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
2344 2345
            // We only care about files.
            if (file->d_type != DT_REG) {
2346 2347 2348
                continue;
            }

Kenny Root's avatar
Kenny Root committed
2349 2350 2351 2352 2353 2354 2355 2356
            // Skip anything that starts with a "."
            if (file->d_name[0] == '.') {
                continue;
            }

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

Kenny Root's avatar
Kenny Root committed
2358
            String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
2359
            Blob keyBlob;
2360
            if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root's avatar
Kenny Root committed
2361 2362
                    != ::NO_ERROR) {
                ALOGW("couldn't open %s", filename.string());
2363 2364 2365 2366 2367
                continue;
            }

            if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
                // A device doesn't have to implement delete_keypair.
2368
                if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
2369 2370
                    if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
                        rc = ::SYSTEM_ERROR;
Kenny Root's avatar
Kenny Root committed
2371
                        ALOGW("device couldn't remove %s", filename.string());
2372 2373 2374 2375
                    }
                }
            }

Kenny Root's avatar
Kenny Root committed
2376
            if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
2377
                rc = ::SYSTEM_ERROR;
Kenny Root's avatar
Kenny Root committed
2378
                ALOGW("couldn't unlink %s", filename.string());
2379 2380 2381 2382 2383 2384 2385
            }
        }
        closedir(dir);

        return rc;
    }

Kenny Root's avatar
Kenny Root committed
2386
private:
2387 2388 2389 2390 2391 2392 2393 2394 2395
    inline bool isKeystoreUnlocked(State state) {
        switch (state) {
        case ::STATE_NO_ERROR:
            return true;
        case ::STATE_UNINITIALIZED:
        case ::STATE_LOCKED:
            return false;
        }
        return false;
2396
    }
Kenny Root's avatar
Kenny Root committed
2397

2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
    bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
        const int32_t device_api = device->common.module->module_api_version;
        if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
            switch (keyType) {
                case TYPE_RSA:
                case TYPE_DSA:
                case TYPE_EC:
                    return true;
                default:
                    return false;
            }
        } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
            switch (keyType) {
                case TYPE_RSA:
                    return true;
                case TYPE_DSA:
                    return device->flags & KEYMASTER_SUPPORTS_DSA;
                case TYPE_EC:
                    return device->flags & KEYMASTER_SUPPORTS_EC;
                default:
                    return false;
            }
        } else {
            return keyType == TYPE_RSA;
        }
    }

Kenny Root's avatar
Kenny Root committed
2425 2426 2427 2428
    ::KeyStore* mKeyStore;
};

}; // namespace android
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443

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;
    }
2444 2445 2446 2447 2448 2449 2450

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

2451 2452 2453 2454 2455 2456 2457 2458
    union selinux_callback cb;
    cb.func_log = selinux_log_callback;
    selinux_set_callback(SELINUX_CB_LOG, cb);
    if (getcon(&tctx) != 0) {
        ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
        return -1;
    }

2459
    KeyStore keyStore(&entropy, dev);
Kenny Root's avatar
Kenny Root committed
2460
    keyStore.initialize();
Kenny Root's avatar
Kenny Root committed
2461 2462 2463 2464 2465 2466
    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;
2467
    }
2468

Kenny Root's avatar
Kenny Root committed
2469 2470 2471 2472 2473
    /*
     * 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();
2474

Kenny Root's avatar
Kenny Root committed
2475
    keymaster_device_release(dev);
2476

2477 2478
    return 1;
}