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

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

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

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

44
#include <hardware/keymaster0.h>
45

46
#include <keymaster/softkeymaster.h>
47
#include <keymaster/soft_keymaster_device.h>
48

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

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

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

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

63 64
#include <selinux/android.h>

Chad Brubaker's avatar
Chad Brubaker committed
65
#include "auth_token_table.h"
66
#include "defaults.h"
67
#include "operation.h"
68

69 70 71 72 73 74 75 76 77 78
/* 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

79

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

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

108
static int keymaster_device_initialize(keymaster0_device_t** dev) {
109 110 111 112 113 114 115 116 117
    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;
    }

118
    rc = keymaster0_open(mod, dev);
119 120 121 122 123 124 125 126 127 128 129 130 131
    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;
}

132 133 134 135 136
static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
    keymaster::SoftKeymasterDevice* softkeymaster =
            new keymaster::SoftKeymasterDevice();
    // SoftKeymasterDevice is designed to make this cast safe.
    *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
137 138 139
    return 0;
}

140 141
static void keymaster_device_release(keymaster0_device_t* dev) {
    keymaster0_close(dev);
142 143
}

Kenny Root's avatar
Kenny Root committed
144 145 146 147 148 149
/***************
 * PERMISSIONS *
 ***************/

/* Here are the permissions, actions, users, and the main function. */
typedef enum {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    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,
    P_CLEAR_UID     = 1 << 15,
    P_RESET_UID     = 1 << 16,
    P_SYNC_UID      = 1 << 17,
    P_PASSWORD_UID  = 1 << 18,
Chad Brubaker's avatar
Chad Brubaker committed
169
    P_ADD_AUTH      = 1 << 19,
Kenny Root's avatar
Kenny Root committed
170 171 172 173 174 175 176 177 178 179 180
} 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},
};

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/* perm_labels associcated with keystore_key SELinux class verbs. */
const char *perm_labels[] = {
    "test",
    "get",
    "insert",
    "delete",
    "exist",
    "saw",
    "reset",
    "password",
    "lock",
    "unlock",
    "zero",
    "sign",
    "verify",
    "grant",
    "duplicate",
198 199 200 201
    "clear_uid",
    "reset_uid",
    "sync_uid",
    "password_uid",
Chad Brubaker's avatar
Chad Brubaker committed
202
    "add_auth",
203 204
};

Kenny Root's avatar
Kenny Root committed
205 206 207 208 209 210 211 212 213 214 215 216 217
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);

218 219 220 221 222 223 224 225 226 227 228 229 230
static char *tctx;
static int ks_is_selinux_enabled;

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

Kenny Root's avatar
Kenny Root committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
/**
 * Returns the app ID (in the Android multi-user sense) for the current
 * UNIX UID.
 */
static uid_t get_app_id(uid_t uid) {
    return uid % AID_USER;
}

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

247
static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    if (!ks_is_selinux_enabled) {
        return true;
    }

    char *sctx = NULL;
    const char *selinux_class = "keystore_key";
    const char *str_perm = get_perm_label(perm);

    if (!str_perm) {
        return false;
    }

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

265 266 267 268 269 270 271
    bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
            NULL) == 0;
    freecon(sctx);
    return allowed;
}

static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root's avatar
Kenny Root committed
272 273 274 275 276
    // All system users are equivalent for multi-user support.
    if (get_app_id(uid) == AID_SYSTEM) {
        uid = AID_SYSTEM;
    }

Kenny Root's avatar
Kenny Root committed
277 278 279
    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) {
280 281
            return (user.perms & perm) &&
                keystore_selinux_check_access(uid, perm, spid);
Kenny Root's avatar
Kenny Root committed
282 283 284
        }
    }

285 286
    return (DEFAULT_PERMS & perm) &&
        keystore_selinux_check_access(uid, perm, spid);
Kenny Root's avatar
Kenny Root committed
287 288
}

289 290 291 292 293
/**
 * 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
294 295 296 297 298 299 300 301 302 303 304
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;
}

305 306 307 308 309
/**
 * 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) {
310 311 312
    if (callingUid == targetUid) {
        return true;
    }
313 314 315 316 317 318 319 320 321 322
    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;
}

323 324 325 326 327 328 329
/* 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
330 331 332 333 334 335 336 337 338 339 340
static size_t encode_key_length(const android::String8& keyName) {
    const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
    size_t length = keyName.length();
    for (int i = length; i > 0; --i, ++in) {
        if (*in < '0' || *in > '~') {
            ++length;
        }
    }
    return length;
}

Kenny Root's avatar
Kenny Root committed
341 342 343
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();
344
    for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root's avatar
Kenny Root committed
345
        if (*in < '0' || *in > '~') {
346 347 348
            *out = '+' + (*in >> 6);
            *++out = '0' + (*in & 0x3F);
            ++length;
Kenny Root's avatar
Kenny Root committed
349 350
        } else {
            *out = *in;
351 352 353
        }
    }
    *out = '\0';
354 355 356
    return length;
}

Kenny Root's avatar
Kenny Root committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
/*
 * 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;
387
        } else {
Kenny Root's avatar
Kenny Root committed
388
            *out++ = *in;
389 390 391 392 393 394 395 396
        }
    }
    *out = '\0';
}

static size_t readFully(int fd, uint8_t* data, size_t size) {
    size_t remaining = size;
    while (remaining > 0) {
397
        ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root's avatar
Kenny Root committed
398
        if (n <= 0) {
399
            return size - remaining;
400 401 402 403 404 405 406 407 408 409
        }
        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) {
410 411 412 413
        ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
        if (n < 0) {
            ALOGW("write failed: %s", strerror(errno));
            return size - remaining;
414 415 416 417 418 419 420 421 422 423 424
        }
        data += n;
        remaining -= n;
    }
    return size;
}

class Entropy {
public:
    Entropy() : mRandom(-1) {}
    ~Entropy() {
425
        if (mRandom >= 0) {
426 427 428 429 430 431
            close(mRandom);
        }
    }

    bool open() {
        const char* randomDevice = "/dev/urandom";
432 433
        mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
        if (mRandom < 0) {
434 435 436 437 438 439
            ALOGE("open: %s: %s", randomDevice, strerror(errno));
            return false;
        }
        return true;
    }

Kenny Root's avatar
Kenny Root committed
440
    bool generate_random_data(uint8_t* data, size_t size) const {
441 442 443 444 445 446 447 448 449 450 451
        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
452
 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
453
 * the second is the blob's type, and the third byte is flags. Fields other
454 455 456
 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
 * and decryptBlob(). Thus they should not be accessed from outside. */

457 458 459 460 461 462 463 464 465 466 467 468 469 470
/* ** 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))
 */
471
struct __attribute__((packed)) blob {
472 473
    uint8_t version;
    uint8_t type;
474
    uint8_t flags;
475 476
    uint8_t info;
    uint8_t vector[AES_BLOCK_SIZE];
477
    uint8_t encrypted[0]; // Marks offset to encrypted data.
478
    uint8_t digest[MD5_DIGEST_LENGTH];
479
    uint8_t digested[0]; // Marks offset to digested data.
480 481 482 483
    int32_t length; // in network byte order when encrypted
    uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
};

484
typedef enum {
485
    TYPE_ANY = 0, // meta type that matches anything
486 487 488
    TYPE_GENERIC = 1,
    TYPE_MASTER_KEY = 2,
    TYPE_KEY_PAIR = 3,
489
    TYPE_KEYMASTER_10 = 4,
490 491
} BlobType;

492
static const uint8_t CURRENT_BLOB_VERSION = 2;
493

494 495
class Blob {
public:
Kenny Root's avatar
Kenny Root committed
496 497
    Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
            BlobType type) {
498 499 500 501 502
        mBlob.length = valueLength;
        memcpy(mBlob.value, value, valueLength);

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

Kenny Root's avatar
Kenny Root committed
504
        mBlob.version = CURRENT_BLOB_VERSION;
505
        mBlob.type = uint8_t(type);
506

507 508 509 510 511
        if (type == TYPE_MASTER_KEY) {
            mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
        } else {
            mBlob.flags = KEYSTORE_FLAG_NONE;
        }
512 513 514 515 516 517 518 519
    }

    Blob(blob b) {
        mBlob = b;
    }

    Blob() {}

Kenny Root's avatar
Kenny Root committed
520
    const uint8_t* getValue() const {
521 522 523
        return mBlob.value;
    }

Kenny Root's avatar
Kenny Root committed
524
    int32_t getLength() const {
525 526 527
        return mBlob.length;
    }

Kenny Root's avatar
Kenny Root committed
528 529 530 531 532
    const uint8_t* getInfo() const {
        return mBlob.value + mBlob.length;
    }

    uint8_t getInfoLength() const {
533 534 535
        return mBlob.info;
    }

536 537 538 539
    uint8_t getVersion() const {
        return mBlob.version;
    }

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    bool isEncrypted() const {
        if (mBlob.version < 2) {
            return true;
        }

        return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
    }

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

556 557 558 559 560 561 562 563 564 565 566 567
    bool isFallback() const {
        return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
    }

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

568 569 570 571 572 573 574 575 576 577 578 579
    void setVersion(uint8_t version) {
        mBlob.version = version;
    }

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

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

580 581 582 583 584 585 586 587 588 589 590 591
    ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
        ALOGV("writing blob %s", filename);
        if (isEncrypted()) {
            if (state != STATE_NO_ERROR) {
                ALOGD("couldn't insert encrypted blob while not unlocked");
                return LOCKED;
            }

            if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
                ALOGW("Could not read random data for: %s", filename);
                return SYSTEM_ERROR;
            }
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        }

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

