keystore.cpp 52.1 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 27 28
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
29
#include <assert.h>
30 31 32 33 34 35 36
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <arpa/inet.h>

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

42 43
#include <hardware/keymaster.h>

44 45
#include <utils/UniquePtr.h>

46 47
#include <cutils/list.h>

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

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

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

/* 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

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

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;


91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
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
119 120 121 122 123 124
/***************
 * PERMISSIONS *
 ***************/

/* Here are the permissions, actions, users, and the main function. */
typedef enum {
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    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,
Kenny Root's avatar
Kenny Root committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
} perm_t;

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

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

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

static bool has_permission(uid_t uid, perm_t perm) {
    for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
        struct user_perm user = user_perms[i];
        if (user.uid == uid) {
            return user.perms & perm;
        }
    }

    return DEFAULT_PERMS & perm;
}

175 176 177 178 179
/**
 * 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
180 181 182 183 184 185 186 187 188 189 190
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;
}

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
/**
 * 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;
}

206 207 208 209 210 211 212
/* 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
213 214 215
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();
216 217 218 219 220 221 222 223 224 225
    for (int i = length; i > 0; --i, ++in, ++out) {
        if (*in >= '0' && *in <= '~') {
            *out = *in;
        } else {
            *out = '+' + (*in >> 6);
            *++out = '0' + (*in & 0x3F);
            ++length;
        }
    }
    *out = '\0';
226 227 228
    return length;
}

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

Kenny Root's avatar
Kenny Root committed
233
    return n + encode_key(out, keyName);
234 235
}

Kenny Root's avatar
Kenny Root committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
/*
 * 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;
266
        } else {
Kenny Root's avatar
Kenny Root committed
267
            *out++ = *in;
268 269 270 271 272 273 274 275
        }
    }
    *out = '\0';
}

static size_t readFully(int fd, uint8_t* data, size_t size) {
    size_t remaining = size;
    while (remaining > 0) {
276
        ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root's avatar
Kenny Root committed
277
        if (n <= 0) {
278
            return size - remaining;
279 280 281 282 283 284 285 286 287 288
        }
        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) {
289 290 291 292
        ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
        if (n < 0) {
            ALOGW("write failed: %s", strerror(errno));
            return size - remaining;
293 294 295 296 297 298 299 300 301 302 303
        }
        data += n;
        remaining -= n;
    }
    return size;
}

class Entropy {
public:
    Entropy() : mRandom(-1) {}
    ~Entropy() {
304
        if (mRandom >= 0) {
305 306 307 308 309 310
            close(mRandom);
        }
    }

    bool open() {
        const char* randomDevice = "/dev/urandom";
311 312
        mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
        if (mRandom < 0) {
313 314 315 316 317 318
            ALOGE("open: %s: %s", randomDevice, strerror(errno));
            return false;
        }
        return true;
    }

Kenny Root's avatar
Kenny Root committed
319
    bool generate_random_data(uint8_t* data, size_t size) const {
320 321 322 323 324 325 326 327 328 329 330
        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
331 332
 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
 * the second is the blob's type, and the third byte is reserved. Fields other
333 334 335
 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
 * and decryptBlob(). Thus they should not be accessed from outside. */

336 337 338 339 340 341 342 343 344 345 346 347 348 349
/* ** 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))
 */
350
struct __attribute__((packed)) blob {
351 352 353
    uint8_t version;
    uint8_t type;
    uint8_t reserved;
354 355
    uint8_t info;
    uint8_t vector[AES_BLOCK_SIZE];
356
    uint8_t encrypted[0]; // Marks offset to encrypted data.
357
    uint8_t digest[MD5_DIGEST_LENGTH];
358
    uint8_t digested[0]; // Marks offset to digested data.
359 360 361 362
    int32_t length; // in network byte order when encrypted
    uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
};

363
typedef enum {
364
    TYPE_ANY = 0, // meta type that matches anything
365 366 367 368 369
    TYPE_GENERIC = 1,
    TYPE_MASTER_KEY = 2,
    TYPE_KEY_PAIR = 3,
} BlobType;

Kenny Root's avatar
Kenny Root committed
370
static const uint8_t CURRENT_BLOB_VERSION = 1;
371

372 373
class Blob {
public:
Kenny Root's avatar
Kenny Root committed
374 375
    Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
            BlobType type) {
376 377 378 379 380
        mBlob.length = valueLength;
        memcpy(mBlob.value, value, valueLength);

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

Kenny Root's avatar
Kenny Root committed
382
        mBlob.version = CURRENT_BLOB_VERSION;
383
        mBlob.type = uint8_t(type);
384 385 386 387 388 389 390 391
    }

    Blob(blob b) {
        mBlob = b;
    }

    Blob() {}

Kenny Root's avatar
Kenny Root committed
392
    const uint8_t* getValue() const {
393 394 395
        return mBlob.value;
    }

