keystore.cpp 54.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,
140
    P_CLEAR_UID = 1 << 15,
Kenny Root's avatar
Kenny Root committed
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 175
} 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;
}

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

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

207 208 209 210 211 212 213
/* 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
214 215 216
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();
217 218 219 220 221 222 223 224 225 226
    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';
227 228 229
    return length;
}

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

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

Kenny Root's avatar
Kenny Root committed
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 266
/*
 * 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;
267
        } else {
Kenny Root's avatar
Kenny Root committed
268
            *out++ = *in;
269 270 271 272 273 274 275 276
        }
    }
    *out = '\0';
}

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

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

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

Kenny Root's avatar
Kenny Root committed
320
    bool generate_random_data(uint8_t* data, size_t size) const {
321 322 323 324 325 326 327 328 329 330 331
        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
332 333
 * 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
334 335 336
 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
 * and decryptBlob(). Thus they should not be accessed from outside. */

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

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

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

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

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

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

    Blob(blob b) {
        mBlob = b;
    }

    Blob() {}

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

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

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

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

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    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);
    }

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

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

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

    ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
479 480
        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
        if (in < 0) {
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 516
            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
517
        return ::NO_ERROR;
518 519 520 521 522 523
    }

private:
    struct blob mBlob;
};

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

    struct listnode plist;
} grant_t;

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

        list_init(&mGrants);
545 546
    }

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

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

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

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

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

Kenny Root's avatar
Kenny Root committed
580
    ResponseCode readMasterKey(const android::String8& pw) {
581 582
        int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
        if (in < 0) {
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 653
            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
654
    bool isEmpty() const {
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        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);
    }

676 677 678 679 680 681 682
    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
683
        if (version < CURRENT_BLOB_VERSION) {
684 685 686
            upgrade(filename, keyBlob, version, type);
        }

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

        return rc;
693 694 695 696 697 698
    }

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

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

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

        return false;
    }

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

Kenny Root's avatar
Kenny Root committed
724
    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
725 726 727 728 729 730 731 732 733
        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
734
        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
735 736 737 738 739 740 741 742 743 744 745
        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);
    }

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

750 751 752 753 754 755 756 757 758 759
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;

760 761
    keymaster_device_t* mDevice;

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

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

    AES_KEY mMasterKeyEncryption;
    AES_KEY mMasterKeyDecryption;