608 609 610 611 612 613 614 615
        if (isEncrypted()) {
            MD5(mBlob.digested, digestedLength, mBlob.digest);

            uint8_t vector[AES_BLOCK_SIZE];
            memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
            AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
                            aes_key, vector, AES_ENCRYPT);
        }
616 617 618 619 620

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

        const char* tmpFileName = ".tmp";
621 622 623 624
        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));
625 626 627 628 629 630 631
            return SYSTEM_ERROR;
        }
        size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
        if (close(out) != 0) {
            return SYSTEM_ERROR;
        }
        if (writtenBytes != fileLength) {
632
            ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
633 634 635
            unlink(tmpFileName);
            return SYSTEM_ERROR;
        }
636 637 638 639 640
        if (rename(tmpFileName, filename) == -1) {
            ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
            return SYSTEM_ERROR;
        }
        return NO_ERROR;
641 642
    }

643 644
    ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
        ALOGV("reading blob %s", filename);
645 646
        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
        if (in < 0) {
647 648 649 650 651 652 653 654 655
            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;
        }
656 657 658 659 660

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

661 662 663 664 665 666
        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
        if (fileLength < headerLength) {
            return VALUE_CORRUPTED;
        }

        ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
667
        if (encryptedLength < 0) {
668 669
            return VALUE_CORRUPTED;
        }
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

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

            AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
                            mBlob.vector, AES_DECRYPT);
            digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
            uint8_t computedDigest[MD5_DIGEST_LENGTH];
            MD5(mBlob.digested, digestedLength, computedDigest);
            if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
                return VALUE_CORRUPTED;
            }
        } else {
            digestedLength = encryptedLength;
687 688 689 690 691 692 693 694 695 696 697
        }

        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
698
        return ::NO_ERROR;
699 700 701 702 703 704
    }

private:
    struct blob mBlob;
};

Kenny Root's avatar
Kenny Root committed
705 706 707 708 709 710
class UserState {
public:
    UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
        asprintf(&mUserDir, "user_%u", mUserId);
        asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
    }
711

Kenny Root's avatar
Kenny Root committed
712 713 714 715
    ~UserState() {
        free(mUserDir);
        free(mMasterKeyFile);
    }
716

Kenny Root's avatar
Kenny Root committed
717 718 719 720 721 722 723
    bool initialize() {
        if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
            ALOGE("Could not create directory '%s'", mUserDir);
            return false;
        }

        if (access(mMasterKeyFile, R_OK) == 0) {
724 725 726 727
            setState(STATE_LOCKED);
        } else {
            setState(STATE_UNINITIALIZED);
        }
728

Kenny Root's avatar
Kenny Root committed
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        return true;
    }

    uid_t getUserId() const {
        return mUserId;
    }

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

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

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

Kenny Root's avatar
Kenny Root committed
751
    State getState() const {
752 753 754
        return mState;
    }

Kenny Root's avatar
Kenny Root committed
755
    int8_t getRetry() const {
756 757 758
        return mRetry;
    }

Kenny Root's avatar
Kenny Root committed
759 760 761 762 763
    void zeroizeMasterKeysInMemory() {
        memset(mMasterKey, 0, sizeof(mMasterKey));
        memset(mSalt, 0, sizeof(mSalt));
        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
764 765
    }

Kenny Root's avatar
Kenny Root committed
766 767
    ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
        if (!generateMasterKey(entropy)) {
768 769
            return SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
770
        ResponseCode response = writeMasterKey(pw, entropy);
771 772 773 774
        if (response != NO_ERROR) {
            return response;
        }
        setupMasterKeys();
Kenny Root's avatar
Kenny Root committed
775
        return ::NO_ERROR;
776 777
    }

778 779 780 781 782 783 784 785 786 787 788 789
    ResponseCode copyMasterKey(UserState* src) {
        if (mState != STATE_UNINITIALIZED) {
            return ::SYSTEM_ERROR;
        }
        if (src->getState() != STATE_NO_ERROR) {
            return ::SYSTEM_ERROR;
        }
        memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
        setupMasterKeys();
        return ::NO_ERROR;
    }

Kenny Root's avatar
Kenny Root committed
790
    ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
791 792 793 794
        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);
795
        Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
796
        return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
797 798
    }

Kenny Root's avatar
Kenny Root committed
799 800
    ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
        int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
801
        if (in < 0) {
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
            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);
824 825
        ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
                STATE_NO_ERROR);
826
        if (response == SYSTEM_ERROR) {
827
            return response;
828 829 830 831
        }
        if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
            // if salt was missing, generate one and write a new master key file with the salt.
            if (salt == NULL) {
Kenny Root's avatar
Kenny Root committed
832
                if (!generateSalt(entropy)) {
833 834
                    return SYSTEM_ERROR;
                }
Kenny Root's avatar
Kenny Root committed
835
                response = writeMasterKey(pw, entropy);
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
            }
            if (response == NO_ERROR) {
                memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
                setupMasterKeys();
            }
            return response;
        }
        if (mRetry <= 0) {
            reset();
            return UNINITIALIZED;
        }
        --mRetry;
        switch (mRetry) {
            case 0: return WRONG_PASSWORD_0;
            case 1: return WRONG_PASSWORD_1;
            case 2: return WRONG_PASSWORD_2;
            case 3: return WRONG_PASSWORD_3;
            default: return WRONG_PASSWORD_3;
        }
    }

Kenny Root's avatar
Kenny Root committed
857 858 859
    AES_KEY* getEncryptionKey() {
        return &mMasterKeyEncryption;
    }
860

Kenny Root's avatar
Kenny Root committed
861 862 863
    AES_KEY* getDecryptionKey() {
        return &mMasterKeyDecryption;
    }
864

Kenny Root's avatar
Kenny Root committed
865 866
    bool reset() {
        DIR* dir = opendir(getUserDirName());
867
        if (!dir) {
Kenny Root's avatar
Kenny Root committed
868
            ALOGW("couldn't open user directory: %s", strerror(errno));
869 870
            return false;
        }
Kenny Root's avatar
Kenny Root committed
871 872

        struct dirent* file;
873
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
874 875 876 877 878 879
            // We only care about files.
            if (file->d_type != DT_REG) {
                continue;
            }

            // Skip anything that starts with a "."
880
            if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root's avatar
Kenny Root committed
881 882 883 884
                continue;
            }

            unlinkat(dirfd(dir), file->d_name, 0);
885 886 887 888 889
        }
        closedir(dir);
        return true;
    }

Kenny Root's avatar
Kenny Root committed
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
private:
    static const int MASTER_KEY_SIZE_BYTES = 16;
    static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;

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

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

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

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

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

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

    uid_t mUserId;

    char* mUserDir;
    char* mMasterKeyFile;

    State mState;
    int8_t mRetry;

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

    AES_KEY mMasterKeyEncryption;
    AES_KEY mMasterKeyDecryption;
};

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

class KeyStore {
public:
955
    KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root's avatar
Kenny Root committed
956 957
        : mEntropy(entropy)
        , mDevice(device)
958
        , mFallbackDevice(fallback)
Kenny Root's avatar
Kenny Root committed
959 960 961 962 963 964 965 966 967
    {
        memset(&mMetaData, '\0', sizeof(mMetaData));
    }

    ~KeyStore() {
        for (android::Vector<grant_t*>::iterator it(mGrants.begin());
                it != mGrants.end(); it++) {
            delete *it;
        }
haitao fang's avatar
haitao fang committed
968
        mGrants.clear();
Kenny Root's avatar
Kenny Root committed
969 970 971 972 973

        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
                it != mMasterKeys.end(); it++) {
            delete *it;
        }
haitao fang's avatar
haitao fang committed
974
        mMasterKeys.clear();
Kenny Root's avatar
Kenny Root committed
975 976
    }

977 978 979 980 981 982 983
    /**
     * Depending on the hardware keymaster version is this may return a
     * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
     * keymaster0 are safe to call, calls to keymaster1_device_t methods should
     * be guarded by a check on the device's version.
     */
    keymaster1_device_t *getDevice() const {
Kenny Root's avatar
Kenny Root committed
984 985 986
        return mDevice;
    }

987
    keymaster1_device_t *getFallbackDevice() const {
988 989 990
        return mFallbackDevice;
    }

991
    keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
992 993 994
        return blob.isFallback() ? mFallbackDevice: mDevice;
    }

Kenny Root's avatar
Kenny Root committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    ResponseCode initialize() {
        readMetaData();
        if (upgradeKeystore()) {
            writeMetaData();
        }

        return ::NO_ERROR;
    }

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

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

1013 1014 1015 1016 1017 1018
    ResponseCode copyMasterKey(uid_t src, uid_t uid) {
        UserState *userState = getUserState(uid);
        UserState *initState = getUserState(src);
        return userState->copyMasterKey(initState);
    }

Kenny Root's avatar
Kenny Root committed
1019
    ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
1020
        UserState* userState = getUserState(uid);
Kenny Root's avatar
Kenny Root committed
1021 1022 1023 1024
        return userState->writeMasterKey(pw, mEntropy);
    }

    ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
1025
        UserState* userState = getUserState(uid);
Kenny Root's avatar
Kenny Root committed
1026 1027 1028 1029
        return userState->readMasterKey(pw, mEntropy);
    }

    android::String8 getKeyName(const android::String8& keyName) {
1030
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
1031 1032 1033 1034 1035
        encode_key(encoded, keyName);
        return android::String8(encoded);
    }

    android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
1036
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
1037 1038 1039 1040 1041
        encode_key(encoded, keyName);
        return android::String8::format("%u_%s", uid, encoded);
    }

    android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