Kenny Root's avatar
Kenny Root committed
396
    int32_t getLength() const {
397 398 399
        return mBlob.length;
    }

Kenny Root's avatar
Kenny Root committed
400 401 402 403 404
    const uint8_t* getInfo() const {
        return mBlob.value + mBlob.length;
    }

    uint8_t getInfoLength() const {
405 406 407
        return mBlob.info;
    }

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    uint8_t getVersion() const {
        return mBlob.version;
    }

    void setVersion(uint8_t version) {
        mBlob.version = version;
    }

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

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

424 425
    ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
        if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
426
            ALOGW("Could not read random data for: %s", filename);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
            return SYSTEM_ERROR;
        }

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

450
        mBlob.reserved = 0;
451 452 453 454
        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
        size_t fileLength = encryptedLength + headerLength + mBlob.info;

        const char* tmpFileName = ".tmp";
455 456 457 458
        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));
459 460 461 462 463 464 465
            return SYSTEM_ERROR;
        }
        size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
        if (close(out) != 0) {
            return SYSTEM_ERROR;
        }
        if (writtenBytes != fileLength) {
466
            ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
467 468 469
            unlink(tmpFileName);
            return SYSTEM_ERROR;
        }
470 471 472 473 474
        if (rename(tmpFileName, filename) == -1) {
            ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
            return SYSTEM_ERROR;
        }
        return NO_ERROR;
475 476 477
    }

    ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
478 479
        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
        if (in < 0) {
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
            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;
        }
        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
        if (fileLength < headerLength) {
            return VALUE_CORRUPTED;
        }

        ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
        if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
            return VALUE_CORRUPTED;
        }
        AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
                        mBlob.vector, AES_DECRYPT);
        size_t 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;
        }

        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
516
        return ::NO_ERROR;
517 518 519 520 521 522
    }

private:
    struct blob mBlob;
};

523 524
typedef struct {
    uint32_t uid;
525
    const uint8_t* filename;
526 527 528 529

    struct listnode plist;
} grant_t;

530 531
class KeyStore {
public:
532
    KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root's avatar
Kenny Root committed
533
        : mEntropy(entropy)
534
        , mDevice(device)
Kenny Root's avatar
Kenny Root committed
535 536
        , mRetry(MAX_RETRY)
    {
537 538 539 540 541
        if (access(MASTER_KEY_FILE, R_OK) == 0) {
            setState(STATE_LOCKED);
        } else {
            setState(STATE_UNINITIALIZED);
        }
542 543

        list_init(&mGrants);
544 545
    }

Kenny Root's avatar
Kenny Root committed
546
    State getState() const {
547 548 549
        return mState;
    }

Kenny Root's avatar
Kenny Root committed
550
    int8_t getRetry() const {
551 552 553
        return mRetry;
    }

554 555 556 557
    keymaster_device_t* getDevice() const {
        return mDevice;
    }

Kenny Root's avatar
Kenny Root committed
558
    ResponseCode initialize(const android::String8& pw) {
559 560 561 562 563 564 565 566
        if (!generateMasterKey()) {
            return SYSTEM_ERROR;
        }
        ResponseCode response = writeMasterKey(pw);
        if (response != NO_ERROR) {
            return response;
        }
        setupMasterKeys();
Kenny Root's avatar
Kenny Root committed
567
        return ::NO_ERROR;
568 569
    }

Kenny Root's avatar
Kenny Root committed
570
    ResponseCode writeMasterKey(const android::String8& pw) {
571 572 573 574
        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);
575
        Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
576 577 578
        return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
    }

Kenny Root's avatar
Kenny Root committed
579
    ResponseCode readMasterKey(const android::String8& pw) {
580 581
        int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
        if (in < 0) {
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
            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);
        ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
        if (response == SYSTEM_ERROR) {
            return SYSTEM_ERROR;
        }
        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) {
                if (!generateSalt()) {
                    return SYSTEM_ERROR;
                }
                response = writeMasterKey(pw);
            }
            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;
        }
    }

    bool reset() {
        clearMasterKeys();
        setState(STATE_UNINITIALIZED);

        DIR* dir = opendir(".");
        struct dirent* file;

        if (!dir) {
            return false;
        }
        while ((file = readdir(dir)) != NULL) {
            unlink(file->d_name);
        }
        closedir(dir);
        return true;
    }

Kenny Root's avatar
Kenny Root committed
653
    bool isEmpty() const {
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
        DIR* dir = opendir(".");
        struct dirent* file;
        if (!dir) {
            return true;
        }
        bool result = true;
        while ((file = readdir(dir)) != NULL) {
            if (isKeyFile(file->d_name)) {
                result = false;
                break;
            }
        }
        closedir(dir);
        return result;
    }

    void lock() {
        clearMasterKeys();
        setState(STATE_LOCKED);
    }