771 772
    struct listnode mGrants;

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

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

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

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

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

        return NULL;
    }

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    /**
     * 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;
        }

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

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

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

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

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

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

931 932 933 934
    // 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);
935
        responseCode = keyStore->get(filename, keyBlob, type);
936 937 938 939 940 941
        if (responseCode == NO_ERROR) {
            return responseCode;
        }
    }

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

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

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

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

Kenny Root's avatar
Kenny Root committed
963
    int32_t test() {
964 965 966
        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
967 968
            return ::PERMISSION_DENIED;
        }
969

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

Kenny Root's avatar
Kenny Root committed
973
    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
974 975 976
        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
977 978
            return ::PERMISSION_DENIED;
        }
979

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

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

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

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

        return ::NO_ERROR;
1004 1005
    }

1006
    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
1007 1008 1009
        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
1010 1011 1012
            return ::PERMISSION_DENIED;
        }

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

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

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

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

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

1034
    int32_t del(const String16& name, int targetUid) {
1035 1036 1037
        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
1038 1039 1040
            return ::PERMISSION_DENIED;
        }

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

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

1050
        encode_key_for_uid(filename, targetUid, name8);
1051

Kenny Root's avatar
Kenny Root committed
1052 1053 1054 1055 1056 1057
        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;
1058 1059
    }

1060
    int32_t exist(const String16& name, int targetUid) {
1061 1062 1063
        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
1064 1065 1066
            return ::PERMISSION_DENIED;
        }

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

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

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

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

1084
    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1085 1086 1087
        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
1088 1089 1090
            return ::PERMISSION_DENIED;
        }

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

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

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

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

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

Kenny Root's avatar
Kenny Root committed
1129
    int32_t reset() {
1130 1131 1132
        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
1133 1134
            return ::PERMISSION_DENIED;
        }
1135

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

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

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

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

        return rc;
1155 1156
    }

Kenny Root's avatar
Kenny Root committed
1157 1158 1159 1160 1161 1162 1163 1164
    /*
     * 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) {
1165 1166 1167
        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
1168 1169
            return ::PERMISSION_DENIED;
        }
1170

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

Kenny Root's avatar
Kenny Root committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        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;
    }
1189

Kenny Root's avatar
Kenny Root committed
1190
    int32_t lock() {
1191 1192 1193
        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
1194 1195 1196
            return ::PERMISSION_DENIED;
        }

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

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

Kenny Root's avatar
Kenny Root committed
1207
    int32_t unlock(const String16& pw) {
1208 1209 1210
        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
1211 1212 1213
            return ::PERMISSION_DENIED;
        }

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

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

Kenny Root's avatar
Kenny Root committed
1224
    int32_t zero() {
1225 1226 1227
        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
1228 1229
            return -1;
        }
1230

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

1234
    int32_t generate(const String16& name, int targetUid) {
1235 1236 1237
        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
1238 1239
            return ::PERMISSION_DENIED;
        }
1240

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

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

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

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

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

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

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

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

1278
        encode_key_for_uid(filename, targetUid, name8);
1279

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

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

1286
    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
1287 1288 1289
        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
1290 1291
            return ::PERMISSION_DENIED;
        }
1292

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

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

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

1308
        encode_key_for_uid(filename, targetUid, name8);
1309

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

Kenny Root's avatar
Kenny Root committed
1313 1314
    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
            size_t* outLength) {
1315 1316 1317
        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
1318 1319
            return ::PERMISSION_DENIED;
        }
1320

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

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

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

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

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

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

Kenny Root's avatar
Kenny Root committed
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
        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;
        }
1360

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

Kenny Root's avatar
Kenny Root committed
1364 1365
    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
            const uint8_t* signature, size_t signatureLength) {
1366 1367 1368
        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
1369 1370
            return ::PERMISSION_DENIED;
        }
1371

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

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

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

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

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

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

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

Kenny Root's avatar
Kenny Root committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    /*
     * 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) {
1422 1423 1424
        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
1425 1426
            return ::PERMISSION_DENIED;
        }
1427

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

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

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

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

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

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

Kenny Root's avatar
Kenny Root committed
1455 1456 1457 1458 1459
        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
1460

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

1464
    int32_t del_key(const String16& name, int targetUid) {
1465 1466 1467
        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
1468 1469
            return ::PERMISSION_DENIED;
        }
Kenny Root's avatar
Kenny Root committed
1470

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

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

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

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

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

Kenny Root's avatar
Kenny Root committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
        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;
                }
            }
        }
1501

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

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

    int32_t grant(const String16& name, int32_t granteeUid) {
1510 1511 1512
        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
1513 1514 1515
            return ::PERMISSION_DENIED;
        }

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

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

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

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

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

    int32_t ungrant(const String16& name, int32_t granteeUid) {
1536 1537 1538
        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
1539 1540 1541
            return ::PERMISSION_DENIED;
        }

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

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

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

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

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

    int64_t getmtime(const String16& name) {
1561 1562 1563
        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
1564
            return -1L;
Kenny Root's avatar
Kenny Root committed
1565 1566 1567 1568 1569
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

        encode_key_for_uid(source, srcUid, source8);

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

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

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

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

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

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

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    int32_t clear_uid(int64_t targetUid) {
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!has_permission(callingUid, P_CLEAR_UID)) {
            ALOGW("permission denied for %d: clear_uid", callingUid);
            return ::PERMISSION_DENIED;
        }

        State state = mKeyStore->getState();
        if (!isKeystoreUnlocked(state)) {
            ALOGD("calling clear_uid in state: %d", state);
            return state;
        }

        const keymaster_device_t* device = mKeyStore->getDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }

        DIR* dir = opendir(".");
        if (!dir) {
            return ::SYSTEM_ERROR;
        }

        char filename[NAME_MAX];
        int n = snprintf(filename, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
        char *end = &filename[n];

        ResponseCode rc = ::NO_ERROR;

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
            if (strncmp(filename, file->d_name, n)) {
                continue;
            }

            String8 file8(&file->d_name[n]);
            encode_key(end, file8);

            Blob keyBlob;
            if (mKeyStore->get(filename, &keyBlob, ::TYPE_ANY) != ::NO_ERROR) {
                ALOGW("couldn't open %s", filename);
                continue;
            }

            if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
                // A device doesn't have to implement delete_keypair.
                if (device->delete_keypair != NULL) {
                    if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
                        rc = ::SYSTEM_ERROR;
                        ALOGW("device couldn't remove %s", filename);
                    }
                }
            }

            if (unlink(filename) && errno != ENOENT) {
                rc = ::SYSTEM_ERROR;
                ALOGW("couldn't unlink %s", filename);
            }
        }
        closedir(dir);

        return rc;
    }

Kenny Root's avatar
Kenny Root committed
1724
private:
1725 1726 1727 1728 1729 1730 1731 1732 1733
    inline bool isKeystoreUnlocked(State state) {
        switch (state) {
        case ::STATE_NO_ERROR:
            return true;
        case ::STATE_UNINITIALIZED:
        case ::STATE_LOCKED:
            return false;
        }
        return false;
1734
    }
Kenny Root's avatar
Kenny Root committed
1735 1736 1737 1738 1739

    ::KeyStore* mKeyStore;
};

}; // namespace android
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754

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;
    }
1755 1756 1757 1758 1759 1760 1761 1762

    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
1763 1764 1765 1766 1767 1768
    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;
1769
    }
1770

Kenny Root's avatar
Kenny Root committed
1771 1772 1773 1774 1775
    /*
     * 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();
1776

Kenny Root's avatar
Kenny Root committed
1777
    keymaster_device_release(dev);
1778 1779
    return 1;
}