1042
        char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
Kenny Root's avatar
Kenny Root committed
1043 1044 1045 1046 1047 1048
        encode_key(encoded, keyName);
        return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
                encoded);
    }

    bool reset(uid_t uid) {
1049 1050 1051 1052 1053 1054
        android::String8 prefix("");
        android::Vector<android::String16> aliases;
        if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
            return ::SYSTEM_ERROR;
        }

Kenny Root's avatar
Kenny Root committed
1055
        UserState* userState = getUserState(uid);
1056 1057 1058 1059 1060 1061 1062
        for (uint32_t i = 0; i < aliases.size(); i++) {
            android::String8 filename(aliases[i]);
            filename = android::String8::format("%s/%s", userState->getUserDirName(),
                    getKeyName(filename).string());
            del(filename, ::TYPE_ANY, uid);
        }

Kenny Root's avatar
Kenny Root committed
1063 1064 1065 1066 1067 1068 1069
        userState->zeroizeMasterKeysInMemory();
        userState->setState(STATE_UNINITIALIZED);
        return userState->reset();
    }

    bool isEmpty(uid_t uid) const {
        const UserState* userState = getUserState(uid);
1070
        if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root's avatar
Kenny Root committed
1071 1072 1073 1074
            return true;
        }

        DIR* dir = opendir(userState->getUserDirName());
1075 1076 1077
        if (!dir) {
            return true;
        }
Kenny Root's avatar
Kenny Root committed
1078

1079 1080
        bool result = true;
        struct dirent* file;
1081
        while ((file = readdir(dir)) != NULL) {
Kenny Root's avatar
Kenny Root committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
            // We only care about files.
            if (file->d_type != DT_REG) {
                continue;
            }

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

1092 1093
            result = false;
            break;
1094 1095 1096 1097 1098
        }
        closedir(dir);
        return result;
    }

Kenny Root's avatar
Kenny Root committed
1099 1100 1101 1102
    void lock(uid_t uid) {
        UserState* userState = getUserState(uid);
        userState->zeroizeMasterKeysInMemory();
        userState->setState(STATE_LOCKED);
1103 1104
    }

Kenny Root's avatar
Kenny Root committed
1105 1106
    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
        UserState* userState = getUserState(uid);
1107 1108
        ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                userState->getState());
1109 1110 1111 1112 1113
        if (rc != NO_ERROR) {
            return rc;
        }

        const uint8_t version = keyBlob->getVersion();
Kenny Root's avatar
Kenny Root committed
1114
        if (version < CURRENT_BLOB_VERSION) {
Kenny Root's avatar
Kenny Root committed
1115 1116 1117 1118
            /* If we upgrade the key, we need to write it to disk again. Then
             * it must be read it again since the blob is encrypted each time
             * it's written.
             */
Kenny Root's avatar
Kenny Root committed
1119 1120
            if (upgradeBlob(filename, keyBlob, version, type, uid)) {
                if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
1121 1122
                        || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                                userState->getState())) != NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1123 1124 1125
                    return rc;
                }
            }
1126 1127
        }

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
        /*
         * This will upgrade software-backed keys to hardware-backed keys when
         * the HAL for the device supports the newer key types.
         */
        if (rc == NO_ERROR && type == TYPE_KEY_PAIR
                && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
                && keyBlob->isFallback()) {
            ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
                    uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);

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

1145
        if (type != TYPE_ANY && keyBlob->getType() != type) {
1146 1147 1148 1149 1150
            ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
            return KEY_NOT_FOUND;
        }

        return rc;
1151 1152
    }

Kenny Root's avatar
Kenny Root committed
1153 1154
    ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
        UserState* userState = getUserState(uid);
1155 1156
        return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
                mEntropy);
1157 1158
    }

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
        Blob keyBlob;
        ResponseCode rc = get(filename, &keyBlob, type, uid);
        if (rc != ::NO_ERROR) {
            return rc;
        }

        if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
            // A device doesn't have to implement delete_keypair.
            if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
                if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
                    rc = ::SYSTEM_ERROR;
                }
            }
        }
1174 1175 1176 1177 1178 1179 1180 1181 1182
        if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
            keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
            if (dev->delete_key) {
                keymaster_key_blob_t blob;
                blob.key_material = keyBlob.getValue();
                blob.key_material_size = keyBlob.getLength();
                dev->delete_key(dev, &blob);
            }
        }
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
        if (rc != ::NO_ERROR) {
            return rc;
        }

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

    ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
            uid_t uid) {

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

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

        struct dirent* file;
        while ((file = readdir(dir)) != NULL) {
            // We only care about files.
            if (file->d_type != DT_REG) {
                continue;
            }

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

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

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

Kenny Root's avatar
Kenny Root committed
1233
    void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root's avatar
Kenny Root committed
1234 1235 1236
        const grant_t* existing = getGrant(filename, granteeUid);
        if (existing == NULL) {
            grant_t* grant = new grant_t;
Kenny Root's avatar
Kenny Root committed
1237
            grant->uid = granteeUid;
1238
            grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root's avatar
Kenny Root committed
1239
            mGrants.add(grant);
1240 1241 1242
        }
    }

Kenny Root's avatar
Kenny Root committed
1243
    bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root's avatar
Kenny Root committed
1244 1245 1246 1247 1248 1249 1250 1251
        for (android::Vector<grant_t*>::iterator it(mGrants.begin());
                it != mGrants.end(); it++) {
            grant_t* grant = *it;
            if (grant->uid == granteeUid
                    && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
                mGrants.erase(it);
                return true;
            }
1252 1253 1254 1255
        }
        return false;
    }

1256 1257
    bool hasGrant(const char* filename, const uid_t uid) const {
        return getGrant(filename, uid) != NULL;
1258 1259
    }

1260 1261
    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
            int32_t flags) {
1262 1263 1264 1265 1266 1267 1268 1269 1270
        uint8_t* data;
        size_t dataLength;
        int rc;

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

1271
        bool isFallback = false;
Kenny Root's avatar
Kenny Root committed
1272
        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
1273
        if (rc) {
1274 1275 1276 1277 1278 1279
            /*
             * Maybe the device doesn't support this type of key. Try to use the
             * software fallback keymaster implementation. This is a little bit
             * lazier than checking the PKCS#8 key type, but the software
             * implementation will do that anyway.
             */
1280
            rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
1281
            isFallback = true;
1282 1283 1284 1285 1286

            if (rc) {
                ALOGE("Error while importing keypair: %d", rc);
                return SYSTEM_ERROR;
            }
1287 1288 1289 1290 1291
        }

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

1292
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1293
        keyBlob.setFallback(isFallback);
1294

Kenny Root's avatar
Kenny Root committed
1295
        return put(filename, &keyBlob, uid);
1296 1297
    }

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    bool isHardwareBacked(const android::String16& keyType) const {
        if (mDevice == NULL) {
            ALOGW("can't get keymaster device");
            return false;
        }

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

Kenny Root's avatar
Kenny Root committed
1313 1314
    ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
            const BlobType type) {
1315
        android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
1316

Kenny Root's avatar
Kenny Root committed
1317 1318 1319 1320
        ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
        if (responseCode == NO_ERROR) {
            return responseCode;
        }
1321

Kenny Root's avatar
Kenny Root committed
1322 1323 1324
        // If this is one of the legacy UID->UID mappings, use it.
        uid_t euid = get_keystore_euid(uid);
        if (euid != uid) {
1325
            filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root's avatar
Kenny Root committed
1326 1327 1328 1329 1330
            responseCode = get(filepath8.string(), keyBlob, type, uid);
            if (responseCode == NO_ERROR) {
                return responseCode;
            }
        }
1331

Kenny Root's avatar
Kenny Root committed
1332
        // They might be using a granted key.
1333
        android::String8 filename8 = getKeyName(keyName);
Kenny Root's avatar
Kenny Root committed
1334
        char* end;
1335
        strtoul(filename8.string(), &end, 10);
Kenny Root's avatar
Kenny Root committed
1336 1337 1338
        if (end[0] != '_' || end[1] == 0) {
            return KEY_NOT_FOUND;
        }
1339 1340
        filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
                filename8.string());
Kenny Root's avatar
Kenny Root committed
1341 1342
        if (!hasGrant(filepath8.string(), uid)) {
            return responseCode;
1343 1344
        }

Kenny Root's avatar
Kenny Root committed
1345 1346
        // It is a granted key. Try to load it.
        return get(filepath8.string(), keyBlob, type, uid);
1347 1348
    }

Kenny Root's avatar
Kenny Root committed
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    /**
     * Returns any existing UserState or creates it if it doesn't exist.
     */
    UserState* getUserState(uid_t uid) {
        uid_t userId = get_user_id(uid);

        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
                it != mMasterKeys.end(); it++) {
            UserState* state = *it;
            if (state->getUserId() == userId) {
                return state;
            }
1361
        }
Kenny Root's avatar
Kenny Root committed
1362 1363 1364 1365 1366 1367 1368 1369

        UserState* userState = new UserState(userId);
        if (!userState->initialize()) {
            /* There's not much we can do if initialization fails. Trying to
             * unlock the keystore for that user will fail as well, so any
             * subsequent request for this user will just return SYSTEM_ERROR.
             */
            ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1370
        }
Kenny Root's avatar
Kenny Root committed
1371 1372
        mMasterKeys.add(userState);
        return userState;
1373 1374
    }