675 676 677 678 679 680 681
    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
        ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
        if (rc != NO_ERROR) {
            return rc;
        }

        const uint8_t version = keyBlob->getVersion();
Kenny Root's avatar
Kenny Root committed
682
        if (version < CURRENT_BLOB_VERSION) {
683 684 685
            upgrade(filename, keyBlob, version, type);
        }

686
        if (type != TYPE_ANY && keyBlob->getType() != type) {
687 688 689 690 691
            ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
            return KEY_NOT_FOUND;
        }

        return rc;
692 693 694 695 696 697
    }

    ResponseCode put(const char* filename, Blob* keyBlob) {
        return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
    }

Kenny Root's avatar
Kenny Root committed
698 699
    void addGrant(const char* filename, uid_t granteeUid) {
        grant_t *grant = getGrant(filename, granteeUid);
700 701
        if (grant == NULL) {
            grant = new grant_t;
Kenny Root's avatar
Kenny Root committed
702
            grant->uid = granteeUid;
703
            grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
704 705 706 707
            list_add_tail(&mGrants, &grant->plist);
        }
    }

Kenny Root's avatar
Kenny Root committed
708 709
    bool removeGrant(const char* filename, uid_t granteeUid) {
        grant_t *grant = getGrant(filename, granteeUid);
710 711 712 713 714 715 716 717 718
        if (grant != NULL) {
            list_remove(&grant->plist);
            delete grant;
            return true;
        }

        return false;
    }

719 720
    bool hasGrant(const char* filename, const uid_t uid) const {
        return getGrant(filename, uid) != NULL;
721 722
    }

Kenny Root's avatar
Kenny Root committed
723
    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
724 725 726 727 728 729 730 731 732
        uint8_t* data;
        size_t dataLength;
        int rc;

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

Kenny Root's avatar
Kenny Root committed
733
        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
734 735 736 737 738 739 740 741 742 743 744
        if (rc) {
            ALOGE("Error while importing keypair: %d", rc);
            return SYSTEM_ERROR;
        }

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

        return put(filename, &keyBlob);
    }

745 746 747 748
    bool isHardwareBacked() const {
        return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) != 0;
    }

749 750 751 752 753 754 755 756 757 758
private:
    static const char* MASTER_KEY_FILE;
    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;

    Entropy* mEntropy;

759 760
    keymaster_device_t* mDevice;

761 762 763 764 765 766 767 768 769
    State mState;
    int8_t mRetry;

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

    AES_KEY mMasterKeyEncryption;
    AES_KEY mMasterKeyDecryption;

770 771
    struct listnode mGrants;

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
    void setState(State state) {
        mState = state;
        if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
            mRetry = MAX_RETRY;
        }
    }

    bool generateSalt() {
        return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
    }

    bool generateMasterKey() {
        if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
            return false;
        }
        if (!generateSalt()) {
            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);
    }

    void clearMasterKeys() {
        memset(mMasterKey, 0, sizeof(mMasterKey));
        memset(mSalt, 0, sizeof(mSalt));
        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
    }

Kenny Root's avatar
Kenny Root committed
806 807
    static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
            uint8_t* salt) {
808 809 810 811 812 813 814 815 816
        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");
        }
Kenny Root's avatar
Kenny Root committed
817 818 819

        PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
                saltSize, 8192, keySize, key);
820 821 822 823 824 825 826
    }

    static bool isKeyFile(const char* filename) {
        return ((strcmp(filename, MASTER_KEY_FILE) != 0)
                && (strcmp(filename, ".") != 0)
                && (strcmp(filename, "..") != 0));
    }
827

828
    grant_t* getGrant(const char* filename, uid_t uid) const {
829 830 831 832 833 834
        struct listnode *node;
        grant_t *grant;

        list_for_each(node, &mGrants) {
            grant = node_to_item(node, grant_t, plist);
            if (grant->uid == uid
835 836
                    && !strcmp(reinterpret_cast<const char*>(grant->filename),
                               filename)) {
837 838 839 840 841 842 843
                return grant;
            }
        }

        return NULL;
    }

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    /**
     * Upgrade code. This will upgrade the key from the current version
     * to whatever is newest.
     */
    void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
        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) {
                importBlobAsKey(blob, filename);
            }
            version = 1;
            updated = true;
        }

        /*
         * If we've updated, set the key blob to the right version
         * and write it.
         * */
        if (updated) {
            ALOGV("updated and writing file %s", filename);
            blob->setVersion(version);
            this->put(filename, blob);
        }
    }

    /**
     * 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.
     */
    ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
        // 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;
        }

902 903
        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
        uint8_t* tmp = pkcs8key.get();
904 905 906 907 908
        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
            ALOGE("Couldn't convert to PKCS#8");
            return SYSTEM_ERROR;
        }

