Home | History | Annotate | Download | only in keystore
      1 /*
      2  * Copyright (C) 2009 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 //#define LOG_NDEBUG 0
     18 #define LOG_TAG "keystore"
     19 
     20 #include <stdio.h>
     21 #include <stdint.h>
     22 #include <string.h>
     23 #include <unistd.h>
     24 #include <signal.h>
     25 #include <errno.h>
     26 #include <dirent.h>
     27 #include <errno.h>
     28 #include <fcntl.h>
     29 #include <limits.h>
     30 #include <assert.h>
     31 #include <sys/types.h>
     32 #include <sys/socket.h>
     33 #include <sys/stat.h>
     34 #include <sys/time.h>
     35 #include <arpa/inet.h>
     36 
     37 #include <openssl/aes.h>
     38 #include <openssl/bio.h>
     39 #include <openssl/evp.h>
     40 #include <openssl/md5.h>
     41 #include <openssl/pem.h>
     42 
     43 #include <hardware/keymaster.h>
     44 
     45 #include <utils/String8.h>
     46 #include <utils/UniquePtr.h>
     47 #include <utils/Vector.h>
     48 
     49 #include <keystore/IKeystoreService.h>
     50 #include <binder/IPCThreadState.h>
     51 #include <binder/IServiceManager.h>
     52 
     53 #include <cutils/log.h>
     54 #include <cutils/sockets.h>
     55 #include <private/android_filesystem_config.h>
     56 
     57 #include <keystore/keystore.h>
     58 
     59 /* KeyStore is a secured storage for key-value pairs. In this implementation,
     60  * each file stores one key-value pair. Keys are encoded in file names, and
     61  * values are encrypted with checksums. The encryption key is protected by a
     62  * user-defined password. To keep things simple, buffers are always larger than
     63  * the maximum space we needed, so boundary checks on buffers are omitted. */
     64 
     65 #define KEY_SIZE        ((NAME_MAX - 15) / 2)
     66 #define VALUE_SIZE      32768
     67 #define PASSWORD_SIZE   VALUE_SIZE
     68 
     69 
     70 struct BIO_Delete {
     71     void operator()(BIO* p) const {
     72         BIO_free(p);
     73     }
     74 };
     75 typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
     76 
     77 struct EVP_PKEY_Delete {
     78     void operator()(EVP_PKEY* p) const {
     79         EVP_PKEY_free(p);
     80     }
     81 };
     82 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
     83 
     84 struct PKCS8_PRIV_KEY_INFO_Delete {
     85     void operator()(PKCS8_PRIV_KEY_INFO* p) const {
     86         PKCS8_PRIV_KEY_INFO_free(p);
     87     }
     88 };
     89 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
     90 
     91 
     92 static int keymaster_device_initialize(keymaster_device_t** dev) {
     93     int rc;
     94 
     95     const hw_module_t* mod;
     96     rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
     97     if (rc) {
     98         ALOGE("could not find any keystore module");
     99         goto out;
    100     }
    101 
    102     rc = keymaster_open(mod, dev);
    103     if (rc) {
    104         ALOGE("could not open keymaster device in %s (%s)",
    105             KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
    106         goto out;
    107     }
    108 
    109     return 0;
    110 
    111 out:
    112     *dev = NULL;
    113     return rc;
    114 }
    115 
    116 static void keymaster_device_release(keymaster_device_t* dev) {
    117     keymaster_close(dev);
    118 }
    119 
    120 /***************
    121  * PERMISSIONS *
    122  ***************/
    123 
    124 /* Here are the permissions, actions, users, and the main function. */
    125 typedef enum {
    126     P_TEST      = 1 << 0,
    127     P_GET       = 1 << 1,
    128     P_INSERT    = 1 << 2,
    129     P_DELETE    = 1 << 3,
    130     P_EXIST     = 1 << 4,
    131     P_SAW       = 1 << 5,
    132     P_RESET     = 1 << 6,
    133     P_PASSWORD  = 1 << 7,
    134     P_LOCK      = 1 << 8,
    135     P_UNLOCK    = 1 << 9,
    136     P_ZERO      = 1 << 10,
    137     P_SIGN      = 1 << 11,
    138     P_VERIFY    = 1 << 12,
    139     P_GRANT     = 1 << 13,
    140     P_DUPLICATE = 1 << 14,
    141     P_CLEAR_UID = 1 << 15,
    142 } perm_t;
    143 
    144 static struct user_euid {
    145     uid_t uid;
    146     uid_t euid;
    147 } user_euids[] = {
    148     {AID_VPN, AID_SYSTEM},
    149     {AID_WIFI, AID_SYSTEM},
    150     {AID_ROOT, AID_SYSTEM},
    151 };
    152 
    153 static struct user_perm {
    154     uid_t uid;
    155     perm_t perms;
    156 } user_perms[] = {
    157     {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
    158     {AID_VPN,    static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
    159     {AID_WIFI,   static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
    160     {AID_ROOT,   static_cast<perm_t>(P_GET) },
    161 };
    162 
    163 static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
    164         | P_VERIFY);
    165 
    166 /**
    167  * Returns the app ID (in the Android multi-user sense) for the current
    168  * UNIX UID.
    169  */
    170 static uid_t get_app_id(uid_t uid) {
    171     return uid % AID_USER;
    172 }
    173 
    174 /**
    175  * Returns the user ID (in the Android multi-user sense) for the current
    176  * UNIX UID.
    177  */
    178 static uid_t get_user_id(uid_t uid) {
    179     return uid / AID_USER;
    180 }
    181 
    182 
    183 static bool has_permission(uid_t uid, perm_t perm) {
    184     // All system users are equivalent for multi-user support.
    185     if (get_app_id(uid) == AID_SYSTEM) {
    186         uid = AID_SYSTEM;
    187     }
    188 
    189     for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
    190         struct user_perm user = user_perms[i];
    191         if (user.uid == uid) {
    192             return user.perms & perm;
    193         }
    194     }
    195 
    196     return DEFAULT_PERMS & perm;
    197 }
    198 
    199 /**
    200  * Returns the UID that the callingUid should act as. This is here for
    201  * legacy support of the WiFi and VPN systems and should be removed
    202  * when WiFi can operate in its own namespace.
    203  */
    204 static uid_t get_keystore_euid(uid_t uid) {
    205     for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
    206         struct user_euid user = user_euids[i];
    207         if (user.uid == uid) {
    208             return user.euid;
    209         }
    210     }
    211 
    212     return uid;
    213 }
    214 
    215 /**
    216  * Returns true if the callingUid is allowed to interact in the targetUid's
    217  * namespace.
    218  */
    219 static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
    220     for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
    221         struct user_euid user = user_euids[i];
    222         if (user.euid == callingUid && user.uid == targetUid) {
    223             return true;
    224         }
    225     }
    226 
    227     return false;
    228 }
    229 
    230 /* Here is the encoding of keys. This is necessary in order to allow arbitrary
    231  * characters in keys. Characters in [0-~] are not encoded. Others are encoded
    232  * into two bytes. The first byte is one of [+-.] which represents the first
    233  * two bits of the character. The second byte encodes the rest of the bits into
    234  * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
    235  * that Base64 cannot be used here due to the need of prefix match on keys. */
    236 
    237 static size_t encode_key_length(const android::String8& keyName) {
    238     const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
    239     size_t length = keyName.length();
    240     for (int i = length; i > 0; --i, ++in) {
    241         if (*in < '0' || *in > '~') {
    242             ++length;
    243         }
    244     }
    245     return length;
    246 }
    247 
    248 static int encode_key(char* out, const android::String8& keyName) {
    249     const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
    250     size_t length = keyName.length();
    251     for (int i = length; i > 0; --i, ++in, ++out) {
    252         if (*in < '0' || *in > '~') {
    253             *out = '+' + (*in >> 6);
    254             *++out = '0' + (*in & 0x3F);
    255             ++length;
    256         } else {
    257             *out = *in;
    258         }
    259     }
    260     *out = '\0';
    261     return length;
    262 }
    263 
    264 static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
    265     int n = snprintf(out, NAME_MAX, "%u_", uid);
    266     out += n;
    267 
    268     return n + encode_key(out, keyName);
    269 }
    270 
    271 /*
    272  * Converts from the "escaped" format on disk to actual name.
    273  * This will be smaller than the input string.
    274  *
    275  * Characters that should combine with the next at the end will be truncated.
    276  */
    277 static size_t decode_key_length(const char* in, size_t length) {
    278     size_t outLength = 0;
    279 
    280     for (const char* end = in + length; in < end; in++) {
    281         /* This combines with the next character. */
    282         if (*in < '0' || *in > '~') {
    283             continue;
    284         }
    285 
    286         outLength++;
    287     }
    288     return outLength;
    289 }
    290 
    291 static void decode_key(char* out, const char* in, size_t length) {
    292     for (const char* end = in + length; in < end; in++) {
    293         if (*in < '0' || *in > '~') {
    294             /* Truncate combining characters at the end. */
    295             if (in + 1 >= end) {
    296                 break;
    297             }
    298 
    299             *out = (*in++ - '+') << 6;
    300             *out++ |= (*in - '0') & 0x3F;
    301         } else {
    302             *out++ = *in;
    303         }
    304     }
    305     *out = '\0';
    306 }
    307 
    308 static size_t readFully(int fd, uint8_t* data, size_t size) {
    309     size_t remaining = size;
    310     while (remaining > 0) {
    311         ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
    312         if (n <= 0) {
    313             return size - remaining;
    314         }
    315         data += n;
    316         remaining -= n;
    317     }
    318     return size;
    319 }
    320 
    321 static size_t writeFully(int fd, uint8_t* data, size_t size) {
    322     size_t remaining = size;
    323     while (remaining > 0) {
    324         ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
    325         if (n < 0) {
    326             ALOGW("write failed: %s", strerror(errno));
    327             return size - remaining;
    328         }
    329         data += n;
    330         remaining -= n;
    331     }
    332     return size;
    333 }
    334 
    335 class Entropy {
    336 public:
    337     Entropy() : mRandom(-1) {}
    338     ~Entropy() {
    339         if (mRandom >= 0) {
    340             close(mRandom);
    341         }
    342     }
    343 
    344     bool open() {
    345         const char* randomDevice = "/dev/urandom";
    346         mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
    347         if (mRandom < 0) {
    348             ALOGE("open: %s: %s", randomDevice, strerror(errno));
    349             return false;
    350         }
    351         return true;
    352     }
    353 
    354     bool generate_random_data(uint8_t* data, size_t size) const {
    355         return (readFully(mRandom, data, size) == size);
    356     }
    357 
    358 private:
    359     int mRandom;
    360 };
    361 
    362 /* Here is the file format. There are two parts in blob.value, the secret and
    363  * the description. The secret is stored in ciphertext, and its original size
    364  * can be found in blob.length. The description is stored after the secret in
    365  * plaintext, and its size is specified in blob.info. The total size of the two
    366  * parts must be no more than VALUE_SIZE bytes. The first field is the version,
    367  * the second is the blob's type, and the third byte is flags. Fields other
    368  * than blob.info, blob.length, and blob.value are modified by encryptBlob()
    369  * and decryptBlob(). Thus they should not be accessed from outside. */
    370 
    371 /* ** Note to future implementors of encryption: **
    372  * Currently this is the construction:
    373  *   metadata || Enc(MD5(data) || data)
    374  *
    375  * This should be the construction used for encrypting if re-implementing:
    376  *
    377  *   Derive independent keys for encryption and MAC:
    378  *     Kenc = AES_encrypt(masterKey, "Encrypt")
    379  *     Kmac = AES_encrypt(masterKey, "MAC")
    380  *
    381  *   Store this:
    382  *     metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
    383  *             HMAC(Kmac, metadata || Enc(data))
    384  */
    385 struct __attribute__((packed)) blob {
    386     uint8_t version;
    387     uint8_t type;
    388     uint8_t flags;
    389     uint8_t info;
    390     uint8_t vector[AES_BLOCK_SIZE];
    391     uint8_t encrypted[0]; // Marks offset to encrypted data.
    392     uint8_t digest[MD5_DIGEST_LENGTH];
    393     uint8_t digested[0]; // Marks offset to digested data.
    394     int32_t length; // in network byte order when encrypted
    395     uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
    396 };
    397 
    398 typedef enum {
    399     TYPE_ANY = 0, // meta type that matches anything
    400     TYPE_GENERIC = 1,
    401     TYPE_MASTER_KEY = 2,
    402     TYPE_KEY_PAIR = 3,
    403 } BlobType;
    404 
    405 static const uint8_t CURRENT_BLOB_VERSION = 2;
    406 
    407 class Blob {
    408 public:
    409     Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
    410             BlobType type) {
    411         mBlob.length = valueLength;
    412         memcpy(mBlob.value, value, valueLength);
    413 
    414         mBlob.info = infoLength;
    415         memcpy(mBlob.value + valueLength, info, infoLength);
    416 
    417         mBlob.version = CURRENT_BLOB_VERSION;
    418         mBlob.type = uint8_t(type);
    419 
    420         mBlob.flags = KEYSTORE_FLAG_NONE;
    421     }
    422 
    423     Blob(blob b) {
    424         mBlob = b;
    425     }
    426 
    427     Blob() {}
    428 
    429     const uint8_t* getValue() const {
    430         return mBlob.value;
    431     }
    432 
    433     int32_t getLength() const {
    434         return mBlob.length;
    435     }
    436 
    437     const uint8_t* getInfo() const {
    438         return mBlob.value + mBlob.length;
    439     }
    440 
    441     uint8_t getInfoLength() const {
    442         return mBlob.info;
    443     }
    444 
    445     uint8_t getVersion() const {
    446         return mBlob.version;
    447     }
    448 
    449     bool isEncrypted() const {
    450         if (mBlob.version < 2) {
    451             return true;
    452         }
    453 
    454         return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
    455     }
    456 
    457     void setEncrypted(bool encrypted) {
    458         if (encrypted) {
    459             mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
    460         } else {
    461             mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
    462         }
    463     }
    464 
    465     void setVersion(uint8_t version) {
    466         mBlob.version = version;
    467     }
    468 
    469     BlobType getType() const {
    470         return BlobType(mBlob.type);
    471     }
    472 
    473     void setType(BlobType type) {
    474         mBlob.type = uint8_t(type);
    475     }
    476 
    477     ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
    478         ALOGV("writing blob %s", filename);
    479         if (isEncrypted()) {
    480             if (state != STATE_NO_ERROR) {
    481                 ALOGD("couldn't insert encrypted blob while not unlocked");
    482                 return LOCKED;
    483             }
    484 
    485             if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
    486                 ALOGW("Could not read random data for: %s", filename);
    487                 return SYSTEM_ERROR;
    488             }
    489         }
    490 
    491         // data includes the value and the value's length
    492         size_t dataLength = mBlob.length + sizeof(mBlob.length);
    493         // pad data to the AES_BLOCK_SIZE
    494         size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
    495                                  / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
    496         // encrypted data includes the digest value
    497         size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
    498         // move info after space for padding
    499         memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
    500         // zero padding area
    501         memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
    502 
    503         mBlob.length = htonl(mBlob.length);
    504 
    505         if (isEncrypted()) {
    506             MD5(mBlob.digested, digestedLength, mBlob.digest);
    507 
    508             uint8_t vector[AES_BLOCK_SIZE];
    509             memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
    510             AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
    511                             aes_key, vector, AES_ENCRYPT);
    512         }
    513 
    514         size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
    515         size_t fileLength = encryptedLength + headerLength + mBlob.info;
    516 
    517         const char* tmpFileName = ".tmp";
    518         int out = TEMP_FAILURE_RETRY(open(tmpFileName,
    519                 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
    520         if (out < 0) {
    521             ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
    522             return SYSTEM_ERROR;
    523         }
    524         size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
    525         if (close(out) != 0) {
    526             return SYSTEM_ERROR;
    527         }
    528         if (writtenBytes != fileLength) {
    529             ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
    530             unlink(tmpFileName);
    531             return SYSTEM_ERROR;
    532         }
    533         if (rename(tmpFileName, filename) == -1) {
    534             ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
    535             return SYSTEM_ERROR;
    536         }
    537         return NO_ERROR;
    538     }
    539 
    540     ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
    541         ALOGV("reading blob %s", filename);
    542         int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
    543         if (in < 0) {
    544             return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
    545         }
    546         // fileLength may be less than sizeof(mBlob) since the in
    547         // memory version has extra padding to tolerate rounding up to
    548         // the AES_BLOCK_SIZE
    549         size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
    550         if (close(in) != 0) {
    551             return SYSTEM_ERROR;
    552         }
    553 
    554         if (isEncrypted() && (state != STATE_NO_ERROR)) {
    555             return LOCKED;
    556         }
    557 
    558         size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
    559         if (fileLength < headerLength) {
    560             return VALUE_CORRUPTED;
    561         }
    562 
    563         ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
    564         if (encryptedLength < 0) {
    565             return VALUE_CORRUPTED;
    566         }
    567 
    568         ssize_t digestedLength;
    569         if (isEncrypted()) {
    570             if (encryptedLength % AES_BLOCK_SIZE != 0) {
    571                 return VALUE_CORRUPTED;
    572             }
    573 
    574             AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
    575                             mBlob.vector, AES_DECRYPT);
    576             digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
    577             uint8_t computedDigest[MD5_DIGEST_LENGTH];
    578             MD5(mBlob.digested, digestedLength, computedDigest);
    579             if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
    580                 return VALUE_CORRUPTED;
    581             }
    582         } else {
    583             digestedLength = encryptedLength;
    584         }
    585 
    586         ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
    587         mBlob.length = ntohl(mBlob.length);
    588         if (mBlob.length < 0 || mBlob.length > maxValueLength) {
    589             return VALUE_CORRUPTED;
    590         }
    591         if (mBlob.info != 0) {
    592             // move info from after padding to after data
    593             memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
    594         }
    595         return ::NO_ERROR;
    596     }
    597 
    598 private:
    599     struct blob mBlob;
    600 };
    601 
    602 class UserState {
    603 public:
    604     UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
    605         asprintf(&mUserDir, "user_%u", mUserId);
    606         asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
    607     }
    608 
    609     ~UserState() {
    610         free(mUserDir);
    611         free(mMasterKeyFile);
    612     }
    613 
    614     bool initialize() {
    615         if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
    616             ALOGE("Could not create directory '%s'", mUserDir);
    617             return false;
    618         }
    619 
    620         if (access(mMasterKeyFile, R_OK) == 0) {
    621             setState(STATE_LOCKED);
    622         } else {
    623             setState(STATE_UNINITIALIZED);
    624         }
    625 
    626         return true;
    627     }
    628 
    629     uid_t getUserId() const {
    630         return mUserId;
    631     }
    632 
    633     const char* getUserDirName() const {
    634         return mUserDir;
    635     }
    636 
    637     const char* getMasterKeyFileName() const {
    638         return mMasterKeyFile;
    639     }
    640 
    641     void setState(State state) {
    642         mState = state;
    643         if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
    644             mRetry = MAX_RETRY;
    645         }
    646     }
    647 
    648     State getState() const {
    649         return mState;
    650     }
    651 
    652     int8_t getRetry() const {
    653         return mRetry;
    654     }
    655 
    656     void zeroizeMasterKeysInMemory() {
    657         memset(mMasterKey, 0, sizeof(mMasterKey));
    658         memset(mSalt, 0, sizeof(mSalt));
    659         memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
    660         memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
    661     }
    662 
    663     ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
    664         if (!generateMasterKey(entropy)) {
    665             return SYSTEM_ERROR;
    666         }
    667         ResponseCode response = writeMasterKey(pw, entropy);
    668         if (response != NO_ERROR) {
    669             return response;
    670         }
    671         setupMasterKeys();
    672         return ::NO_ERROR;
    673     }
    674 
    675     ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
    676         uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
    677         generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
    678         AES_KEY passwordAesKey;
    679         AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
    680         Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
    681         return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
    682     }
    683 
    684     ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
    685         int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
    686         if (in < 0) {
    687             return SYSTEM_ERROR;
    688         }
    689 
    690         // we read the raw blob to just to get the salt to generate
    691         // the AES key, then we create the Blob to use with decryptBlob
    692         blob rawBlob;
    693         size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
    694         if (close(in) != 0) {
    695             return SYSTEM_ERROR;
    696         }
    697         // find salt at EOF if present, otherwise we have an old file
    698         uint8_t* salt;
    699         if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
    700             salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
    701         } else {
    702             salt = NULL;
    703         }
    704         uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
    705         generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
    706         AES_KEY passwordAesKey;
    707         AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
    708         Blob masterKeyBlob(rawBlob);
    709         ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
    710                 STATE_NO_ERROR);
    711         if (response == SYSTEM_ERROR) {
    712             return response;
    713         }
    714         if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
    715             // if salt was missing, generate one and write a new master key file with the salt.
    716             if (salt == NULL) {
    717                 if (!generateSalt(entropy)) {
    718                     return SYSTEM_ERROR;
    719                 }
    720                 response = writeMasterKey(pw, entropy);
    721             }
    722             if (response == NO_ERROR) {
    723                 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
    724                 setupMasterKeys();
    725             }
    726             return response;
    727         }
    728         if (mRetry <= 0) {
    729             reset();
    730             return UNINITIALIZED;
    731         }
    732         --mRetry;
    733         switch (mRetry) {
    734             case 0: return WRONG_PASSWORD_0;
    735             case 1: return WRONG_PASSWORD_1;
    736             case 2: return WRONG_PASSWORD_2;
    737             case 3: return WRONG_PASSWORD_3;
    738             default: return WRONG_PASSWORD_3;
    739         }
    740     }
    741 
    742     AES_KEY* getEncryptionKey() {
    743         return &mMasterKeyEncryption;
    744     }
    745 
    746     AES_KEY* getDecryptionKey() {
    747         return &mMasterKeyDecryption;
    748     }
    749 
    750     bool reset() {
    751         DIR* dir = opendir(getUserDirName());
    752         if (!dir) {
    753             ALOGW("couldn't open user directory: %s", strerror(errno));
    754             return false;
    755         }
    756 
    757         struct dirent* file;
    758         while ((file = readdir(dir)) != NULL) {
    759             // We only care about files.
    760             if (file->d_type != DT_REG) {
    761                 continue;
    762             }
    763 
    764             // Skip anything that starts with a "."
    765             if (file->d_name[0] == '.') {
    766                 continue;
    767             }
    768 
    769             // Find the current file's UID.
    770             char* end;
    771             unsigned long thisUid = strtoul(file->d_name, &end, 10);
    772             if (end[0] != '_' || end[1] == 0) {
    773                 continue;
    774             }
    775 
    776             // Skip if this is not our user.
    777             if (get_user_id(thisUid) != mUserId) {
    778                 continue;
    779             }
    780 
    781             unlinkat(dirfd(dir), file->d_name, 0);
    782         }
    783         closedir(dir);
    784         return true;
    785     }
    786 
    787 private:
    788     static const int MASTER_KEY_SIZE_BYTES = 16;
    789     static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
    790 
    791     static const int MAX_RETRY = 4;
    792     static const size_t SALT_SIZE = 16;
    793 
    794     void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
    795             uint8_t* salt) {
    796         size_t saltSize;
    797         if (salt != NULL) {
    798             saltSize = SALT_SIZE;
    799         } else {
    800             // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
    801             salt = (uint8_t*) "keystore";
    802             // sizeof = 9, not strlen = 8
    803             saltSize = sizeof("keystore");
    804         }
    805 
    806         PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
    807                 saltSize, 8192, keySize, key);
    808     }
    809 
    810     bool generateSalt(Entropy* entropy) {
    811         return entropy->generate_random_data(mSalt, sizeof(mSalt));
    812     }
    813 
    814     bool generateMasterKey(Entropy* entropy) {
    815         if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
    816             return false;
    817         }
    818         if (!generateSalt(entropy)) {
    819             return false;
    820         }
    821         return true;
    822     }
    823 
    824     void setupMasterKeys() {
    825         AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
    826         AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
    827         setState(STATE_NO_ERROR);
    828     }
    829 
    830     uid_t mUserId;
    831 
    832     char* mUserDir;
    833     char* mMasterKeyFile;
    834 
    835     State mState;
    836     int8_t mRetry;
    837 
    838     uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
    839     uint8_t mSalt[SALT_SIZE];
    840 
    841     AES_KEY mMasterKeyEncryption;
    842     AES_KEY mMasterKeyDecryption;
    843 };
    844 
    845 typedef struct {
    846     uint32_t uid;
    847     const uint8_t* filename;
    848 } grant_t;
    849 
    850 class KeyStore {
    851 public:
    852     KeyStore(Entropy* entropy, keymaster_device_t* device)
    853         : mEntropy(entropy)
    854         , mDevice(device)
    855     {
    856         memset(&mMetaData, '\0', sizeof(mMetaData));
    857     }
    858 
    859     ~KeyStore() {
    860         for (android::Vector<grant_t*>::iterator it(mGrants.begin());
    861                 it != mGrants.end(); it++) {
    862             delete *it;
    863             mGrants.erase(it);
    864         }
    865 
    866         for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
    867                 it != mMasterKeys.end(); it++) {
    868             delete *it;
    869             mMasterKeys.erase(it);
    870         }
    871     }
    872 
    873     keymaster_device_t* getDevice() const {
    874         return mDevice;
    875     }
    876 
    877     ResponseCode initialize() {
    878         readMetaData();
    879         if (upgradeKeystore()) {
    880             writeMetaData();
    881         }
    882 
    883         return ::NO_ERROR;
    884     }
    885 
    886     State getState(uid_t uid) {
    887         return getUserState(uid)->getState();
    888     }
    889 
    890     ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
    891         UserState* userState = getUserState(uid);
    892         return userState->initialize(pw, mEntropy);
    893     }
    894 
    895     ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
    896         uid_t user_id = get_user_id(uid);
    897         UserState* userState = getUserState(user_id);
    898         return userState->writeMasterKey(pw, mEntropy);
    899     }
    900 
    901     ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
    902         uid_t user_id = get_user_id(uid);
    903         UserState* userState = getUserState(user_id);
    904         return userState->readMasterKey(pw, mEntropy);
    905     }
    906 
    907     android::String8 getKeyName(const android::String8& keyName) {
    908         char encoded[encode_key_length(keyName)];
    909         encode_key(encoded, keyName);
    910         return android::String8(encoded);
    911     }
    912 
    913     android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
    914         char encoded[encode_key_length(keyName)];
    915         encode_key(encoded, keyName);
    916         return android::String8::format("%u_%s", uid, encoded);
    917     }
    918 
    919     android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
    920         char encoded[encode_key_length(keyName)];
    921         encode_key(encoded, keyName);
    922         return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
    923                 encoded);
    924     }
    925 
    926     bool reset(uid_t uid) {
    927         UserState* userState = getUserState(uid);
    928         userState->zeroizeMasterKeysInMemory();
    929         userState->setState(STATE_UNINITIALIZED);
    930         return userState->reset();
    931     }
    932 
    933     bool isEmpty(uid_t uid) const {
    934         const UserState* userState = getUserState(uid);
    935         if (userState == NULL) {
    936             return true;
    937         }
    938 
    939         DIR* dir = opendir(userState->getUserDirName());
    940         struct dirent* file;
    941         if (!dir) {
    942             return true;
    943         }
    944         bool result = true;
    945 
    946         char filename[NAME_MAX];
    947         int n = snprintf(filename, sizeof(filename), "%u_", uid);
    948 
    949         while ((file = readdir(dir)) != NULL) {
    950             // We only care about files.
    951             if (file->d_type != DT_REG) {
    952                 continue;
    953             }
    954 
    955             // Skip anything that starts with a "."
    956             if (file->d_name[0] == '.') {
    957                 continue;
    958             }
    959 
    960             if (!strncmp(file->d_name, filename, n)) {
    961                 result = false;
    962                 break;
    963             }
    964         }
    965         closedir(dir);
    966         return result;
    967     }
    968 
    969     void lock(uid_t uid) {
    970         UserState* userState = getUserState(uid);
    971         userState->zeroizeMasterKeysInMemory();
    972         userState->setState(STATE_LOCKED);
    973     }
    974 
    975     ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
    976         UserState* userState = getUserState(uid);
    977         ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
    978                 userState->getState());
    979         if (rc != NO_ERROR) {
    980             return rc;
    981         }
    982 
    983         const uint8_t version = keyBlob->getVersion();
    984         if (version < CURRENT_BLOB_VERSION) {
    985             /* If we upgrade the key, we need to write it to disk again. Then
    986              * it must be read it again since the blob is encrypted each time
    987              * it's written.
    988              */
    989             if (upgradeBlob(filename, keyBlob, version, type, uid)) {
    990                 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
    991                         || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
    992                                 userState->getState())) != NO_ERROR) {
    993                     return rc;
    994                 }
    995             }
    996         }
    997 
    998         if (type != TYPE_ANY && keyBlob->getType() != type) {
    999             ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
   1000             return KEY_NOT_FOUND;
   1001         }
   1002 
   1003         return rc;
   1004     }
   1005 
   1006     ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
   1007         UserState* userState = getUserState(uid);
   1008         return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
   1009                 mEntropy);
   1010     }
   1011 
   1012     void addGrant(const char* filename, uid_t granteeUid) {
   1013         const grant_t* existing = getGrant(filename, granteeUid);
   1014         if (existing == NULL) {
   1015             grant_t* grant = new grant_t;
   1016             grant->uid = granteeUid;
   1017             grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
   1018             mGrants.add(grant);
   1019         }
   1020     }
   1021 
   1022     bool removeGrant(const char* filename, uid_t granteeUid) {
   1023         for (android::Vector<grant_t*>::iterator it(mGrants.begin());
   1024                 it != mGrants.end(); it++) {
   1025             grant_t* grant = *it;
   1026             if (grant->uid == granteeUid
   1027                     && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
   1028                 mGrants.erase(it);
   1029                 return true;
   1030             }
   1031         }
   1032         return false;
   1033     }
   1034 
   1035     bool hasGrant(const char* filename, const uid_t uid) const {
   1036         return getGrant(filename, uid) != NULL;
   1037     }
   1038 
   1039     ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
   1040             int32_t flags) {
   1041         uint8_t* data;
   1042         size_t dataLength;
   1043         int rc;
   1044 
   1045         if (mDevice->import_keypair == NULL) {
   1046             ALOGE("Keymaster doesn't support import!");
   1047             return SYSTEM_ERROR;
   1048         }
   1049 
   1050         rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
   1051         if (rc) {
   1052             ALOGE("Error while importing keypair: %d", rc);
   1053             return SYSTEM_ERROR;
   1054         }
   1055 
   1056         Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
   1057         free(data);
   1058 
   1059         keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
   1060 
   1061         return put(filename, &keyBlob, uid);
   1062     }
   1063 
   1064     bool isHardwareBacked() const {
   1065         return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
   1066     }
   1067 
   1068     ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
   1069             const BlobType type) {
   1070         char filename[NAME_MAX];
   1071         encode_key_for_uid(filename, uid, keyName);
   1072 
   1073         UserState* userState = getUserState(uid);
   1074         android::String8 filepath8;
   1075 
   1076         filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
   1077         if (filepath8.string() == NULL) {
   1078             ALOGW("can't create filepath for key %s", filename);
   1079             return SYSTEM_ERROR;
   1080         }
   1081 
   1082         ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
   1083         if (responseCode == NO_ERROR) {
   1084             return responseCode;
   1085         }
   1086 
   1087         // If this is one of the legacy UID->UID mappings, use it.
   1088         uid_t euid = get_keystore_euid(uid);
   1089         if (euid != uid) {
   1090             encode_key_for_uid(filename, euid, keyName);
   1091             filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
   1092             responseCode = get(filepath8.string(), keyBlob, type, uid);
   1093             if (responseCode == NO_ERROR) {
   1094                 return responseCode;
   1095             }
   1096         }
   1097 
   1098         // They might be using a granted key.
   1099         encode_key(filename, keyName);
   1100         char* end;
   1101         strtoul(filename, &end, 10);
   1102         if (end[0] != '_' || end[1] == 0) {
   1103             return KEY_NOT_FOUND;
   1104         }
   1105         filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
   1106         if (!hasGrant(filepath8.string(), uid)) {
   1107             return responseCode;
   1108         }
   1109 
   1110         // It is a granted key. Try to load it.
   1111         return get(filepath8.string(), keyBlob, type, uid);
   1112     }
   1113 
   1114     /**
   1115      * Returns any existing UserState or creates it if it doesn't exist.
   1116      */
   1117     UserState* getUserState(uid_t uid) {
   1118         uid_t userId = get_user_id(uid);
   1119 
   1120         for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
   1121                 it != mMasterKeys.end(); it++) {
   1122             UserState* state = *it;
   1123             if (state->getUserId() == userId) {
   1124                 return state;
   1125             }
   1126         }
   1127 
   1128         UserState* userState = new UserState(userId);
   1129         if (!userState->initialize()) {
   1130             /* There's not much we can do if initialization fails. Trying to
   1131              * unlock the keystore for that user will fail as well, so any
   1132              * subsequent request for this user will just return SYSTEM_ERROR.
   1133              */
   1134             ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
   1135         }
   1136         mMasterKeys.add(userState);
   1137         return userState;
   1138     }
   1139 
   1140     /**
   1141      * Returns NULL if the UserState doesn't already exist.
   1142      */
   1143     const UserState* getUserState(uid_t uid) const {
   1144         uid_t userId = get_user_id(uid);
   1145 
   1146         for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
   1147                 it != mMasterKeys.end(); it++) {
   1148             UserState* state = *it;
   1149             if (state->getUserId() == userId) {
   1150                 return state;
   1151             }
   1152         }
   1153 
   1154         return NULL;
   1155     }
   1156 
   1157 private:
   1158     static const char* sOldMasterKey;
   1159     static const char* sMetaDataFile;
   1160     Entropy* mEntropy;
   1161 
   1162     keymaster_device_t* mDevice;
   1163 
   1164     android::Vector<UserState*> mMasterKeys;
   1165 
   1166     android::Vector<grant_t*> mGrants;
   1167 
   1168     typedef struct {
   1169         uint32_t version;
   1170     } keystore_metadata_t;
   1171 
   1172     keystore_metadata_t mMetaData;
   1173 
   1174     const grant_t* getGrant(const char* filename, uid_t uid) const {
   1175         for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
   1176                 it != mGrants.end(); it++) {
   1177             grant_t* grant = *it;
   1178             if (grant->uid == uid
   1179                     && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
   1180                 return grant;
   1181             }
   1182         }
   1183         return NULL;
   1184     }
   1185 
   1186     /**
   1187      * Upgrade code. This will upgrade the key from the current version
   1188      * to whatever is newest.
   1189      */
   1190     bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
   1191             const BlobType type, uid_t uid) {
   1192         bool updated = false;
   1193         uint8_t version = oldVersion;
   1194 
   1195         /* From V0 -> V1: All old types were unknown */
   1196         if (version == 0) {
   1197             ALOGV("upgrading to version 1 and setting type %d", type);
   1198 
   1199             blob->setType(type);
   1200             if (type == TYPE_KEY_PAIR) {
   1201                 importBlobAsKey(blob, filename, uid);
   1202             }
   1203             version = 1;
   1204             updated = true;
   1205         }
   1206 
   1207         /* From V1 -> V2: All old keys were encrypted */
   1208         if (version == 1) {
   1209             ALOGV("upgrading to version 2");
   1210 
   1211             blob->setEncrypted(true);
   1212             version = 2;
   1213             updated = true;
   1214         }
   1215 
   1216         /*
   1217          * If we've updated, set the key blob to the right version
   1218          * and write it.
   1219          */
   1220         if (updated) {
   1221             ALOGV("updated and writing file %s", filename);
   1222             blob->setVersion(version);
   1223         }
   1224 
   1225         return updated;
   1226     }
   1227 
   1228     /**
   1229      * Takes a blob that is an PEM-encoded RSA key as a byte array and
   1230      * converts it to a DER-encoded PKCS#8 for import into a keymaster.
   1231      * Then it overwrites the original blob with the new blob
   1232      * format that is returned from the keymaster.
   1233      */
   1234     ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
   1235         // We won't even write to the blob directly with this BIO, so const_cast is okay.
   1236         Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
   1237         if (b.get() == NULL) {
   1238             ALOGE("Problem instantiating BIO");
   1239             return SYSTEM_ERROR;
   1240         }
   1241 
   1242         Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
   1243         if (pkey.get() == NULL) {
   1244             ALOGE("Couldn't read old PEM file");
   1245             return SYSTEM_ERROR;
   1246         }
   1247 
   1248         Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
   1249         int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
   1250         if (len < 0) {
   1251             ALOGE("Couldn't measure PKCS#8 length");
   1252             return SYSTEM_ERROR;
   1253         }
   1254 
   1255         UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
   1256         uint8_t* tmp = pkcs8key.get();
   1257         if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
   1258             ALOGE("Couldn't convert to PKCS#8");
   1259             return SYSTEM_ERROR;
   1260         }
   1261 
   1262         ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
   1263                 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
   1264         if (rc != NO_ERROR) {
   1265             return rc;
   1266         }
   1267 
   1268         return get(filename, blob, TYPE_KEY_PAIR, uid);
   1269     }
   1270 
   1271     void readMetaData() {
   1272         int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
   1273         if (in < 0) {
   1274             return;
   1275         }
   1276         size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
   1277         if (fileLength != sizeof(mMetaData)) {
   1278             ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
   1279                     sizeof(mMetaData));
   1280         }
   1281         close(in);
   1282     }
   1283 
   1284     void writeMetaData() {
   1285         const char* tmpFileName = ".metadata.tmp";
   1286         int out = TEMP_FAILURE_RETRY(open(tmpFileName,
   1287                 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
   1288         if (out < 0) {
   1289             ALOGE("couldn't write metadata file: %s", strerror(errno));
   1290             return;
   1291         }
   1292         size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
   1293         if (fileLength != sizeof(mMetaData)) {
   1294             ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
   1295                     sizeof(mMetaData));
   1296         }
   1297         close(out);
   1298         rename(tmpFileName, sMetaDataFile);
   1299     }
   1300 
   1301     bool upgradeKeystore() {
   1302         bool upgraded = false;
   1303 
   1304         if (mMetaData.version == 0) {
   1305             UserState* userState = getUserState(0);
   1306 
   1307             // Initialize first so the directory is made.
   1308             userState->initialize();
   1309 
   1310             // Migrate the old .masterkey file to user 0.
   1311             if (access(sOldMasterKey, R_OK) == 0) {
   1312                 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
   1313                     ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
   1314                     return false;
   1315                 }
   1316             }
   1317 
   1318             // Initialize again in case we had a key.
   1319             userState->initialize();
   1320 
   1321             // Try to migrate existing keys.
   1322             DIR* dir = opendir(".");
   1323             if (!dir) {
   1324                 // Give up now; maybe we can upgrade later.
   1325                 ALOGE("couldn't open keystore's directory; something is wrong");
   1326                 return false;
   1327             }
   1328 
   1329             struct dirent* file;
   1330             while ((file = readdir(dir)) != NULL) {
   1331                 // We only care about files.
   1332                 if (file->d_type != DT_REG) {
   1333                     continue;
   1334                 }
   1335 
   1336                 // Skip anything that starts with a "."
   1337                 if (file->d_name[0] == '.') {
   1338                     continue;
   1339                 }
   1340 
   1341                 // Find the current file's user.
   1342                 char* end;
   1343                 unsigned long thisUid = strtoul(file->d_name, &end, 10);
   1344                 if (end[0] != '_' || end[1] == 0) {
   1345                     continue;
   1346                 }
   1347                 UserState* otherUser = getUserState(thisUid);
   1348                 if (otherUser->getUserId() != 0) {
   1349                     unlinkat(dirfd(dir), file->d_name, 0);
   1350                 }
   1351 
   1352                 // Rename the file into user directory.
   1353                 DIR* otherdir = opendir(otherUser->getUserDirName());
   1354                 if (otherdir == NULL) {
   1355                     ALOGW("couldn't open user directory for rename");
   1356                     continue;
   1357                 }
   1358                 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
   1359                     ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
   1360                 }
   1361                 closedir(otherdir);
   1362             }
   1363             closedir(dir);
   1364 
   1365             mMetaData.version = 1;
   1366             upgraded = true;
   1367         }
   1368 
   1369         return upgraded;
   1370     }
   1371 };
   1372 
   1373 const char* KeyStore::sOldMasterKey = ".masterkey";
   1374 const char* KeyStore::sMetaDataFile = ".metadata";
   1375 
   1376 namespace android {
   1377 class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
   1378 public:
   1379     KeyStoreProxy(KeyStore* keyStore)
   1380         : mKeyStore(keyStore)
   1381     {
   1382     }
   1383 
   1384     void binderDied(const wp<IBinder>&) {
   1385         ALOGE("binder death detected");
   1386     }
   1387 
   1388     int32_t test() {
   1389         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1390         if (!has_permission(callingUid, P_TEST)) {
   1391             ALOGW("permission denied for %d: test", callingUid);
   1392             return ::PERMISSION_DENIED;
   1393         }
   1394 
   1395         return mKeyStore->getState(callingUid);
   1396     }
   1397 
   1398     int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
   1399         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1400         if (!has_permission(callingUid, P_GET)) {
   1401             ALOGW("permission denied for %d: get", callingUid);
   1402             return ::PERMISSION_DENIED;
   1403         }
   1404 
   1405         String8 name8(name);
   1406         Blob keyBlob;
   1407 
   1408         ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
   1409                 TYPE_GENERIC);
   1410         if (responseCode != ::NO_ERROR) {
   1411             ALOGW("Could not read %s", name8.string());
   1412             *item = NULL;
   1413             *itemLength = 0;
   1414             return responseCode;
   1415         }
   1416 
   1417         *item = (uint8_t*) malloc(keyBlob.getLength());
   1418         memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
   1419         *itemLength = keyBlob.getLength();
   1420 
   1421         return ::NO_ERROR;
   1422     }
   1423 
   1424     int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
   1425             int32_t flags) {
   1426         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1427         if (!has_permission(callingUid, P_INSERT)) {
   1428             ALOGW("permission denied for %d: insert", callingUid);
   1429             return ::PERMISSION_DENIED;
   1430         }
   1431 
   1432         State state = mKeyStore->getState(callingUid);
   1433         if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
   1434             ALOGD("calling get in state: %d", state);
   1435             return state;
   1436         }
   1437 
   1438         if (targetUid == -1) {
   1439             targetUid = callingUid;
   1440         } else if (!is_granted_to(callingUid, targetUid)) {
   1441             return ::PERMISSION_DENIED;
   1442         }
   1443 
   1444         String8 name8(name);
   1445         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
   1446 
   1447         Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
   1448         return mKeyStore->put(filename.string(), &keyBlob, callingUid);
   1449     }
   1450 
   1451     int32_t del(const String16& name, int targetUid) {
   1452         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1453         if (!has_permission(callingUid, P_DELETE)) {
   1454             ALOGW("permission denied for %d: del", callingUid);
   1455             return ::PERMISSION_DENIED;
   1456         }
   1457 
   1458         if (targetUid == -1) {
   1459             targetUid = callingUid;
   1460         } else if (!is_granted_to(callingUid, targetUid)) {
   1461             return ::PERMISSION_DENIED;
   1462         }
   1463 
   1464         String8 name8(name);
   1465         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
   1466 
   1467         Blob keyBlob;
   1468         ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
   1469                 callingUid);
   1470         if (responseCode != ::NO_ERROR) {
   1471             return responseCode;
   1472         }
   1473         return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
   1474     }
   1475 
   1476     int32_t exist(const String16& name, int targetUid) {
   1477         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1478         if (!has_permission(callingUid, P_EXIST)) {
   1479             ALOGW("permission denied for %d: exist", callingUid);
   1480             return ::PERMISSION_DENIED;
   1481         }
   1482 
   1483         if (targetUid == -1) {
   1484             targetUid = callingUid;
   1485         } else if (!is_granted_to(callingUid, targetUid)) {
   1486             return ::PERMISSION_DENIED;
   1487         }
   1488 
   1489         String8 name8(name);
   1490         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
   1491 
   1492         if (access(filename.string(), R_OK) == -1) {
   1493             return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
   1494         }
   1495         return ::NO_ERROR;
   1496     }
   1497 
   1498     int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
   1499         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1500         if (!has_permission(callingUid, P_SAW)) {
   1501             ALOGW("permission denied for %d: saw", callingUid);
   1502             return ::PERMISSION_DENIED;
   1503         }
   1504 
   1505         if (targetUid == -1) {
   1506             targetUid = callingUid;
   1507         } else if (!is_granted_to(callingUid, targetUid)) {
   1508             return ::PERMISSION_DENIED;
   1509         }
   1510 
   1511         UserState* userState = mKeyStore->getUserState(targetUid);
   1512         DIR* dir = opendir(userState->getUserDirName());
   1513         if (!dir) {
   1514             ALOGW("can't open directory for user: %s", strerror(errno));
   1515             return ::SYSTEM_ERROR;
   1516         }
   1517 
   1518         const String8 prefix8(prefix);
   1519         String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
   1520         size_t n = filename.length();
   1521 
   1522         struct dirent* file;
   1523         while ((file = readdir(dir)) != NULL) {
   1524             // We only care about files.
   1525             if (file->d_type != DT_REG) {
   1526                 continue;
   1527             }
   1528 
   1529             // Skip anything that starts with a "."
   1530             if (file->d_name[0] == '.') {
   1531                 continue;
   1532             }
   1533 
   1534             if (!strncmp(filename.string(), file->d_name, n)) {
   1535                 const char* p = &file->d_name[n];
   1536                 size_t plen = strlen(p);
   1537 
   1538                 size_t extra = decode_key_length(p, plen);
   1539                 char *match = (char*) malloc(extra + 1);
   1540                 if (match != NULL) {
   1541                     decode_key(match, p, plen);
   1542                     matches->push(String16(match, extra));
   1543                     free(match);
   1544                 } else {
   1545                     ALOGW("could not allocate match of size %zd", extra);
   1546                 }
   1547             }
   1548         }
   1549         closedir(dir);
   1550 
   1551         return ::NO_ERROR;
   1552     }
   1553 
   1554     int32_t reset() {
   1555         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1556         if (!has_permission(callingUid, P_RESET)) {
   1557             ALOGW("permission denied for %d: reset", callingUid);
   1558             return ::PERMISSION_DENIED;
   1559         }
   1560 
   1561         ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
   1562 
   1563         const keymaster_device_t* device = mKeyStore->getDevice();
   1564         if (device == NULL) {
   1565             ALOGE("No keymaster device!");
   1566             return ::SYSTEM_ERROR;
   1567         }
   1568 
   1569         if (device->delete_all == NULL) {
   1570             ALOGV("keymaster device doesn't implement delete_all");
   1571             return rc;
   1572         }
   1573 
   1574         if (device->delete_all(device)) {
   1575             ALOGE("Problem calling keymaster's delete_all");
   1576             return ::SYSTEM_ERROR;
   1577         }
   1578 
   1579         return rc;
   1580     }
   1581 
   1582     /*
   1583      * Here is the history. To improve the security, the parameters to generate the
   1584      * master key has been changed. To make a seamless transition, we update the
   1585      * file using the same password when the user unlock it for the first time. If
   1586      * any thing goes wrong during the transition, the new file will not overwrite
   1587      * the old one. This avoids permanent damages of the existing data.
   1588      */
   1589     int32_t password(const String16& password) {
   1590         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1591         if (!has_permission(callingUid, P_PASSWORD)) {
   1592             ALOGW("permission denied for %d: password", callingUid);
   1593             return ::PERMISSION_DENIED;
   1594         }
   1595 
   1596         const String8 password8(password);
   1597 
   1598         switch (mKeyStore->getState(callingUid)) {
   1599             case ::STATE_UNINITIALIZED: {
   1600                 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
   1601                 return mKeyStore->initializeUser(password8, callingUid);
   1602             }
   1603             case ::STATE_NO_ERROR: {
   1604                 // rewrite master key with new password.
   1605                 return mKeyStore->writeMasterKey(password8, callingUid);
   1606             }
   1607             case ::STATE_LOCKED: {
   1608                 // read master key, decrypt with password, initialize mMasterKey*.
   1609                 return mKeyStore->readMasterKey(password8, callingUid);
   1610             }
   1611         }
   1612         return ::SYSTEM_ERROR;
   1613     }
   1614 
   1615     int32_t lock() {
   1616         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1617         if (!has_permission(callingUid, P_LOCK)) {
   1618             ALOGW("permission denied for %d: lock", callingUid);
   1619             return ::PERMISSION_DENIED;
   1620         }
   1621 
   1622         State state = mKeyStore->getState(callingUid);
   1623         if (state != ::STATE_NO_ERROR) {
   1624             ALOGD("calling lock in state: %d", state);
   1625             return state;
   1626         }
   1627 
   1628         mKeyStore->lock(callingUid);
   1629         return ::NO_ERROR;
   1630     }
   1631 
   1632     int32_t unlock(const String16& pw) {
   1633         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1634         if (!has_permission(callingUid, P_UNLOCK)) {
   1635             ALOGW("permission denied for %d: unlock", callingUid);
   1636             return ::PERMISSION_DENIED;
   1637         }
   1638 
   1639         State state = mKeyStore->getState(callingUid);
   1640         if (state != ::STATE_LOCKED) {
   1641             ALOGD("calling unlock when not locked");
   1642             return state;
   1643         }
   1644 
   1645         const String8 password8(pw);
   1646         return password(pw);
   1647     }
   1648 
   1649     int32_t zero() {
   1650         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1651         if (!has_permission(callingUid, P_ZERO)) {
   1652             ALOGW("permission denied for %d: zero", callingUid);
   1653             return -1;
   1654         }
   1655 
   1656         return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
   1657     }
   1658 
   1659     int32_t generate(const String16& name, int targetUid, int32_t flags) {
   1660         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1661         if (!has_permission(callingUid, P_INSERT)) {
   1662             ALOGW("permission denied for %d: generate", callingUid);
   1663             return ::PERMISSION_DENIED;
   1664         }
   1665 
   1666         if (targetUid == -1) {
   1667             targetUid = callingUid;
   1668         } else if (!is_granted_to(callingUid, targetUid)) {
   1669             return ::PERMISSION_DENIED;
   1670         }
   1671 
   1672         State state = mKeyStore->getState(callingUid);
   1673         if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
   1674             ALOGW("calling generate in state: %d", state);
   1675             return state;
   1676         }
   1677 
   1678         uint8_t* data;
   1679         size_t dataLength;
   1680         int rc;
   1681 
   1682         const keymaster_device_t* device = mKeyStore->getDevice();
   1683         if (device == NULL) {
   1684             return ::SYSTEM_ERROR;
   1685         }
   1686 
   1687         if (device->generate_keypair == NULL) {
   1688             return ::SYSTEM_ERROR;
   1689         }
   1690 
   1691         keymaster_rsa_keygen_params_t rsa_params;
   1692         rsa_params.modulus_size = 2048;
   1693         rsa_params.public_exponent = 0x10001;
   1694 
   1695         rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
   1696         if (rc) {
   1697             return ::SYSTEM_ERROR;
   1698         }
   1699 
   1700         String8 name8(name);
   1701         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
   1702 
   1703         Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
   1704         free(data);
   1705 
   1706         return mKeyStore->put(filename.string(), &keyBlob, callingUid);
   1707     }
   1708 
   1709     int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
   1710             int32_t flags) {
   1711         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1712         if (!has_permission(callingUid, P_INSERT)) {
   1713             ALOGW("permission denied for %d: import", callingUid);
   1714             return ::PERMISSION_DENIED;
   1715         }
   1716 
   1717         if (targetUid == -1) {
   1718             targetUid = callingUid;
   1719         } else if (!is_granted_to(callingUid, targetUid)) {
   1720             return ::PERMISSION_DENIED;
   1721         }
   1722 
   1723         State state = mKeyStore->getState(callingUid);
   1724         if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
   1725             ALOGD("calling import in state: %d", state);
   1726             return state;
   1727         }
   1728 
   1729         String8 name8(name);
   1730         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
   1731 
   1732         return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
   1733     }
   1734 
   1735     int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
   1736             size_t* outLength) {
   1737         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1738         if (!has_permission(callingUid, P_SIGN)) {
   1739             ALOGW("permission denied for %d: saw", callingUid);
   1740             return ::PERMISSION_DENIED;
   1741         }
   1742 
   1743         Blob keyBlob;
   1744         String8 name8(name);
   1745 
   1746         ALOGV("sign %s from uid %d", name8.string(), callingUid);
   1747         int rc;
   1748 
   1749         ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
   1750                 ::TYPE_KEY_PAIR);
   1751         if (responseCode != ::NO_ERROR) {
   1752             return responseCode;
   1753         }
   1754 
   1755         const keymaster_device_t* device = mKeyStore->getDevice();
   1756         if (device == NULL) {
   1757             ALOGE("no keymaster device; cannot sign");
   1758             return ::SYSTEM_ERROR;
   1759         }
   1760 
   1761         if (device->sign_data == NULL) {
   1762             ALOGE("device doesn't implement signing");
   1763             return ::SYSTEM_ERROR;
   1764         }
   1765 
   1766         keymaster_rsa_sign_params_t params;
   1767         params.digest_type = DIGEST_NONE;
   1768         params.padding_type = PADDING_NONE;
   1769 
   1770         rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
   1771                 data, length, out, outLength);
   1772         if (rc) {
   1773             ALOGW("device couldn't sign data");
   1774             return ::SYSTEM_ERROR;
   1775         }
   1776 
   1777         return ::NO_ERROR;
   1778     }
   1779 
   1780     int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
   1781             const uint8_t* signature, size_t signatureLength) {
   1782         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1783         if (!has_permission(callingUid, P_VERIFY)) {
   1784             ALOGW("permission denied for %d: verify", callingUid);
   1785             return ::PERMISSION_DENIED;
   1786         }
   1787 
   1788         State state = mKeyStore->getState(callingUid);
   1789         if (!isKeystoreUnlocked(state)) {
   1790             ALOGD("calling verify in state: %d", state);
   1791             return state;
   1792         }
   1793 
   1794         Blob keyBlob;
   1795         String8 name8(name);
   1796         int rc;
   1797 
   1798         ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
   1799                 TYPE_KEY_PAIR);
   1800         if (responseCode != ::NO_ERROR) {
   1801             return responseCode;
   1802         }
   1803 
   1804         const keymaster_device_t* device = mKeyStore->getDevice();
   1805         if (device == NULL) {
   1806             return ::SYSTEM_ERROR;
   1807         }
   1808 
   1809         if (device->verify_data == NULL) {
   1810             return ::SYSTEM_ERROR;
   1811         }
   1812 
   1813         keymaster_rsa_sign_params_t params;
   1814         params.digest_type = DIGEST_NONE;
   1815         params.padding_type = PADDING_NONE;
   1816 
   1817         rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
   1818                 data, dataLength, signature, signatureLength);
   1819         if (rc) {
   1820             return ::SYSTEM_ERROR;
   1821         } else {
   1822             return ::NO_ERROR;
   1823         }
   1824     }
   1825 
   1826     /*
   1827      * TODO: The abstraction between things stored in hardware and regular blobs
   1828      * of data stored on the filesystem should be moved down to keystore itself.
   1829      * Unfortunately the Java code that calls this has naming conventions that it
   1830      * knows about. Ideally keystore shouldn't be used to store random blobs of
   1831      * data.
   1832      *
   1833      * Until that happens, it's necessary to have a separate "get_pubkey" and
   1834      * "del_key" since the Java code doesn't really communicate what it's
   1835      * intentions are.
   1836      */
   1837     int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
   1838         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1839         if (!has_permission(callingUid, P_GET)) {
   1840             ALOGW("permission denied for %d: get_pubkey", callingUid);
   1841             return ::PERMISSION_DENIED;
   1842         }
   1843 
   1844         Blob keyBlob;
   1845         String8 name8(name);
   1846 
   1847         ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
   1848 
   1849         ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
   1850                 TYPE_KEY_PAIR);
   1851         if (responseCode != ::NO_ERROR) {
   1852             return responseCode;
   1853         }
   1854 
   1855         const keymaster_device_t* device = mKeyStore->getDevice();
   1856         if (device == NULL) {
   1857             return ::SYSTEM_ERROR;
   1858         }
   1859 
   1860         if (device->get_keypair_public == NULL) {
   1861             ALOGE("device has no get_keypair_public implementation!");
   1862             return ::SYSTEM_ERROR;
   1863         }
   1864 
   1865         int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
   1866                 pubkeyLength);
   1867         if (rc) {
   1868             return ::SYSTEM_ERROR;
   1869         }
   1870 
   1871         return ::NO_ERROR;
   1872     }
   1873 
   1874     int32_t del_key(const String16& name, int targetUid) {
   1875         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1876         if (!has_permission(callingUid, P_DELETE)) {
   1877             ALOGW("permission denied for %d: del_key", callingUid);
   1878             return ::PERMISSION_DENIED;
   1879         }
   1880 
   1881         if (targetUid == -1) {
   1882             targetUid = callingUid;
   1883         } else if (!is_granted_to(callingUid, targetUid)) {
   1884             return ::PERMISSION_DENIED;
   1885         }
   1886 
   1887         String8 name8(name);
   1888         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
   1889 
   1890         Blob keyBlob;
   1891         ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
   1892                 callingUid);
   1893         if (responseCode != ::NO_ERROR) {
   1894             return responseCode;
   1895         }
   1896 
   1897         ResponseCode rc = ::NO_ERROR;
   1898 
   1899         const keymaster_device_t* device = mKeyStore->getDevice();
   1900         if (device == NULL) {
   1901             rc = ::SYSTEM_ERROR;
   1902         } else {
   1903             // A device doesn't have to implement delete_keypair.
   1904             if (device->delete_keypair != NULL) {
   1905                 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
   1906                     rc = ::SYSTEM_ERROR;
   1907                 }
   1908             }
   1909         }
   1910 
   1911         if (rc != ::NO_ERROR) {
   1912             return rc;
   1913         }
   1914 
   1915         return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
   1916     }
   1917 
   1918     int32_t grant(const String16& name, int32_t granteeUid) {
   1919         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1920         if (!has_permission(callingUid, P_GRANT)) {
   1921             ALOGW("permission denied for %d: grant", callingUid);
   1922             return ::PERMISSION_DENIED;
   1923         }
   1924 
   1925         State state = mKeyStore->getState(callingUid);
   1926         if (!isKeystoreUnlocked(state)) {
   1927             ALOGD("calling grant in state: %d", state);
   1928             return state;
   1929         }
   1930 
   1931         String8 name8(name);
   1932         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
   1933 
   1934         if (access(filename.string(), R_OK) == -1) {
   1935             return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
   1936         }
   1937 
   1938         mKeyStore->addGrant(filename.string(), granteeUid);
   1939         return ::NO_ERROR;
   1940     }
   1941 
   1942     int32_t ungrant(const String16& name, int32_t granteeUid) {
   1943         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1944         if (!has_permission(callingUid, P_GRANT)) {
   1945             ALOGW("permission denied for %d: ungrant", callingUid);
   1946             return ::PERMISSION_DENIED;
   1947         }
   1948 
   1949         State state = mKeyStore->getState(callingUid);
   1950         if (!isKeystoreUnlocked(state)) {
   1951             ALOGD("calling ungrant in state: %d", state);
   1952             return state;
   1953         }
   1954 
   1955         String8 name8(name);
   1956         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
   1957 
   1958         if (access(filename.string(), R_OK) == -1) {
   1959             return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
   1960         }
   1961 
   1962         return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
   1963     }
   1964 
   1965     int64_t getmtime(const String16& name) {
   1966         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1967         if (!has_permission(callingUid, P_GET)) {
   1968             ALOGW("permission denied for %d: getmtime", callingUid);
   1969             return -1L;
   1970         }
   1971 
   1972         String8 name8(name);
   1973         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
   1974 
   1975         if (access(filename.string(), R_OK) == -1) {
   1976             ALOGW("could not access %s for getmtime", filename.string());
   1977             return -1L;
   1978         }
   1979 
   1980         int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
   1981         if (fd < 0) {
   1982             ALOGW("could not open %s for getmtime", filename.string());
   1983             return -1L;
   1984         }
   1985 
   1986         struct stat s;
   1987         int ret = fstat(fd, &s);
   1988         close(fd);
   1989         if (ret == -1) {
   1990             ALOGW("could not stat %s for getmtime", filename.string());
   1991             return -1L;
   1992         }
   1993 
   1994         return static_cast<int64_t>(s.st_mtime);
   1995     }
   1996 
   1997     int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
   1998             int32_t destUid) {
   1999         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   2000         if (!has_permission(callingUid, P_DUPLICATE)) {
   2001             ALOGW("permission denied for %d: duplicate", callingUid);
   2002             return -1L;
   2003         }
   2004 
   2005         State state = mKeyStore->getState(callingUid);
   2006         if (!isKeystoreUnlocked(state)) {
   2007             ALOGD("calling duplicate in state: %d", state);
   2008             return state;
   2009         }
   2010 
   2011         if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
   2012             srcUid = callingUid;
   2013         } else if (!is_granted_to(callingUid, srcUid)) {
   2014             ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
   2015             return ::PERMISSION_DENIED;
   2016         }
   2017 
   2018         if (destUid == -1) {
   2019             destUid = callingUid;
   2020         }
   2021 
   2022         if (srcUid != destUid) {
   2023             if (static_cast<uid_t>(srcUid) != callingUid) {
   2024                 ALOGD("can only duplicate from caller to other or to same uid: "
   2025                       "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
   2026                 return ::PERMISSION_DENIED;
   2027             }
   2028 
   2029             if (!is_granted_to(callingUid, destUid)) {
   2030                 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
   2031                 return ::PERMISSION_DENIED;
   2032             }
   2033         }
   2034 
   2035         String8 source8(srcKey);
   2036         String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
   2037 
   2038         String8 target8(destKey);
   2039         String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
   2040 
   2041         if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
   2042             ALOGD("destination already exists: %s", targetFile.string());
   2043             return ::SYSTEM_ERROR;
   2044         }
   2045 
   2046         Blob keyBlob;
   2047         ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
   2048                 callingUid);
   2049         if (responseCode != ::NO_ERROR) {
   2050             return responseCode;
   2051         }
   2052 
   2053         return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
   2054     }
   2055 
   2056     int32_t is_hardware_backed() {
   2057         return mKeyStore->isHardwareBacked() ? 1 : 0;
   2058     }
   2059 
   2060     int32_t clear_uid(int64_t targetUid) {
   2061         uid_t callingUid = IPCThreadState::self()->getCallingUid();
   2062         if (!has_permission(callingUid, P_CLEAR_UID)) {
   2063             ALOGW("permission denied for %d: clear_uid", callingUid);
   2064             return ::PERMISSION_DENIED;
   2065         }
   2066 
   2067         State state = mKeyStore->getState(callingUid);
   2068         if (!isKeystoreUnlocked(state)) {
   2069             ALOGD("calling clear_uid in state: %d", state);
   2070             return state;
   2071         }
   2072 
   2073         const keymaster_device_t* device = mKeyStore->getDevice();
   2074         if (device == NULL) {
   2075             ALOGW("can't get keymaster device");
   2076             return ::SYSTEM_ERROR;
   2077         }
   2078 
   2079         UserState* userState = mKeyStore->getUserState(callingUid);
   2080         DIR* dir = opendir(userState->getUserDirName());
   2081         if (!dir) {
   2082             ALOGW("can't open user directory: %s", strerror(errno));
   2083             return ::SYSTEM_ERROR;
   2084         }
   2085 
   2086         char prefix[NAME_MAX];
   2087         int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
   2088 
   2089         ResponseCode rc = ::NO_ERROR;
   2090 
   2091         struct dirent* file;
   2092         while ((file = readdir(dir)) != NULL) {
   2093             // We only care about files.
   2094             if (file->d_type != DT_REG) {
   2095                 continue;
   2096             }
   2097 
   2098             // Skip anything that starts with a "."
   2099             if (file->d_name[0] == '.') {
   2100                 continue;
   2101             }
   2102 
   2103             if (strncmp(prefix, file->d_name, n)) {
   2104                 continue;
   2105             }
   2106 
   2107             String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
   2108             Blob keyBlob;
   2109             if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
   2110                     != ::NO_ERROR) {
   2111                 ALOGW("couldn't open %s", filename.string());
   2112                 continue;
   2113             }
   2114 
   2115             if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
   2116                 // A device doesn't have to implement delete_keypair.
   2117                 if (device->delete_keypair != NULL) {
   2118                     if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
   2119                         rc = ::SYSTEM_ERROR;
   2120                         ALOGW("device couldn't remove %s", filename.string());
   2121                     }
   2122                 }
   2123             }
   2124 
   2125             if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
   2126                 rc = ::SYSTEM_ERROR;
   2127                 ALOGW("couldn't unlink %s", filename.string());
   2128             }
   2129         }
   2130         closedir(dir);
   2131 
   2132         return rc;
   2133     }
   2134 
   2135 private:
   2136     inline bool isKeystoreUnlocked(State state) {
   2137         switch (state) {
   2138         case ::STATE_NO_ERROR:
   2139             return true;
   2140         case ::STATE_UNINITIALIZED:
   2141         case ::STATE_LOCKED:
   2142             return false;
   2143         }
   2144         return false;
   2145     }
   2146 
   2147     ::KeyStore* mKeyStore;
   2148 };
   2149 
   2150 }; // namespace android
   2151 
   2152 int main(int argc, char* argv[]) {
   2153     if (argc < 2) {
   2154         ALOGE("A directory must be specified!");
   2155         return 1;
   2156     }
   2157     if (chdir(argv[1]) == -1) {
   2158         ALOGE("chdir: %s: %s", argv[1], strerror(errno));
   2159         return 1;
   2160     }
   2161 
   2162     Entropy entropy;
   2163     if (!entropy.open()) {
   2164         return 1;
   2165     }
   2166 
   2167     keymaster_device_t* dev;
   2168     if (keymaster_device_initialize(&dev)) {
   2169         ALOGE("keystore keymaster could not be initialized; exiting");
   2170         return 1;
   2171     }
   2172 
   2173     KeyStore keyStore(&entropy, dev);
   2174     keyStore.initialize();
   2175     android::sp<android::IServiceManager> sm = android::defaultServiceManager();
   2176     android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
   2177     android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
   2178     if (ret != android::OK) {
   2179         ALOGE("Couldn't register binder service!");
   2180         return -1;
   2181     }
   2182 
   2183     /*
   2184      * We're the only thread in existence, so we're just going to process
   2185      * Binder transaction as a single-threaded program.
   2186      */
   2187     android::IPCThreadState::self()->joinThreadPool();
   2188 
   2189     keymaster_device_release(dev);
   2190     return 1;
   2191 }
   2192