Kenny Root's avatar
Kenny Root committed
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    /**
     * Returns NULL if the UserState doesn't already exist.
     */
    const UserState* getUserState(uid_t uid) const {
        uid_t userId = get_user_id(uid);

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

Kenny Root's avatar
Kenny Root committed
1389
        return NULL;
1390 1391
    }

Kenny Root's avatar
Kenny Root committed
1392 1393 1394
private:
    static const char* sOldMasterKey;
    static const char* sMetaDataFile;
1395
    static const android::String16 sRSAKeyType;
Kenny Root's avatar
Kenny Root committed
1396
    Entropy* mEntropy;
Kenny Root's avatar
Kenny Root committed
1397

1398 1399
    keymaster1_device_t* mDevice;
    keymaster1_device_t* mFallbackDevice;
1400

Kenny Root's avatar
Kenny Root committed
1401 1402 1403
    android::Vector<UserState*> mMasterKeys;

    android::Vector<grant_t*> mGrants;
1404

Kenny Root's avatar
Kenny Root committed
1405 1406 1407
    typedef struct {
        uint32_t version;
    } keystore_metadata_t;
1408

Kenny Root's avatar
Kenny Root committed
1409 1410 1411 1412 1413 1414
    keystore_metadata_t mMetaData;

    const grant_t* getGrant(const char* filename, uid_t uid) const {
        for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
                it != mGrants.end(); it++) {
            grant_t* grant = *it;
1415
            if (grant->uid == uid
Kenny Root's avatar
Kenny Root committed
1416
                    && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1417 1418 1419 1420 1421 1422
                return grant;
            }
        }
        return NULL;
    }

1423 1424 1425 1426
    /**
     * Upgrade code. This will upgrade the key from the current version
     * to whatever is newest.
     */
Kenny Root's avatar
Kenny Root committed
1427 1428
    bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
            const BlobType type, uid_t uid) {
1429 1430 1431 1432 1433 1434 1435 1436 1437
        bool updated = false;
        uint8_t version = oldVersion;

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

            blob->setType(type);
            if (type == TYPE_KEY_PAIR) {
Kenny Root's avatar
Kenny Root committed
1438
                importBlobAsKey(blob, filename, uid);
1439 1440 1441 1442 1443
            }
            version = 1;
            updated = true;
        }

1444 1445 1446 1447 1448 1449 1450 1451 1452
        /* From V1 -> V2: All old keys were encrypted */
        if (version == 1) {
            ALOGV("upgrading to version 2");

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

1453 1454 1455
        /*
         * If we've updated, set the key blob to the right version
         * and write it.
Kenny Root's avatar
Kenny Root committed
1456
         */
1457 1458 1459 1460
        if (updated) {
            ALOGV("updated and writing file %s", filename);
            blob->setVersion(version);
        }
Kenny Root's avatar
Kenny Root committed
1461 1462

        return updated;
1463 1464 1465 1466 1467 1468 1469 1470
    }

    /**
     * Takes a blob that is an PEM-encoded RSA key as a byte array and
     * converts it to a DER-encoded PKCS#8 for import into a keymaster.
     * Then it overwrites the original blob with the new blob
     * format that is returned from the keymaster.
     */
Kenny Root's avatar
Kenny Root committed
1471
    ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        // 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;
        }

1492 1493
        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
        uint8_t* tmp = pkcs8key.get();
1494 1495 1496 1497 1498
        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
            ALOGE("Couldn't convert to PKCS#8");
            return SYSTEM_ERROR;
        }

1499 1500
        ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
                blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1501 1502 1503 1504
        if (rc != NO_ERROR) {
            return rc;
        }

Kenny Root's avatar
Kenny Root committed
1505
        return get(filename, blob, TYPE_KEY_PAIR, uid);
1506
    }
1507

Kenny Root's avatar
Kenny Root committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    void readMetaData() {
        int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
        if (in < 0) {
            return;
        }
        size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
        if (fileLength != sizeof(mMetaData)) {
            ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
                    sizeof(mMetaData));
        }
        close(in);
1519 1520
    }

Kenny Root's avatar
Kenny Root committed
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    void writeMetaData() {
        const char* tmpFileName = ".metadata.tmp";
        int out = TEMP_FAILURE_RETRY(open(tmpFileName,
                O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
        if (out < 0) {
            ALOGE("couldn't write metadata file: %s", strerror(errno));
            return;
        }
        size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
        if (fileLength != sizeof(mMetaData)) {
            ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
                    sizeof(mMetaData));
1533
        }
Kenny Root's avatar
Kenny Root committed
1534 1535
        close(out);
        rename(tmpFileName, sMetaDataFile);
1536 1537
    }

Kenny Root's avatar
Kenny Root committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
    bool upgradeKeystore() {
        bool upgraded = false;

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

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

            // Migrate the old .masterkey file to user 0.
            if (access(sOldMasterKey, R_OK) == 0) {
                if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
                    ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
                    return false;
                }
            }

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

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

            struct dirent* file;
            while ((file = readdir(dir)) != NULL) {
                // We only care about files.
                if (file->d_type != DT_REG) {
                    continue;
                }

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

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

                // Rename the file into user directory.
                DIR* otherdir = opendir(otherUser->getUserDirName());
                if (otherdir == NULL) {
                    ALOGW("couldn't open user directory for rename");
                    continue;
                }
                if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
                    ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
                }
                closedir(otherdir);
            }
            closedir(dir);

            mMetaData.version = 1;
            upgraded = true;
        }

        return upgraded;
1607
    }
Kenny Root's avatar
Kenny Root committed
1608
};
1609

Kenny Root's avatar
Kenny Root committed
1610 1611
const char* KeyStore::sOldMasterKey = ".masterkey";
const char* KeyStore::sMetaDataFile = ".metadata";
1612

1613 1614
const android::String16 KeyStore::sRSAKeyType("RSA");

Kenny Root's avatar
Kenny Root committed
1615 1616 1617 1618
namespace android {
class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
public:
    KeyStoreProxy(KeyStore* keyStore)
1619 1620
        : mKeyStore(keyStore),
          mOperationMap(this)
Kenny Root's avatar
Kenny Root committed
1621 1622
    {
    }
1623

1624 1625 1626 1627 1628
    void binderDied(const wp<IBinder>& who) {
        auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
        for (auto token: operations) {
            abort(token);
        }
Kenny Root's avatar
Kenny Root committed
1629
    }
1630

Kenny Root's avatar
Kenny Root committed
1631
    int32_t test() {
1632
        if (!checkBinderPermission(P_TEST)) {
Kenny Root's avatar
Kenny Root committed
1633 1634
            return ::PERMISSION_DENIED;
        }
1635

1636
        return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
1637 1638
    }

Kenny Root's avatar
Kenny Root committed
1639
    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
1640
        if (!checkBinderPermission(P_GET)) {
Kenny Root's avatar
Kenny Root committed
1641 1642
            return ::PERMISSION_DENIED;
        }
1643

1644
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root's avatar
Kenny Root committed
1645 1646
        String8 name8(name);
        Blob keyBlob;
1647

Kenny Root's avatar
Kenny Root committed
1648
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1649
                TYPE_GENERIC);
Kenny Root's avatar
Kenny Root committed
1650
        if (responseCode != ::NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1651
            ALOGW("Could not read %s", name8.string());
Kenny Root's avatar
Kenny Root committed
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
            *item = NULL;
            *itemLength = 0;
            return responseCode;
        }

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

        return ::NO_ERROR;
1662 1663
    }

1664 1665
    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
            int32_t flags) {
1666 1667 1668 1669 1670
        targetUid = getEffectiveUid(targetUid);
        int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
                                                    flags & KEYSTORE_FLAG_ENCRYPTED);
        if (result != ::NO_ERROR) {
            return result;
Kenny Root's avatar
Kenny Root committed
1671 1672
        }

Kenny Root's avatar
Kenny Root committed
1673
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1674
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
1675 1676

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

1679
        return mKeyStore->put(filename.string(), &keyBlob, targetUid);
1680 1681
    }

1682
    int32_t del(const String16& name, int targetUid) {
1683 1684
        targetUid = getEffectiveUid(targetUid);
        if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1685 1686
            return ::PERMISSION_DENIED;
        }
Kenny Root's avatar
Kenny Root committed
1687
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1688
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1689
        return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
1690 1691
    }

1692
    int32_t exist(const String16& name, int targetUid) {
1693 1694
        targetUid = getEffectiveUid(targetUid);
        if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1695 1696 1697
            return ::PERMISSION_DENIED;
        }

Kenny Root's avatar
Kenny Root committed
1698
        String8 name8(name);
Kenny Root's avatar
Kenny Root committed
1699
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root's avatar
Kenny Root committed
1700

Kenny Root's avatar
Kenny Root committed
1701
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
1702 1703 1704
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }
        return ::NO_ERROR;
1705 1706
    }

1707
    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1708 1709
        targetUid = getEffectiveUid(targetUid);
        if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root's avatar
Kenny Root committed
1710 1711
            return ::PERMISSION_DENIED;
        }
Kenny Root's avatar
Kenny Root committed
1712
        const String8 prefix8(prefix);
Kenny Root's avatar
Kenny Root committed
1713
        String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root's avatar
Kenny Root committed
1714

1715 1716
        if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
            return ::SYSTEM_ERROR;
Kenny Root's avatar
Kenny Root committed
1717 1718
        }
        return ::NO_ERROR;
1719 1720
    }

Kenny Root's avatar
Kenny Root committed
1721
    int32_t reset() {
1722
        if (!checkBinderPermission(P_RESET)) {
Kenny Root's avatar
Kenny Root committed
1723 1724
            return ::PERMISSION_DENIED;
        }
1725

1726
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1727
        return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
1728 1729
    }