909
        ResponseCode rc = importKey(pkcs8key.get(), len, filename);
910 911 912 913 914 915
        if (rc != NO_ERROR) {
            return rc;
        }

        return get(filename, blob, TYPE_KEY_PAIR);
    }
916 917 918 919
};

const char* KeyStore::MASTER_KEY_FILE = ".masterkey";

Kenny Root's avatar
Kenny Root committed
920 921
static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
        const android::String8& keyName, const uid_t uid, const BlobType type) {
922 923 924
    char filename[NAME_MAX];

    encode_key_for_uid(filename, uid, keyName);
925
    ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
926 927 928 929
    if (responseCode == NO_ERROR) {
        return responseCode;
    }

930 931 932 933
    // If this is one of the legacy UID->UID mappings, use it.
    uid_t euid = get_keystore_euid(uid);
    if (euid != uid) {
        encode_key_for_uid(filename, euid, keyName);
934
        responseCode = keyStore->get(filename, keyBlob, type);
935 936 937 938 939 940
        if (responseCode == NO_ERROR) {
            return responseCode;
        }
    }

    // They might be using a granted key.
941 942
    encode_key(filename, keyName);
    if (!keyStore->hasGrant(filename, uid)) {
943 944 945 946
        return responseCode;
    }

    // It is a granted key. Try to load it.
947
    return keyStore->get(filename, keyBlob, type);
948 949
}

Kenny Root's avatar
Kenny Root committed
950 951 952 953 954 955 956
namespace android {
class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
public:
    KeyStoreProxy(KeyStore* keyStore)
        : mKeyStore(keyStore)
    {
    }
957

Kenny Root's avatar
Kenny Root committed
958 959 960
    void binderDied(const wp<IBinder>&) {
        ALOGE("binder death detected");
    }
961

Kenny Root's avatar
Kenny Root committed
962
    int32_t test() {
963 964 965
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_TEST)) {
            ALOGW("permission denied for %d: test", callingUid);
Kenny Root's avatar
Kenny Root committed
966 967
            return ::PERMISSION_DENIED;
        }
968

Kenny Root's avatar
Kenny Root committed
969
        return mKeyStore->getState();
970 971
    }

Kenny Root's avatar
Kenny Root committed
972
    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
973 974 975
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GET)) {
            ALOGW("permission denied for %d: get", callingUid);
Kenny Root's avatar
Kenny Root committed
976 977
            return ::PERMISSION_DENIED;
        }
978

979 980
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
981 982 983
            ALOGD("calling get in state: %d", state);
            return state;
        }
984

Kenny Root's avatar
Kenny Root committed
985 986 987
        String8 name8(name);
        char filename[NAME_MAX];
        Blob keyBlob;
988 989 990

        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
                TYPE_GENERIC);
Kenny Root's avatar
Kenny Root committed
991
        if (responseCode != ::NO_ERROR) {
992
            ALOGW("Could not read %s", filename);
Kenny Root's avatar
Kenny Root committed
993 994 995 996 997 998 999 1000 1001 1002
            *item = NULL;
            *itemLength = 0;
            return responseCode;
        }

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

        return ::NO_ERROR;
1003 1004
    }

1005
    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
1006 1007 1008
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_INSERT)) {
            ALOGW("permission denied for %d: insert", callingUid);
Kenny Root's avatar
Kenny Root committed
1009 1010 1011
            return ::PERMISSION_DENIED;
        }

1012 1013 1014
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1015 1016 1017
            return ::PERMISSION_DENIED;
        }

1018 1019
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1020 1021
            ALOGD("calling insert in state: %d", state);
            return state;
1022
        }
Kenny Root's avatar
Kenny Root committed
1023 1024 1025 1026

        String8 name8(name);
        char filename[NAME_MAX];

1027
        encode_key_for_uid(filename, targetUid, name8);
Kenny Root's avatar
Kenny Root committed
1028 1029 1030

        Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
        return mKeyStore->put(filename, &keyBlob);
1031 1032
    }

1033
    int32_t del(const String16& name, int targetUid) {
1034 1035 1036
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_DELETE)) {
            ALOGW("permission denied for %d: del", callingUid);
Kenny Root's avatar
Kenny Root committed
1037 1038 1039
            return ::PERMISSION_DENIED;
        }

1040 1041 1042
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1043 1044 1045
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1046 1047 1048
        String8 name8(name);
        char filename[NAME_MAX];

1049
        encode_key_for_uid(filename, targetUid, name8);
1050

Kenny Root's avatar
Kenny Root committed
1051 1052 1053 1054 1055 1056
        Blob keyBlob;
        ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1057 1058
    }

1059
    int32_t exist(const String16& name, int targetUid) {
1060 1061 1062
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_EXIST)) {
            ALOGW("permission denied for %d: exist", callingUid);
Kenny Root's avatar
Kenny Root committed
1063 1064 1065
            return ::PERMISSION_DENIED;
        }