Kenny Root's avatar
Kenny Root committed
1730 1731 1732 1733 1734 1735 1736 1737
    /*
     * 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) {
1738
        if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root's avatar
Kenny Root committed
1739 1740
            return ::PERMISSION_DENIED;
        }
1741

Kenny Root's avatar
Kenny Root committed
1742
        const String8 password8(password);
1743
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1744

Kenny Root's avatar
Kenny Root committed
1745
        switch (mKeyStore->getState(callingUid)) {
Kenny Root's avatar
Kenny Root committed
1746 1747
            case ::STATE_UNINITIALIZED: {
                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root's avatar
Kenny Root committed
1748
                return mKeyStore->initializeUser(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1749 1750 1751
            }
            case ::STATE_NO_ERROR: {
                // rewrite master key with new password.
Kenny Root's avatar
Kenny Root committed
1752
                return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1753 1754 1755
            }
            case ::STATE_LOCKED: {
                // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root's avatar
Kenny Root committed
1756
                return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root's avatar
Kenny Root committed
1757 1758 1759 1760
            }
        }
        return ::SYSTEM_ERROR;
    }
1761

Kenny Root's avatar
Kenny Root committed
1762
    int32_t lock() {
1763
        if (!checkBinderPermission(P_LOCK)) {
Kenny Root's avatar
Kenny Root committed
1764 1765 1766
            return ::PERMISSION_DENIED;
        }

1767
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root's avatar
Kenny Root committed
1768
        State state = mKeyStore->getState(callingUid);
1769
        if (state != ::STATE_NO_ERROR) {
Kenny Root's avatar
Kenny Root committed
1770 1771 1772
            ALOGD("calling lock in state: %d", state);
            return state;
        }
1773

Kenny Root's avatar
Kenny Root committed
1774
        mKeyStore->lock(callingUid);
Kenny Root's avatar
Kenny Root committed
1775
        return ::NO_ERROR;
1776
    }
1777

Kenny Root's avatar
Kenny Root committed
1778
    int32_t unlock(const String16& pw) {
1779
        if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root's avatar
Kenny Root committed
1780 1781 1782
            return ::PERMISSION_DENIED;
        }

1783
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root's avatar
Kenny Root committed
1784
        State state = mKeyStore->getState(callingUid);
1785
        if (state != ::STATE_LOCKED) {
Kenny Root's avatar
Kenny Root committed
1786 1787 1788 1789 1790 1791
            ALOGD("calling unlock when not locked");
            return state;
        }

        const String8 password8(pw);
        return password(pw);
1792 1793
    }

Kenny Root's avatar
Kenny Root committed
1794
    int32_t zero() {
1795
        if (!checkBinderPermission(P_ZERO)) {
Kenny Root's avatar
Kenny Root committed
1796 1797
            return -1;
        }
1798

1799
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root's avatar
Kenny Root committed
1800
        return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
1801 1802
    }

1803 1804
    int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
            int32_t flags, Vector<sp<KeystoreArg> >* args) {
1805 1806 1807 1808 1809
        targetUid = getEffectiveUid(targetUid);
        int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
                                                       flags & KEYSTORE_FLAG_ENCRYPTED);
        if (result != ::NO_ERROR) {
            return result;
Kenny Root's avatar
Kenny Root committed
1810 1811 1812 1813
        }
        uint8_t* data;
        size_t dataLength;
        int rc;
1814
        bool isFallback = false;
1815

1816 1817
        const keymaster1_device_t* device = mKeyStore->getDevice();
        const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root's avatar
Kenny Root committed
1818 1819 1820
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
1821

Kenny Root's avatar
Kenny Root committed
1822 1823 1824
        if (device->generate_keypair == NULL) {
            return ::SYSTEM_ERROR;
        }
1825

1826
        if (keyType == EVP_PKEY_DSA) {
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
            keymaster_dsa_keygen_params_t dsa_params;
            memset(&dsa_params, '\0', sizeof(dsa_params));

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

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

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

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

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

1862
            if (isKeyTypeSupported(device, TYPE_DSA)) {
1863 1864 1865
                rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
            } else {
                isFallback = true;
1866 1867
                rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
                                                &dataLength);
1868 1869
            }
        } else if (keyType == EVP_PKEY_EC) {
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
            keymaster_ec_keygen_params_t ec_params;
            memset(&ec_params, '\0', sizeof(ec_params));

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

1881
            if (isKeyTypeSupported(device, TYPE_EC)) {
1882 1883 1884
                rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
            } else {
                isFallback = true;
1885
                rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
1886
            }
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
        } else if (keyType == EVP_PKEY_RSA) {
            keymaster_rsa_keygen_params_t rsa_params;
            memset(&rsa_params, '\0', sizeof(rsa_params));
            rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;

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

            if (args->size() > 1) {
1901
                ALOGI("invalid number of arguments: %zu", args->size());
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
                return ::SYSTEM_ERROR;
            } else if (args->size() == 1) {
                sp<KeystoreArg> pubExpBlob = args->itemAt(0);
                if (pubExpBlob != NULL) {
                    Unique_BIGNUM pubExpBn(
                            BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
                                    pubExpBlob->size(), NULL));
                    if (pubExpBn.get() == NULL) {
                        ALOGI("Could not convert public exponent to BN");
                        return ::SYSTEM_ERROR;
                    }
                    unsigned long pubExp = BN_get_word(pubExpBn.get());
                    if (pubExp == 0xFFFFFFFFL) {
                        ALOGI("cannot represent public exponent as a long value");
                        return ::SYSTEM_ERROR;
                    }
                    rsa_params.public_exponent = pubExp;
                }
            }

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

Kenny Root's avatar
Kenny Root committed
1928 1929 1930
        if (rc) {
            return ::SYSTEM_ERROR;
        }
1931

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

Kenny Root's avatar
Kenny Root committed
1935 1936 1937
        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
        free(data);

1938
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1939 1940
        keyBlob.setFallback(isFallback);

1941
        return mKeyStore->put(filename.string(), &keyBlob, targetUid);
1942 1943
    }

1944 1945
    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
            int32_t flags) {
1946 1947 1948 1949 1950
        targetUid = getEffectiveUid(targetUid);
        int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
                                                       flags & KEYSTORE_FLAG_ENCRYPTED);
        if (result != ::NO_ERROR) {
            return result;
Kenny Root's avatar
Kenny Root committed
1951 1952
        }
        String8 name8(name);
1953
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1954

1955
        return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
1956 1957
    }

Kenny Root's avatar
Kenny Root committed
1958 1959
    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
            size_t* outLength) {
1960
        if (!checkBinderPermission(P_SIGN)) {
Kenny Root's avatar
Kenny Root committed
1961 1962
            return ::PERMISSION_DENIED;
        }
1963

1964
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root's avatar
Kenny Root committed
1965 1966
        Blob keyBlob;
        String8 name8(name);
1967

1968
        ALOGV("sign %s from uid %d", name8.string(), callingUid);
1969

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

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

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

Kenny Root's avatar
Kenny Root committed
1987 1988 1989
        keymaster_rsa_sign_params_t params;
        params.digest_type = DIGEST_NONE;
        params.padding_type = PADDING_NONE;
1990
        int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1991
                length, out, outLength);
Kenny Root's avatar
Kenny Root committed
1992 1993 1994 1995
        if (rc) {
            ALOGW("device couldn't sign data");
            return ::SYSTEM_ERROR;
        }
1996

Kenny Root's avatar
Kenny Root committed
1997
        return ::NO_ERROR;
1998 1999
    }

Kenny Root's avatar
Kenny Root committed
2000 2001
    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
            const uint8_t* signature, size_t signatureLength) {
2002
        if (!checkBinderPermission(P_VERIFY)) {
Kenny Root's avatar
Kenny Root committed
2003 2004
            return ::PERMISSION_DENIED;
        }
2005

2006
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root's avatar
Kenny Root committed
2007 2008 2009
        Blob keyBlob;
        String8 name8(name);
        int rc;
2010

Kenny Root's avatar
Kenny Root committed
2011
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2012
                TYPE_KEY_PAIR);
Kenny Root's avatar
Kenny Root committed
2013 2014 2015
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
2016

2017
        const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root's avatar
Kenny Root committed
2018 2019 2020
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
2021

Kenny Root's avatar
Kenny Root committed
2022 2023 2024 2025 2026 2027 2028
        if (device->verify_data == NULL) {
            return ::SYSTEM_ERROR;
        }

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

2030 2031
        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
                dataLength, signature, signatureLength);
Kenny Root's avatar
Kenny Root committed
2032 2033 2034 2035 2036
        if (rc) {
            return ::SYSTEM_ERROR;
        } else {
            return ::NO_ERROR;
        }
2037 2038
    }

Kenny Root's avatar
Kenny Root committed
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
    /*
     * 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) {
2051
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2052
        if (!checkBinderPermission(P_GET)) {
2053
            ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root's avatar
Kenny Root committed
2054 2055
            return ::PERMISSION_DENIED;
        }
2056

Kenny Root's avatar
Kenny Root committed
2057 2058
        Blob keyBlob;
        String8 name8(name);
2059

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

Kenny Root's avatar
Kenny Root committed
2062
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root's avatar
Kenny Root committed
2063 2064 2065 2066
                TYPE_KEY_PAIR);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
2067

2068
        const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root's avatar
Kenny Root committed
2069 2070 2071
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
2072

Kenny Root's avatar
Kenny Root committed
2073 2074 2075 2076
        if (device->get_keypair_public == NULL) {
            ALOGE("device has no get_keypair_public implementation!");
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
2077

2078
        int rc;
2079 2080
        rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
                pubkeyLength);
Kenny Root's avatar
Kenny Root committed
2081 2082 2083
        if (rc) {
            return ::SYSTEM_ERROR;
        }
Kenny Root's avatar
Kenny Root committed
2084

Kenny Root's avatar
Kenny Root committed
2085
        return ::NO_ERROR;
Kenny Root's avatar
Kenny Root committed
2086 2087
    }

2088
    int32_t del_key(const String16& name, int targetUid) {
2089
        return del(name, targetUid);
2090
    }
Kenny Root's avatar
Kenny Root committed
2091 2092

    int32_t grant(const String16& name, int32_t granteeUid) {
2093
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2094 2095 2096
        int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
        if (result != ::NO_ERROR) {
            return result;
Kenny Root's avatar
Kenny Root committed
2097 2098 2099
        }

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

Kenny Root's avatar
Kenny Root committed
2102
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
2103 2104 2105
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

Kenny Root's avatar
Kenny Root committed
2106
        mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root's avatar
Kenny Root committed
2107
        return ::NO_ERROR;
2108
    }
Kenny Root's avatar
Kenny Root committed
2109 2110

    int32_t ungrant(const String16& name, int32_t granteeUid) {
2111
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2112 2113 2114
        int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
        if (result != ::NO_ERROR) {
            return result;
Kenny Root's avatar
Kenny Root committed
2115 2116 2117
        }

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

Kenny Root's avatar
Kenny Root committed
2120
        if (access(filename.string(), R_OK) == -1) {
Kenny Root's avatar
Kenny Root committed
2121 2122 2123
            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
        }

Kenny Root's avatar
Kenny Root committed
2124
        return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
2125
    }
Kenny Root's avatar
Kenny Root committed
2126 2127

    int64_t getmtime(const String16& name) {
2128
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2129
        if (!checkBinderPermission(P_GET)) {
2130
            ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root's avatar
Kenny Root committed
2131
            return -1L;
Kenny Root's avatar
Kenny Root committed
2132 2133 2134
        }

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

Kenny Root's avatar
Kenny Root committed
2137 2138
        if (access(filename.string(), R_OK) == -1) {
            ALOGW("could not access %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
2139
            return -1L;
2140
        }
Kenny Root's avatar
Kenny Root committed
2141

Kenny Root's avatar
Kenny Root committed
2142
        int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root's avatar
Kenny Root committed
2143
        if (fd < 0) {
Kenny Root's avatar
Kenny Root committed
2144
            ALOGW("could not open %s for getmtime", filename.string());
Kenny Root's avatar
Kenny Root committed
2145
            return -1L;
Kenny Root's avatar
Kenny Root committed
2146 2147 2148 2149 2150 2151
        }

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

Kenny Root's avatar
Kenny Root committed
2156
        return static_cast<int64_t>(s.st_mtime);
2157
    }
Kenny Root's avatar
Kenny Root committed
2158

2159 2160
    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
            int32_t destUid) {
Kenny Root's avatar
Kenny Root committed
2161
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2162 2163
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, P_DUPLICATE, spid)) {
2164
            ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root's avatar
Kenny Root committed
2165 2166 2167
            return -1L;
        }

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

2174 2175 2176 2177
        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
2178 2179 2180
            return ::PERMISSION_DENIED;
        }

2181 2182 2183
        if (destUid == -1) {
            destUid = callingUid;
        }
Kenny Root's avatar
Kenny Root committed
2184

2185 2186 2187 2188 2189 2190
        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
2191

2192 2193 2194 2195
            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
2196 2197
        }

2198
        String8 source8(srcKey);
Kenny Root's avatar
Kenny Root committed
2199
        String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
2200 2201

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

Kenny Root's avatar
Kenny Root committed
2204 2205
        if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
            ALOGD("destination already exists: %s", targetFile.string());
Kenny Root's avatar
Kenny Root committed
2206 2207 2208
            return ::SYSTEM_ERROR;
        }

2209
        Blob keyBlob;
Kenny Root's avatar
Kenny Root committed
2210
        ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2211
                srcUid);
2212 2213
        if (responseCode != ::NO_ERROR) {
            return responseCode;
Kenny Root's avatar
Kenny Root committed
2214
        }
2215

2216
        return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root's avatar
Kenny Root committed
2217 2218
    }

2219 2220
    int32_t is_hardware_backed(const String16& keyType) {
        return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
2221 2222
    }

2223
    int32_t clear_uid(int64_t targetUid64) {
2224 2225
        uid_t targetUid = getEffectiveUid(targetUid64);
        if (!checkBinderPermission(P_CLEAR_UID, targetUid)) {
2226 2227 2228
            return ::PERMISSION_DENIED;
        }

2229 2230 2231
        String8 prefix = String8::format("%u_", targetUid);
        Vector<String16> aliases;
        if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
2232 2233 2234
            return ::SYSTEM_ERROR;
        }

2235 2236 2237 2238
        for (uint32_t i = 0; i < aliases.size(); i++) {
            String8 name8(aliases[i]);
            String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
            mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
2239
        }
2240
        return ::NO_ERROR;
2241 2242
    }

2243
    int32_t reset_uid(int32_t targetUid) {
2244 2245
        targetUid = getEffectiveUid(targetUid);
        if (!checkBinderPermission(P_RESET_UID, targetUid)) {
2246 2247 2248
            return ::PERMISSION_DENIED;
        }

2249
        return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
2250 2251 2252
    }

    int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2253
        if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
2254 2255
            return ::PERMISSION_DENIED;
        }
2256

2257 2258 2259 2260 2261 2262 2263 2264 2265
        if (sourceUid == targetUid) {
            return ::SYSTEM_ERROR;
        }

        // Initialise user keystore with existing master key held in-memory
        return mKeyStore->copyMasterKey(sourceUid, targetUid);
    }

    int32_t password_uid(const String16& pw, int32_t targetUid) {
2266 2267
        targetUid = getEffectiveUid(targetUid);
        if (!checkBinderPermission(P_PASSWORD, targetUid)) {
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
            return ::PERMISSION_DENIED;
        }
        const String8 password8(pw);

        switch (mKeyStore->getState(targetUid)) {
            case ::STATE_UNINITIALIZED: {
                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
                return mKeyStore->initializeUser(password8, targetUid);
            }
            case ::STATE_NO_ERROR: {
                // rewrite master key with new password.
                return mKeyStore->writeMasterKey(password8, targetUid);
            }
            case ::STATE_LOCKED: {
                // read master key, decrypt with password, initialize mMasterKey*.
                return mKeyStore->readMasterKey(password8, targetUid);
            }
        }
        return ::SYSTEM_ERROR;
    }

2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
    int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
        const keymaster1_device_t* device = mKeyStore->getDevice();
        const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
        int32_t devResult = KM_ERROR_UNIMPLEMENTED;
        int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
        if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
                device->add_rng_entropy != NULL) {
            devResult = device->add_rng_entropy(device, data, dataLength);
        }
        if (fallback->add_rng_entropy) {
            fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
        }
        if (devResult) {
            return devResult;
        }
        if (fallbackResult) {
            return fallbackResult;
        }
        return ::NO_ERROR;
2308 2309
    }

2310
    int32_t generateKey(const String16& name, const KeymasterArguments& params,
2311 2312
                        const uint8_t* entropy, size_t entropyLength, int uid, int flags,
                        KeyCharacteristics* outCharacteristics) {
2313 2314 2315 2316 2317
        uid = getEffectiveUid(uid);
        int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
                                                       flags & KEYSTORE_FLAG_ENCRYPTED);
        if (rc != ::NO_ERROR) {
            return rc;
2318 2319
        }

2320
        rc = KM_ERROR_UNIMPLEMENTED;
2321 2322 2323 2324 2325 2326 2327 2328 2329
        bool isFallback = false;
        keymaster_key_blob_t blob;
        keymaster_key_characteristics_t *out = NULL;

        const keymaster1_device_t* device = mKeyStore->getDevice();
        const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
2330
        // TODO: Seed from Linux RNG before this.
2331 2332
        if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
                device->generate_key != NULL) {
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
            if (!entropy) {
                rc = KM_ERROR_OK;
            } else if (device->add_rng_entropy) {
                rc = device->add_rng_entropy(device, entropy, entropyLength);
            } else {
                rc = KM_ERROR_UNIMPLEMENTED;
            }
            if (rc == KM_ERROR_OK) {
                rc = device->generate_key(device, params.params.data(), params.params.size(),
                                          &blob, &out);
            }
2344 2345 2346 2347 2348
        }
        // If the HW device didn't support generate_key or generate_key failed
        // fall back to the software implementation.
        if (rc && fallback->generate_key != NULL) {
            isFallback = true;
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
            if (!entropy) {
                rc = KM_ERROR_OK;
            } else if (fallback->add_rng_entropy) {
                rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
            } else {
                rc = KM_ERROR_UNIMPLEMENTED;
            }
            if (rc == KM_ERROR_OK) {
                rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
                                            &blob,
                                            &out);
            }
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
        }

        if (out) {
            if (outCharacteristics) {
                outCharacteristics->characteristics = *out;
            } else {
                keymaster_free_characteristics(out);
            }
            free(out);
        }

        if (rc) {
            return rc;
        }

        String8 name8(name);
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));

        Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
        keyBlob.setFallback(isFallback);
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);

        free(const_cast<uint8_t*>(blob.key_material));

        return mKeyStore->put(filename.string(), &keyBlob, uid);
2386 2387
    }

2388
    int32_t getKeyCharacteristics(const String16& name,
2389 2390
                                  const keymaster_blob_t* clientId,
                                  const keymaster_blob_t* appData,
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
                                  KeyCharacteristics* outCharacteristics) {
        if (!outCharacteristics) {
            return KM_ERROR_UNEXPECTED_NULL_POINTER;
        }

        uid_t callingUid = IPCThreadState::self()->getCallingUid();

        Blob keyBlob;
        String8 name8(name);
        int rc;

        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
                TYPE_KEYMASTER_10);
        if (responseCode != ::NO_ERROR) {
            return responseCode;
        }
        keymaster_key_blob_t key;
        key.key_material_size = keyBlob.getLength();
        key.key_material = keyBlob.getValue();
        keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
        keymaster_key_characteristics_t *out = NULL;
        if (!dev->get_key_characteristics) {
            ALOGW("device does not implement get_key_characteristics");
            return KM_ERROR_UNIMPLEMENTED;
        }
2416
        rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
2417 2418 2419 2420 2421
        if (out) {
            outCharacteristics->characteristics = *out;
            free(out);
        }
        return rc ? rc : ::NO_ERROR;
2422 2423
    }

2424 2425 2426 2427
    int32_t importKey(const String16& name, const KeymasterArguments& params,
                                keymaster_key_format_t format, const uint8_t *keyData,
                                size_t keyLength, int uid, int flags,
                                KeyCharacteristics* outCharacteristics) {
2428 2429 2430 2431 2432
        uid = getEffectiveUid(uid);
        int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
                                                       flags & KEYSTORE_FLAG_ENCRYPTED);
        if (rc != ::NO_ERROR) {
            return rc;
2433 2434
        }

2435
        rc = KM_ERROR_UNIMPLEMENTED;
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
        bool isFallback = false;
        keymaster_key_blob_t blob;
        keymaster_key_characteristics_t *out = NULL;

        const keymaster1_device_t* device = mKeyStore->getDevice();
        const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
        if (device == NULL) {
            return ::SYSTEM_ERROR;
        }
        if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
                device->import_key != NULL) {
            rc = device->import_key(device, params.params.data(), params.params.size(),
                                    format, keyData, keyLength, &blob, &out);
        }
        if (rc && fallback->import_key != NULL) {
            isFallback = true;
            rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
                                      format, keyData, keyLength, &blob, &out);
        }
        if (out) {
            if (outCharacteristics) {
                outCharacteristics->characteristics = *out;
            } else {
                keymaster_free_characteristics(out);
            }
            free(out);
        }
        if (rc) {
            return rc;
        }

        String8 name8(name);
        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));

        Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
        keyBlob.setFallback(isFallback);
        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);

        free((void*) blob.key_material);

        return mKeyStore->put(filename.string(), &keyBlob, uid);
2477 2478
    }

2479
    void exportKey(const String16& name, keymaster_key_format_t format,
2480 2481
                           const keymaster_blob_t* clientId,
                           const keymaster_blob_t* appData, ExportResult* result) {
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503

        uid_t callingUid = IPCThreadState::self()->getCallingUid();

        Blob keyBlob;
        String8 name8(name);
        int rc;

        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
                TYPE_KEYMASTER_10);
        if (responseCode != ::NO_ERROR) {
            result->resultCode = responseCode;
            return;
        }
        keymaster_key_blob_t key;
        key.key_material_size = keyBlob.getLength();
        key.key_material = keyBlob.getValue();
        keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
        if (!dev->export_key) {
            result->resultCode = KM_ERROR_UNIMPLEMENTED;
            return;
        }
        uint8_t* ptr = NULL;
2504
        rc = dev->export_key(dev, format, &key, clientId, appData,
2505 2506 2507
                                             &ptr, &result->dataLength);
        result->exportData.reset(ptr);
        result->resultCode = rc ? rc : ::NO_ERROR;
2508 2509
    }

Chad Brubaker's avatar
Chad Brubaker committed
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
    /**
     * Check that all keymaster_key_param_t's provided by the application are
     * allowed. Any parameter that keystore adds itself should be disallowed here.
     */
    bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
        for (auto param: params) {
            switch (param.tag) {
                case KM_TAG_AUTH_TOKEN:
                    return false;
                default:
                    break;
            }
        }
        return true;
    }

2526
    int authorizeOperation(const keymaster_key_characteristics_t& characteristics,
Chad Brubaker's avatar
Chad Brubaker committed
2527 2528 2529 2530 2531 2532
                            keymaster_operation_handle_t handle,
                            std::vector<keymaster_key_param_t>* params,
                            bool failOnTokenMissing=true) {
        if (!checkAllowedOperationParams(*params)) {
            return KM_ERROR_INVALID_ARGUMENT;
        }
2533 2534 2535 2536 2537 2538 2539
        std::vector<keymaster_key_param_t> allCharacteristics;
        for (size_t i = 0; i < characteristics.sw_enforced.length; i++) {
            allCharacteristics.push_back(characteristics.sw_enforced.params[i]);
        }
        for (size_t i = 0; i < characteristics.hw_enforced.length; i++) {
            allCharacteristics.push_back(characteristics.hw_enforced.params[i]);
        }
Chad Brubaker's avatar
Chad Brubaker committed
2540 2541
        // Check for auth token and add it to the param list if present.
        const hw_auth_token_t* authToken;
2542 2543
        switch (mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
                                                  allCharacteristics.size(), handle, &authToken)) {
Chad Brubaker's avatar
Chad Brubaker committed
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
        case keymaster::AuthTokenTable::OK:
            // Auth token found.
            params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
                                                   reinterpret_cast<const uint8_t*>(authToken),
                                                   sizeof(hw_auth_token_t)));
            break;
        case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
            return KM_ERROR_OK;
        case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
        case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
        case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
            if (failOnTokenMissing) {
                return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
            }
            break;
        case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
            return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
        default:
            return KM_ERROR_INVALID_ARGUMENT;
        }
        // TODO: Enforce the rest of authorization
        return KM_ERROR_OK;
    }