1066 1067 1068
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1069 1070 1071
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1072 1073 1074
        String8 name8(name);
        char filename[NAME_MAX];

1075
        encode_key_for_uid(filename, targetUid, name8);
Kenny Root's avatar
Kenny Root committed
1076 1077 1078 1079 1080

        if (access(filename, R_OK) == -1) {
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }
        return ::NO_ERROR;
1081 1082
    }

1083
    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1084 1085 1086
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_SAW)) {
            ALOGW("permission denied for %d: saw", callingUid);
Kenny Root's avatar
Kenny Root committed
1087 1088 1089
            return ::PERMISSION_DENIED;
        }

1090 1091 1092
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1093 1094 1095
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1096 1097 1098 1099 1100 1101 1102 1103
        DIR* dir = opendir(".");
        if (!dir) {
            return ::SYSTEM_ERROR;
        }

        const String8 prefix8(prefix);
        char filename[NAME_MAX];

1104
        int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root's avatar
Kenny Root committed
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
            if (!strncmp(filename, file->d_name, n)) {
                const char* p = &file->d_name[n];
                size_t plen = strlen(p);

                size_t extra = decode_key_length(p, plen);
                char *match = (char*) malloc(extra + 1);
                if (match != NULL) {
                    decode_key(match, p, plen);
                    matches->push(String16(match, extra));
                    free(match);
                } else {
                    ALOGW("could not allocate match of size %zd", extra);
                }
            }
        }
        closedir(dir);

        return ::NO_ERROR;
1126 1127
    }

Kenny Root's avatar
Kenny Root committed
1128
    int32_t reset() {
1129 1130 1131
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_RESET)) {
            ALOGW("permission denied for %d: reset", callingUid);
Kenny Root's avatar
Kenny Root committed
1132 1133
            return ::PERMISSION_DENIED;
        }
1134

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

Kenny Root's avatar
Kenny Root committed
1137 1138 1139 1140
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            ALOGE("No keymaster device!");
            return ::SYSTEM_ERROR;
1141
        }
Kenny Root's avatar
Kenny Root committed
1142 1143 1144 1145

        if (device->delete_all == NULL) {
            ALOGV("keymaster device doesn't implement delete_all");
            return rc;
1146
        }
Kenny Root's avatar
Kenny Root committed
1147 1148 1149 1150

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

        return rc;
1154 1155
    }