2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
    keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
                                    const keymaster1_device_t* dev,
                                    const std::vector<keymaster_key_param_t>& params,
                                    keymaster_key_characteristics_t* out) {
        UniquePtr<keymaster_blob_t> appId;
        UniquePtr<keymaster_blob_t> appData;
        for (auto param : params) {
            if (param.tag == KM_TAG_APPLICATION_ID) {
                appId.reset(new keymaster_blob_t);
                appId->data = param.blob.data;
                appId->data_length = param.blob.data_length;
            } else if (param.tag == KM_TAG_APPLICATION_DATA) {
                appData.reset(new keymaster_blob_t);
                appData->data = param.blob.data;
                appData->data_length = param.blob.data_length;
            }
        }
        keymaster_key_characteristics_t* result = NULL;
        if (!dev->get_key_characteristics) {
            return KM_ERROR_UNIMPLEMENTED;
        }
        keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
                                                               appData.get(), &result);
        if (result) {
            *out = *result;
            free(result);
        }
        return error;
    }

2598
    void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
2599 2600
               bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
               size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
        if (!result || !outParams) {
            ALOGE("Unexpected null arguments to begin()");
            return;
        }
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
            ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
            result->resultCode = ::PERMISSION_DENIED;
            return;
        }
        Blob keyBlob;
        String8 name8(name);
        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
                TYPE_KEYMASTER_10);
        if (responseCode != ::NO_ERROR) {
            result->resultCode = responseCode;
            return;
        }
        keymaster_key_blob_t key;
        key.key_material_size = keyBlob.getLength();
        key.key_material = keyBlob.getValue();
        keymaster_key_param_t* out;
        size_t outSize;
        keymaster_operation_handle_t handle;
        keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2626
        keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker's avatar
Chad Brubaker committed
2627
        std::vector<keymaster_key_param_t> opParams(params.params);
2628 2629 2630 2631 2632 2633 2634
        Unique_keymaster_key_characteristics characteristics;
        characteristics.reset(new keymaster_key_characteristics_t);
        err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
        if (err) {
            result->resultCode = err;
            return;
        }
Chad Brubaker's avatar
Chad Brubaker committed
2635 2636 2637
        // Don't require an auth token for the call to begin, authentication can
        // require an operation handle. Update and finish will require the token
        // be present and valid.
2638
        int32_t authResult = authorizeOperation(*characteristics, 0, &opParams,
Chad Brubaker's avatar
Chad Brubaker committed
2639 2640 2641 2642 2643
                                                /*failOnTokenMissing*/ false);
        if (authResult) {
            result->resultCode = err;
            return;
        }
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
        // Add entropy to the device first.
        if (entropy) {
            if (dev->add_rng_entropy) {
                err = dev->add_rng_entropy(dev, entropy, entropyLength);
            } else {
                err = KM_ERROR_UNIMPLEMENTED;
            }
            if (err) {
                result->resultCode = err;
                return;
            }
        }
Chad Brubaker's avatar
Chad Brubaker committed
2656 2657 2658 2659
        // Don't do an auth check here, we need begin to succeed for
        // per-operation auth. update/finish will be doing the auth checks.
        err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
                         &handle);
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680

        // If there are too many operations abort the oldest operation that was
        // started as pruneable and try again.
        while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
            sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
            ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
            if (abort(oldest) != ::NO_ERROR) {
                break;
            }
            err = dev->begin(dev, purpose, &key, params.params.data(),
                             params.params.size(), &out, &outSize,
                             &handle);
        }
        if (err) {
            result->resultCode = err;
            return;
        }
        if (out) {
            outParams->params.assign(out, out + outSize);
            free(out);
        }
2681

2682 2683
        sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
                                                                characteristics.release(),
Chad Brubaker's avatar
Chad Brubaker committed
2684
                                                                pruneable);
2685 2686
        result->resultCode = ::NO_ERROR;
        result->token = operationToken;
2687
        result->handle = handle;
2688 2689
    }

2690 2691 2692 2693
    void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
                size_t dataLength, OperationResult* result) {
        const keymaster1_device_t* dev;
        keymaster_operation_handle_t handle;
2694 2695
        const keymaster_key_characteristics_t* characteristics;
        if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2696 2697 2698 2699 2700 2701
            result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
            return;
        }
        uint8_t* output_buf = NULL;
        size_t output_length = 0;
        size_t consumed = 0;
Chad Brubaker's avatar
Chad Brubaker committed
2702
        std::vector<keymaster_key_param_t> opParams(params.params);
2703
        int32_t authResult = authorizeOperation(*characteristics, handle, &opParams);
Chad Brubaker's avatar
Chad Brubaker committed
2704 2705 2706 2707 2708 2709
        if (authResult) {
            result->resultCode = authResult;
            return;
        }
        keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
                                            dataLength, &consumed, &output_buf, &output_length);
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
        result->data.reset(output_buf);
        result->dataLength = output_length;
        result->inputConsumed = consumed;
        result->resultCode = err ? (int32_t) err : ::NO_ERROR;
    }

    void finish(const sp<IBinder>& token, const KeymasterArguments& params,
                const uint8_t* signature, size_t signatureLength, OperationResult* result) {
        const keymaster1_device_t* dev;
        keymaster_operation_handle_t handle;
2720 2721
        const keymaster_key_characteristics_t* characteristics;
        if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2722 2723 2724 2725 2726
            result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
            return;
        }
        uint8_t* output_buf = NULL;
        size_t output_length = 0;
Chad Brubaker's avatar
Chad Brubaker committed
2727
        std::vector<keymaster_key_param_t> opParams(params.params);
2728
        int32_t authResult = authorizeOperation(*characteristics, handle, &opParams);
Chad Brubaker's avatar
Chad Brubaker committed
2729 2730 2731 2732 2733 2734 2735
        if (authResult) {
            result->resultCode = authResult;
            return;
        }
        keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
                                            signature, signatureLength, &output_buf,
                                            &output_length);
2736 2737
        // Remove the operation regardless of the result
        mOperationMap.removeOperation(token);
Chad Brubaker's avatar
Chad Brubaker committed
2738
        mAuthTokenTable.MarkCompleted(handle);
2739 2740 2741 2742 2743 2744 2745 2746
        result->data.reset(output_buf);
        result->dataLength = output_length;
        result->resultCode = err ? (int32_t) err : ::NO_ERROR;
    }

    int32_t abort(const sp<IBinder>& token) {
        const keymaster1_device_t* dev;
        keymaster_operation_handle_t handle;
Chad Brubaker's avatar
Chad Brubaker committed
2747
        if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
2748 2749 2750
            return KM_ERROR_INVALID_OPERATION_HANDLE;
        }
        mOperationMap.removeOperation(token);
Chad Brubaker's avatar
Chad Brubaker committed
2751
        int32_t rc;
2752
        if (!dev->abort) {
Chad Brubaker's avatar
Chad Brubaker committed
2753 2754 2755
            rc = KM_ERROR_UNIMPLEMENTED;
        } else {
            rc = dev->abort(dev, handle);
2756
        }
Chad Brubaker's avatar
Chad Brubaker committed
2757
        mAuthTokenTable.MarkCompleted(handle);
2758 2759 2760 2761
        if (rc) {
            return rc;
        }
        return ::NO_ERROR;
2762 2763
    }

2764 2765 2766
    bool isOperationAuthorized(const sp<IBinder>& token) {
        const keymaster1_device_t* dev;
        keymaster_operation_handle_t handle;
2767 2768
        const keymaster_key_characteristics_t* characteristics;
        if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
2769 2770
            return false;
        }
Chad Brubaker's avatar
Chad Brubaker committed
2771
        std::vector<keymaster_key_param_t> ignored;
2772
        int32_t authResult = authorizeOperation(*characteristics, handle, &ignored);
Chad Brubaker's avatar
Chad Brubaker committed
2773
        return authResult == KM_ERROR_OK;
2774 2775
    }

Chad Brubaker's avatar
Chad Brubaker committed
2776
    int32_t addAuthToken(const uint8_t* token, size_t length) {
2777 2778 2779
        if (!checkBinderPermission(P_ADD_AUTH)) {
            ALOGW("addAuthToken: permission denied for %d",
                  IPCThreadState::self()->getCallingUid());
Chad Brubaker's avatar
Chad Brubaker committed
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
            return ::PERMISSION_DENIED;
        }
        if (length != sizeof(hw_auth_token_t)) {
            return KM_ERROR_INVALID_ARGUMENT;
        }
        hw_auth_token_t* authToken = new hw_auth_token_t;
        memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
        // The table takes ownership of authToken.
        mAuthTokenTable.AddAuthenticationToken(authToken);
        return ::NO_ERROR;
2790 2791
    }

Kenny Root's avatar
Kenny Root committed
2792
private:
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
    static const int32_t UID_SELF = -1;

    /**
     * Get the effective target uid for a binder operation that takes an
     * optional uid as the target.
     */
    inline uid_t getEffectiveUid(int32_t targetUid) {
        if (targetUid == UID_SELF) {
            return IPCThreadState::self()->getCallingUid();
        }
        return static_cast<uid_t>(targetUid);
    }

    /**
     * Check if the caller of the current binder method has the required
     * permission and if acting on other uids the grants to do so.
     */
    inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        pid_t spid = IPCThreadState::self()->getCallingPid();
        if (!has_permission(callingUid, permission, spid)) {
            ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
            return false;
        }
        if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
            ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
            return false;
        }
        return true;
    }

    /**
     * Check if the caller of the current binder method has the required
     * permission or the target of the operation is the caller's uid. This is
     * for operation where the permission is only for cross-uid activity and all
     * uids are allowed to act on their own (ie: clearing all entries for a
     * given uid).
     */
    inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
        uid_t callingUid = IPCThreadState::self()->getCallingUid();
        if (getEffectiveUid(targetUid) == callingUid) {
            return true;
        } else {
            return checkBinderPermission(permission, targetUid);
        }
    }

    /**
     * Helper method to check that the caller has the required permission as
     * well as the keystore is in the unlocked state if checkUnlocked is true.
     *
     * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
     * otherwise the state of keystore when not unlocked and checkUnlocked is
     * true.
     */
    inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
                                                 bool checkUnlocked = true) {
        if (!checkBinderPermission(permission, targetUid)) {
            return ::PERMISSION_DENIED;
        }
        State state = mKeyStore->getState(getEffectiveUid(targetUid));
        if (checkUnlocked && !isKeystoreUnlocked(state)) {
            return state;
        }

        return ::NO_ERROR;

    }

2862 2863 2864 2865 2866 2867 2868 2869 2870
    inline bool isKeystoreUnlocked(State state) {
        switch (state) {
        case ::STATE_NO_ERROR:
            return true;
        case ::STATE_UNINITIALIZED:
        case ::STATE_LOCKED:
            return false;
        }
        return false;
2871
    }
Kenny Root's avatar
Kenny Root committed
2872

2873
    bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
        const int32_t device_api = device->common.module->module_api_version;
        if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
            switch (keyType) {
                case TYPE_RSA:
                case TYPE_DSA:
                case TYPE_EC:
                    return true;
                default:
                    return false;
            }
        } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
            switch (keyType) {
                case TYPE_RSA:
                    return true;
                case TYPE_DSA:
                    return device->flags & KEYMASTER_SUPPORTS_DSA;
                case TYPE_EC:
                    return device->flags & KEYMASTER_SUPPORTS_EC;
                default:
                    return false;
            }
        } else {
            return keyType == TYPE_RSA;
        }
    }

Kenny Root's avatar
Kenny Root committed
2900
    ::KeyStore* mKeyStore;
2901
    OperationMap mOperationMap;
Chad Brubaker's avatar
Chad Brubaker committed
2902
    keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root's avatar
Kenny Root committed
2903 2904 2905
};

}; // namespace android
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920

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

2922
    keymaster0_device_t* dev;
2923 2924 2925 2926 2927
    if (keymaster_device_initialize(&dev)) {
        ALOGE("keystore keymaster could not be initialized; exiting");
        return 1;
    }

2928
    keymaster1_device_t* fallback;
2929 2930 2931 2932 2933
    if (fallback_keymaster_device_initialize(&fallback)) {
        ALOGE("software keymaster could not be initialized; exiting");
        return 1;
    }

2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
    ks_is_selinux_enabled = is_selinux_enabled();
    if (ks_is_selinux_enabled) {
        union selinux_callback cb;
        cb.func_log = selinux_log_callback;
        selinux_set_callback(SELINUX_CB_LOG, cb);
        if (getcon(&tctx) != 0) {
            ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
            return -1;
        }
    } else {
        ALOGI("SELinux: Keystore SELinux is disabled.\n");
    }

2947
    KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root's avatar
Kenny Root committed
2948
    keyStore.initialize();
Kenny Root's avatar
Kenny Root committed
2949 2950 2951 2952 2953 2954
    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;
2955
    }
2956

Kenny Root's avatar
Kenny Root committed
2957 2958 2959 2960 2961
    /*
     * 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();
2962

Kenny Root's avatar
Kenny Root committed
2963
    keymaster_device_release(dev);
2964 2965
    return 1;
}