Kenny Root's avatar
Kenny Root committed
1156 1157 1158 1159 1160 1161 1162 1163
    /*
     * 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) {
1164 1165 1166
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_PASSWORD)) {
            ALOGW("permission denied for %d: password", callingUid);
Kenny Root's avatar
Kenny Root committed
1167 1168
            return ::PERMISSION_DENIED;
        }
1169

Kenny Root's avatar
Kenny Root committed
1170
        const String8 password8(password);
1171

Kenny Root's avatar
Kenny Root committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        switch (mKeyStore->getState()) {
            case ::STATE_UNINITIALIZED: {
                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
                return mKeyStore->initialize(password8);
            }
            case ::STATE_NO_ERROR: {
                // rewrite master key with new password.
                return mKeyStore->writeMasterKey(password8);
            }
            case ::STATE_LOCKED: {
                // read master key, decrypt with password, initialize mMasterKey*.
                return mKeyStore->readMasterKey(password8);
            }
        }
        return ::SYSTEM_ERROR;
    }
1188

Kenny Root's avatar
Kenny Root committed
1189
    int32_t lock() {
1190 1191 1192
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_LOCK)) {
            ALOGW("permission denied for %d: lock", callingUid);
Kenny Root's avatar
Kenny Root committed
1193 1194 1195
            return ::PERMISSION_DENIED;
        }

1196 1197
        State state = mKeyStore->getState();
        if (state != ::STATE_NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1198 1199 1200
            ALOGD("calling lock in state: %d", state);
            return state;
        }
1201

Kenny Root's avatar
Kenny Root committed
1202 1203
        mKeyStore->lock();
        return ::NO_ERROR;
1204
    }
1205

Kenny Root's avatar
Kenny Root committed
1206
    int32_t unlock(const String16& pw) {
1207 1208 1209
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_UNLOCK)) {
            ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root's avatar
Kenny Root committed
1210 1211 1212
            return ::PERMISSION_DENIED;
        }

1213 1214
        State state = mKeyStore->getState();
        if (state != ::STATE_LOCKED) {
Kenny Root's avatar
Kenny Root committed
1215 1216 1217 1218 1219 1220
            ALOGD("calling unlock when not locked");
            return state;
        }

        const String8 password8(pw);
        return password(pw);
1221 1222
    }

Kenny Root's avatar
Kenny Root committed
1223
    int32_t zero() {
1224 1225 1226
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_ZERO)) {
            ALOGW("permission denied for %d: zero", callingUid);
Kenny Root's avatar
Kenny Root committed
1227 1228
            return -1;
        }
1229

Kenny Root's avatar
Kenny Root committed
1230
        return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
1231 1232
    }

1233
    int32_t generate(const String16& name, int targetUid) {
1234 1235 1236
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_INSERT)) {
            ALOGW("permission denied for %d: generate", callingUid);
Kenny Root's avatar
Kenny Root committed
1237 1238
            return ::PERMISSION_DENIED;
        }
1239

1240 1241 1242
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1243 1244 1245
            return ::PERMISSION_DENIED;
        }

1246 1247
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1248 1249 1250
            ALOGD("calling generate in state: %d", state);
            return state;
        }
1251

Kenny Root's avatar
Kenny Root committed
1252 1253
        String8 name8(name);
        char filename[NAME_MAX];
1254

Kenny Root's avatar
Kenny Root committed
1255 1256 1257
        uint8_t* data;
        size_t dataLength;
        int rc;
1258

Kenny Root's avatar
Kenny Root committed
1259 1260 1261 1262
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1263

Kenny Root's avatar
Kenny Root committed
1264 1265 1266
        if (device->generate_keypair == NULL) {
            return ::SYSTEM_ERROR;
        }
1267

Kenny Root's avatar
Kenny Root committed
1268 1269 1270
        keymaster_rsa_keygen_params_t rsa_params;
        rsa_params.modulus_size = 2048;
        rsa_params.public_exponent = 0x10001;
1271

Kenny Root's avatar
Kenny Root committed
1272 1273 1274 1275
        rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
        if (rc) {
            return ::SYSTEM_ERROR;
        }
1276

1277
        encode_key_for_uid(filename, targetUid, name8);
1278

Kenny Root's avatar
Kenny Root committed
1279 1280 1281 1282
        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
        free(data);

        return mKeyStore->put(filename, &keyBlob);
1283 1284
    }

1285
    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
1286 1287 1288
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_INSERT)) {
            ALOGW("permission denied for %d: import", callingUid);
Kenny Root's avatar
Kenny Root committed
1289 1290
            return ::PERMISSION_DENIED;
        }
1291

1292 1293 1294
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1295 1296 1297
            return ::PERMISSION_DENIED;
        }

1298 1299
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1300 1301 1302
            ALOGD("calling import in state: %d", state);
            return state;
        }
1303

Kenny Root's avatar
Kenny Root committed
1304 1305
        String8 name8(name);
        char filename[NAME_MAX];
1306

1307
        encode_key_for_uid(filename, targetUid, name8);
1308

Kenny Root's avatar
Kenny Root committed
1309
        return mKeyStore->importKey(data, length, filename);
1310 1311
    }

Kenny Root's avatar
Kenny Root committed
1312 1313
    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
            size_t* outLength) {
1314 1315 1316
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_SIGN)) {
            ALOGW("permission denied for %d: saw", callingUid);
Kenny Root's avatar
Kenny Root committed
1317 1318
            return ::PERMISSION_DENIED;
        }
1319

1320 1321
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1322 1323
            ALOGD("calling sign in state: %d", state);
            return state;
1324
        }
1325

Kenny Root's avatar
Kenny Root committed
1326 1327
        Blob keyBlob;
        String8 name8(name);
1328

1329
        ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root's avatar
Kenny Root committed
1330
        int rc;
1331

1332 1333
        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
                ::TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
1334 1335 1336
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1337

Kenny Root's avatar
Kenny Root committed
1338 1339 1340 1341 1342
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            ALOGE("no keymaster device; cannot sign");
            return ::SYSTEM_ERROR;
        }
1343

Kenny Root's avatar
Kenny Root committed
1344 1345 1346 1347
        if (device->sign_data == NULL) {
            ALOGE("device doesn't implement signing");
            return ::SYSTEM_ERROR;
        }
1348

Kenny Root's avatar
Kenny Root committed
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
        keymaster_rsa_sign_params_t params;
        params.digest_type = DIGEST_NONE;
        params.padding_type = PADDING_NONE;

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

Kenny Root's avatar
Kenny Root committed
1360
        return ::NO_ERROR;
1361 1362
    }

Kenny Root's avatar
Kenny Root committed
1363 1364
    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
            const uint8_t* signature, size_t signatureLength) {
1365 1366 1367
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_VERIFY)) {
            ALOGW("permission denied for %d: verify", callingUid);
Kenny Root's avatar
Kenny Root committed
1368 1369
            return ::PERMISSION_DENIED;
        }
1370

1371 1372
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1373 1374 1375
            ALOGD("calling verify in state: %d", state);
            return state;
        }
1376

Kenny Root's avatar
Kenny Root committed
1377 1378 1379
        Blob keyBlob;
        String8 name8(name);
        int rc;
1380

1381 1382
        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
                TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
1383 1384 1385
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1386

Kenny Root's avatar
Kenny Root committed
1387 1388 1389 1390
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1391

Kenny Root's avatar
Kenny Root committed
1392 1393 1394 1395 1396 1397 1398
        if (device->verify_data == NULL) {
            return ::SYSTEM_ERROR;
        }

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

Kenny Root's avatar
Kenny Root committed
1400 1401 1402 1403 1404 1405 1406
        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
                data, dataLength, signature, signatureLength);
        if (rc) {
            return ::SYSTEM_ERROR;
        } else {
            return ::NO_ERROR;
        }
1407 1408
    }

Kenny Root's avatar
Kenny Root committed
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    /*
     * 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) {
1421 1422 1423
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GET)) {
            ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root's avatar
Kenny Root committed
1424 1425
            return ::PERMISSION_DENIED;
        }
1426

1427 1428
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1429 1430 1431
            ALOGD("calling get_pubkey in state: %d", state);
            return state;
        }
1432

Kenny Root's avatar
Kenny Root committed
1433 1434
        Blob keyBlob;
        String8 name8(name);
1435

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

1438
        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root's avatar
Kenny Root committed
1439 1440 1441 1442
                TYPE_KEY_PAIR);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1443

Kenny Root's avatar
Kenny Root committed
1444 1445 1446 1447
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1448

Kenny Root's avatar
Kenny Root committed
1449 1450 1451 1452
        if (device->get_keypair_public == NULL) {
            ALOGE("device has no get_keypair_public implementation!");
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
1453

Kenny Root's avatar
Kenny Root committed
1454 1455 1456 1457 1458
        int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
                pubkeyLength);
        if (rc) {
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
1459

Kenny Root's avatar
Kenny Root committed
1460
        return ::NO_ERROR;
Kenny Root's avatar
Kenny Root committed
1461 1462
    }

1463
    int32_t del_key(const String16& name, int targetUid) {
1464 1465 1466
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_DELETE)) {
            ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root's avatar
Kenny Root committed
1467 1468
            return ::PERMISSION_DENIED;
        }
Kenny Root's avatar
Kenny Root committed
1469

1470 1471 1472
        if (targetUid == -1) {
            targetUid = callingUid;
        } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1473 1474 1475
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1476 1477
        String8 name8(name);
        char filename[NAME_MAX];
Kenny Root's avatar
Kenny Root committed
1478

1479
        encode_key_for_uid(filename, targetUid, name8);
Kenny Root's avatar
Kenny Root committed
1480

Kenny Root's avatar
Kenny Root committed
1481 1482 1483 1484 1485
        Blob keyBlob;
        ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
1486

Kenny Root's avatar
Kenny Root committed
1487
        ResponseCode rc = ::NO_ERROR;
1488

Kenny Root's avatar
Kenny Root committed
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            rc = ::SYSTEM_ERROR;
        } else {
            // A device doesn't have to implement delete_keypair.
            if (device->delete_keypair != NULL) {
                if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
                    rc = ::SYSTEM_ERROR;
                }
            }
        }
1500

Kenny Root's avatar
Kenny Root committed
1501 1502 1503
        if (rc != ::NO_ERROR) {
            return rc;
        }
1504

Kenny Root's avatar
Kenny Root committed
1505
        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1506
    }
Kenny Root's avatar
Kenny Root committed
1507 1508

    int32_t grant(const String16& name, int32_t granteeUid) {
1509 1510 1511
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GRANT)) {
            ALOGW("permission denied for %d: grant", callingUid);
Kenny Root's avatar
Kenny Root committed
1512 1513 1514
            return ::PERMISSION_DENIED;
        }

1515 1516
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1517 1518 1519 1520 1521 1522 1523
            ALOGD("calling grant in state: %d", state);
            return state;
        }

        String8 name8(name);
        char filename[NAME_MAX];

1524
        encode_key_for_uid(filename, callingUid, name8);
Kenny Root's avatar
Kenny Root committed
1525 1526 1527 1528 1529 1530 1531

        if (access(filename, R_OK) == -1) {
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

        mKeyStore->addGrant(filename, granteeUid);
        return ::NO_ERROR;
1532
    }
Kenny Root's avatar
Kenny Root committed
1533 1534

    int32_t ungrant(const String16& name, int32_t granteeUid) {
1535 1536 1537
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GRANT)) {
            ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root's avatar
Kenny Root committed
1538 1539 1540
            return ::PERMISSION_DENIED;
        }

1541 1542
        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
Kenny Root's avatar
Kenny Root committed
1543 1544 1545 1546 1547 1548 1549
            ALOGD("calling ungrant in state: %d", state);
            return state;
        }

        String8 name8(name);
        char filename[NAME_MAX];

1550
        encode_key_for_uid(filename, callingUid, name8);
Kenny Root's avatar
Kenny Root committed
1551 1552 1553 1554 1555 1556

        if (access(filename, R_OK) == -1) {
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

        return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1557
    }
Kenny Root's avatar
Kenny Root committed
1558 1559

    int64_t getmtime(const String16& name) {
1560 1561 1562
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_GET)) {
            ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root's avatar
Kenny Root committed
1563
            return -1L;
Kenny Root's avatar
Kenny Root committed
1564 1565 1566 1567 1568
        }

        String8 name8(name);
        char filename[NAME_MAX];

1569
        encode_key_for_uid(filename, callingUid, name8);
Kenny Root's avatar
Kenny Root committed
1570 1571

        if (access(filename, R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
1572 1573
            ALOGW("could not access %s for getmtime", filename);
            return -1L;
1574
        }
Kenny Root's avatar
Kenny Root committed
1575

1576
        int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root's avatar
Kenny Root committed
1577
        if (fd < 0) {
Kenny Root's avatar
Kenny Root committed
1578 1579
            ALOGW("could not open %s for getmtime", filename);
            return -1L;
Kenny Root's avatar
Kenny Root committed
1580 1581 1582 1583 1584 1585
        }

        struct stat s;
        int ret = fstat(fd, &s);
        close(fd);
        if (ret == -1) {
Kenny Root's avatar
Kenny Root committed
1586 1587
            ALOGW("could not stat %s for getmtime", filename);
            return -1L;
Kenny Root's avatar
Kenny Root committed
1588 1589
        }

Kenny Root's avatar
Kenny Root committed
1590
        return static_cast<int64_t>(s.st_mtime);
1591
    }
Kenny Root's avatar
Kenny Root committed
1592

1593 1594
    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
            int32_t destUid) {
Kenny Root's avatar
Kenny Root committed
1595
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1596 1597
        if (!has_permission(callingUid, P_DUPLICATE)) {
            ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root's avatar
Kenny Root committed
1598 1599 1600 1601 1602
            return -1L;
        }

        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
1603
            ALOGD("calling duplicate in state: %d", state);
Kenny Root's avatar
Kenny Root committed
1604 1605 1606
            return state;
        }

1607 1608 1609 1610
        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
1611 1612 1613
            return ::PERMISSION_DENIED;
        }

1614 1615 1616
        if (destUid == -1) {
            destUid = callingUid;
        }
Kenny Root's avatar
Kenny Root committed
1617

1618 1619 1620 1621 1622 1623
        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
1624

1625 1626 1627 1628
            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
1629 1630
        }

1631 1632 1633 1634 1635 1636
        String8 source8(srcKey);
        char source[NAME_MAX];

        encode_key_for_uid(source, srcUid, source8);

        String8 target8(destKey);
Kenny Root's avatar
Kenny Root committed
1637 1638
        char target[NAME_MAX];

1639
        encode_key_for_uid(target, destUid, target8);
Kenny Root's avatar
Kenny Root committed
1640

1641 1642
        if (access(target, W_OK) != -1 || errno != ENOENT) {
            ALOGD("destination already exists: %s", target);
Kenny Root's avatar
Kenny Root committed
1643 1644 1645
            return ::SYSTEM_ERROR;
        }

1646 1647 1648 1649
        Blob keyBlob;
        ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
Kenny Root's avatar
Kenny Root committed
1650
        }
1651 1652

        return mKeyStore->put(target, &keyBlob);
Kenny Root's avatar
Kenny Root committed
1653 1654
    }

1655 1656 1657 1658
    int32_t is_hardware_backed() {
        return mKeyStore->isHardwareBacked() ? 1 : 0;
    }

Kenny Root's avatar
Kenny Root committed
1659
private:
1660 1661 1662 1663 1664 1665 1666 1667 1668
    inline bool isKeystoreUnlocked(State state) {
        switch (state) {
        case ::STATE_NO_ERROR:
            return true;
        case ::STATE_UNINITIALIZED:
        case ::STATE_LOCKED:
            return false;
        }
        return false;
1669
    }
Kenny Root's avatar
Kenny Root committed
1670 1671 1672 1673 1674

    ::KeyStore* mKeyStore;
};

}; // namespace android
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689

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;
    }
1690 1691 1692 1693 1694 1695 1696 1697

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

    KeyStore keyStore(&entropy, dev);
Kenny Root's avatar
Kenny Root committed
1698 1699 1700 1701 1702 1703
    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;
1704
    }
1705

Kenny Root's avatar
Kenny Root committed
1706 1707 1708 1709 1710
    /*
     * 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();
1711

Kenny Root's avatar
Kenny Root committed
1712
    keymaster_device_release(dev);
1713 1714
    return 1;
}