keystore.cpp revision 655b958eb2180c7c06889f83f606d23421bf038c
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
70struct BIO_Delete {
71    void operator()(BIO* p) const {
72        BIO_free(p);
73    }
74};
75typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
76
77struct EVP_PKEY_Delete {
78    void operator()(EVP_PKEY* p) const {
79        EVP_PKEY_free(p);
80    }
81};
82typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
83
84struct PKCS8_PRIV_KEY_INFO_Delete {
85    void operator()(PKCS8_PRIV_KEY_INFO* p) const {
86        PKCS8_PRIV_KEY_INFO_free(p);
87    }
88};
89typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
90
91
92static 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
111out:
112    *dev = NULL;
113    return rc;
114}
115
116static 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. */
125typedef 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
144static 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
153static 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
163static 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 */
170static 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 */
178static uid_t get_user_id(uid_t uid) {
179    return uid / AID_USER;
180}
181
182
183static 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 */
204static 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 */
219static 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
237static 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
248static 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
264static 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 */
277static 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
291static 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
308static 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
321static 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
335class Entropy {
336public:
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
358private:
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 reserved. 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 */
385struct __attribute__((packed)) blob {
386    uint8_t version;
387    uint8_t type;
388    uint8_t reserved;
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
398typedef 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
405static const uint8_t CURRENT_BLOB_VERSION = 1;
406
407class Blob {
408public:
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
421    Blob(blob b) {
422        mBlob = b;
423    }
424
425    Blob() {}
426
427    const uint8_t* getValue() const {
428        return mBlob.value;
429    }
430
431    int32_t getLength() const {
432        return mBlob.length;
433    }
434
435    const uint8_t* getInfo() const {
436        return mBlob.value + mBlob.length;
437    }
438
439    uint8_t getInfoLength() const {
440        return mBlob.info;
441    }
442
443    uint8_t getVersion() const {
444        return mBlob.version;
445    }
446
447    void setVersion(uint8_t version) {
448        mBlob.version = version;
449    }
450
451    BlobType getType() const {
452        return BlobType(mBlob.type);
453    }
454
455    void setType(BlobType type) {
456        mBlob.type = uint8_t(type);
457    }
458
459    ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
460        if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
461            ALOGW("Could not read random data for: %s", filename);
462            return SYSTEM_ERROR;
463        }
464
465        // data includes the value and the value's length
466        size_t dataLength = mBlob.length + sizeof(mBlob.length);
467        // pad data to the AES_BLOCK_SIZE
468        size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
469                                 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
470        // encrypted data includes the digest value
471        size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
472        // move info after space for padding
473        memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
474        // zero padding area
475        memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
476
477        mBlob.length = htonl(mBlob.length);
478        MD5(mBlob.digested, digestedLength, mBlob.digest);
479
480        uint8_t vector[AES_BLOCK_SIZE];
481        memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
482        AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
483                        aes_key, vector, AES_ENCRYPT);
484
485        mBlob.reserved = 0;
486        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
487        size_t fileLength = encryptedLength + headerLength + mBlob.info;
488
489        const char* tmpFileName = ".tmp";
490        int out = TEMP_FAILURE_RETRY(open(tmpFileName,
491                O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
492        if (out < 0) {
493            ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
494            return SYSTEM_ERROR;
495        }
496        size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
497        if (close(out) != 0) {
498            return SYSTEM_ERROR;
499        }
500        if (writtenBytes != fileLength) {
501            ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
502            unlink(tmpFileName);
503            return SYSTEM_ERROR;
504        }
505        if (rename(tmpFileName, filename) == -1) {
506            ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
507            return SYSTEM_ERROR;
508        }
509        return NO_ERROR;
510    }
511
512    ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
513        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
514        if (in < 0) {
515            return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
516        }
517        // fileLength may be less than sizeof(mBlob) since the in
518        // memory version has extra padding to tolerate rounding up to
519        // the AES_BLOCK_SIZE
520        size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
521        if (close(in) != 0) {
522            return SYSTEM_ERROR;
523        }
524        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
525        if (fileLength < headerLength) {
526            return VALUE_CORRUPTED;
527        }
528
529        ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
530        if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
531            return VALUE_CORRUPTED;
532        }
533        AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
534                        mBlob.vector, AES_DECRYPT);
535        size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
536        uint8_t computedDigest[MD5_DIGEST_LENGTH];
537        MD5(mBlob.digested, digestedLength, computedDigest);
538        if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
539            return VALUE_CORRUPTED;
540        }
541
542        ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
543        mBlob.length = ntohl(mBlob.length);
544        if (mBlob.length < 0 || mBlob.length > maxValueLength) {
545            return VALUE_CORRUPTED;
546        }
547        if (mBlob.info != 0) {
548            // move info from after padding to after data
549            memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
550        }
551        return ::NO_ERROR;
552    }
553
554private:
555    struct blob mBlob;
556};
557
558class UserState {
559public:
560    UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
561        asprintf(&mUserDir, "user_%u", mUserId);
562        asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
563    }
564
565    ~UserState() {
566        free(mUserDir);
567        free(mMasterKeyFile);
568    }
569
570    bool initialize() {
571        if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
572            ALOGE("Could not create directory '%s'", mUserDir);
573            return false;
574        }
575
576        if (access(mMasterKeyFile, R_OK) == 0) {
577            setState(STATE_LOCKED);
578        } else {
579            setState(STATE_UNINITIALIZED);
580        }
581
582        return true;
583    }
584
585    uid_t getUserId() const {
586        return mUserId;
587    }
588
589    const char* getUserDirName() const {
590        return mUserDir;
591    }
592
593    const char* getMasterKeyFileName() const {
594        return mMasterKeyFile;
595    }
596
597    void setState(State state) {
598        mState = state;
599        if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
600            mRetry = MAX_RETRY;
601        }
602    }
603
604    State getState() const {
605        return mState;
606    }
607
608    int8_t getRetry() const {
609        return mRetry;
610    }
611
612    void zeroizeMasterKeysInMemory() {
613        memset(mMasterKey, 0, sizeof(mMasterKey));
614        memset(mSalt, 0, sizeof(mSalt));
615        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
616        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
617    }
618
619    ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
620        if (!generateMasterKey(entropy)) {
621            return SYSTEM_ERROR;
622        }
623        ResponseCode response = writeMasterKey(pw, entropy);
624        if (response != NO_ERROR) {
625            return response;
626        }
627        setupMasterKeys();
628        return ::NO_ERROR;
629    }
630
631    ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
632        uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
633        generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
634        AES_KEY passwordAesKey;
635        AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
636        Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
637        return masterKeyBlob.encryptBlob(mMasterKeyFile, &passwordAesKey, entropy);
638    }
639
640    ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
641        int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
642        if (in < 0) {
643            return SYSTEM_ERROR;
644        }
645
646        // we read the raw blob to just to get the salt to generate
647        // the AES key, then we create the Blob to use with decryptBlob
648        blob rawBlob;
649        size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
650        if (close(in) != 0) {
651            return SYSTEM_ERROR;
652        }
653        // find salt at EOF if present, otherwise we have an old file
654        uint8_t* salt;
655        if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
656            salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
657        } else {
658            salt = NULL;
659        }
660        uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
661        generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
662        AES_KEY passwordAesKey;
663        AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
664        Blob masterKeyBlob(rawBlob);
665        ResponseCode response = masterKeyBlob.decryptBlob(mMasterKeyFile, &passwordAesKey);
666        if (response == SYSTEM_ERROR) {
667            return SYSTEM_ERROR;
668        }
669        if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
670            // if salt was missing, generate one and write a new master key file with the salt.
671            if (salt == NULL) {
672                if (!generateSalt(entropy)) {
673                    return SYSTEM_ERROR;
674                }
675                response = writeMasterKey(pw, entropy);
676            }
677            if (response == NO_ERROR) {
678                memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
679                setupMasterKeys();
680            }
681            return response;
682        }
683        if (mRetry <= 0) {
684            reset();
685            return UNINITIALIZED;
686        }
687        --mRetry;
688        switch (mRetry) {
689            case 0: return WRONG_PASSWORD_0;
690            case 1: return WRONG_PASSWORD_1;
691            case 2: return WRONG_PASSWORD_2;
692            case 3: return WRONG_PASSWORD_3;
693            default: return WRONG_PASSWORD_3;
694        }
695    }
696
697    AES_KEY* getEncryptionKey() {
698        return &mMasterKeyEncryption;
699    }
700
701    AES_KEY* getDecryptionKey() {
702        return &mMasterKeyDecryption;
703    }
704
705    bool reset() {
706        DIR* dir = opendir(getUserDirName());
707        if (!dir) {
708            ALOGW("couldn't open user directory: %s", strerror(errno));
709            return false;
710        }
711
712        struct dirent* file;
713        while ((file = readdir(dir)) != NULL) {
714            // We only care about files.
715            if (file->d_type != DT_REG) {
716                continue;
717            }
718
719            // Skip anything that starts with a "."
720            if (file->d_name[0] == '.') {
721                continue;
722            }
723
724            // Find the current file's UID.
725            char* end;
726            unsigned long thisUid = strtoul(file->d_name, &end, 10);
727            if (end[0] != '_' || end[1] == 0) {
728                continue;
729            }
730
731            // Skip if this is not our user.
732            if (get_user_id(thisUid) != mUserId) {
733                continue;
734            }
735
736            unlinkat(dirfd(dir), file->d_name, 0);
737        }
738        closedir(dir);
739        return true;
740    }
741
742private:
743    static const int MASTER_KEY_SIZE_BYTES = 16;
744    static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
745
746    static const int MAX_RETRY = 4;
747    static const size_t SALT_SIZE = 16;
748
749    void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
750            uint8_t* salt) {
751        size_t saltSize;
752        if (salt != NULL) {
753            saltSize = SALT_SIZE;
754        } else {
755            // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
756            salt = (uint8_t*) "keystore";
757            // sizeof = 9, not strlen = 8
758            saltSize = sizeof("keystore");
759        }
760
761        PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
762                saltSize, 8192, keySize, key);
763    }
764
765    bool generateSalt(Entropy* entropy) {
766        return entropy->generate_random_data(mSalt, sizeof(mSalt));
767    }
768
769    bool generateMasterKey(Entropy* entropy) {
770        if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
771            return false;
772        }
773        if (!generateSalt(entropy)) {
774            return false;
775        }
776        return true;
777    }
778
779    void setupMasterKeys() {
780        AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
781        AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
782        setState(STATE_NO_ERROR);
783    }
784
785    uid_t mUserId;
786
787    char* mUserDir;
788    char* mMasterKeyFile;
789
790    State mState;
791    int8_t mRetry;
792
793    uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
794    uint8_t mSalt[SALT_SIZE];
795
796    AES_KEY mMasterKeyEncryption;
797    AES_KEY mMasterKeyDecryption;
798};
799
800typedef struct {
801    uint32_t uid;
802    const uint8_t* filename;
803} grant_t;
804
805class KeyStore {
806public:
807    KeyStore(Entropy* entropy, keymaster_device_t* device)
808        : mEntropy(entropy)
809        , mDevice(device)
810    {
811        memset(&mMetaData, '\0', sizeof(mMetaData));
812    }
813
814    ~KeyStore() {
815        for (android::Vector<grant_t*>::iterator it(mGrants.begin());
816                it != mGrants.end(); it++) {
817            delete *it;
818            mGrants.erase(it);
819        }
820
821        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
822                it != mMasterKeys.end(); it++) {
823            delete *it;
824            mMasterKeys.erase(it);
825        }
826    }
827
828    keymaster_device_t* getDevice() const {
829        return mDevice;
830    }
831
832    ResponseCode initialize() {
833        readMetaData();
834        if (upgradeKeystore()) {
835            writeMetaData();
836        }
837
838        return ::NO_ERROR;
839    }
840
841    State getState(uid_t uid) {
842        return getUserState(uid)->getState();
843    }
844
845    ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
846        UserState* userState = getUserState(uid);
847        return userState->initialize(pw, mEntropy);
848    }
849
850    ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
851        uid_t user_id = get_user_id(uid);
852        UserState* userState = getUserState(user_id);
853        return userState->writeMasterKey(pw, mEntropy);
854    }
855
856    ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
857        uid_t user_id = get_user_id(uid);
858        UserState* userState = getUserState(user_id);
859        return userState->readMasterKey(pw, mEntropy);
860    }
861
862    android::String8 getKeyName(const android::String8& keyName) {
863        char encoded[encode_key_length(keyName)];
864        encode_key(encoded, keyName);
865        return android::String8(encoded);
866    }
867
868    android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
869        char encoded[encode_key_length(keyName)];
870        encode_key(encoded, keyName);
871        return android::String8::format("%u_%s", uid, encoded);
872    }
873
874    android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
875        char encoded[encode_key_length(keyName)];
876        encode_key(encoded, keyName);
877        return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
878                encoded);
879    }
880
881    bool reset(uid_t uid) {
882        UserState* userState = getUserState(uid);
883        userState->zeroizeMasterKeysInMemory();
884        userState->setState(STATE_UNINITIALIZED);
885        return userState->reset();
886    }
887
888    bool isEmpty(uid_t uid) const {
889        const UserState* userState = getUserState(uid);
890        if (userState == NULL) {
891            return true;
892        }
893
894        DIR* dir = opendir(userState->getUserDirName());
895        struct dirent* file;
896        if (!dir) {
897            return true;
898        }
899        bool result = true;
900
901        char filename[NAME_MAX];
902        int n = snprintf(filename, sizeof(filename), "%u_", uid);
903
904        while ((file = readdir(dir)) != NULL) {
905            // We only care about files.
906            if (file->d_type != DT_REG) {
907                continue;
908            }
909
910            // Skip anything that starts with a "."
911            if (file->d_name[0] == '.') {
912                continue;
913            }
914
915            if (!strncmp(file->d_name, filename, n)) {
916                result = false;
917                break;
918            }
919        }
920        closedir(dir);
921        return result;
922    }
923
924    void lock(uid_t uid) {
925        UserState* userState = getUserState(uid);
926        userState->zeroizeMasterKeysInMemory();
927        userState->setState(STATE_LOCKED);
928    }
929
930    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
931        UserState* userState = getUserState(uid);
932        ResponseCode rc = keyBlob->decryptBlob(filename, userState->getDecryptionKey());
933        if (rc != NO_ERROR) {
934            return rc;
935        }
936
937        const uint8_t version = keyBlob->getVersion();
938        if (version < CURRENT_BLOB_VERSION) {
939            /* If we upgrade the key, we need to write it to disk again. Then
940             * it must be read it again since the blob is encrypted each time
941             * it's written.
942             */
943            if (upgradeBlob(filename, keyBlob, version, type, uid)) {
944                if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
945                        || (rc = keyBlob->decryptBlob(filename, userState->getDecryptionKey()))
946                                != NO_ERROR) {
947                    return rc;
948                }
949            }
950        }
951
952        if (type != TYPE_ANY && keyBlob->getType() != type) {
953            ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
954            return KEY_NOT_FOUND;
955        }
956
957        return rc;
958    }
959
960    ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
961        UserState* userState = getUserState(uid);
962        return keyBlob->encryptBlob(filename, userState->getEncryptionKey(), mEntropy);
963    }
964
965    void addGrant(const char* filename, uid_t granteeUid) {
966        const grant_t* existing = getGrant(filename, granteeUid);
967        if (existing == NULL) {
968            grant_t* grant = new grant_t;
969            grant->uid = granteeUid;
970            grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
971            mGrants.add(grant);
972        }
973    }
974
975    bool removeGrant(const char* filename, uid_t granteeUid) {
976        for (android::Vector<grant_t*>::iterator it(mGrants.begin());
977                it != mGrants.end(); it++) {
978            grant_t* grant = *it;
979            if (grant->uid == granteeUid
980                    && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
981                mGrants.erase(it);
982                return true;
983            }
984        }
985        return false;
986    }
987
988    bool hasGrant(const char* filename, const uid_t uid) const {
989        return getGrant(filename, uid) != NULL;
990    }
991
992    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid) {
993        uint8_t* data;
994        size_t dataLength;
995        int rc;
996
997        if (mDevice->import_keypair == NULL) {
998            ALOGE("Keymaster doesn't support import!");
999            return SYSTEM_ERROR;
1000        }
1001
1002        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
1003        if (rc) {
1004            ALOGE("Error while importing keypair: %d", rc);
1005            return SYSTEM_ERROR;
1006        }
1007
1008        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1009        free(data);
1010
1011        return put(filename, &keyBlob, uid);
1012    }
1013
1014    bool isHardwareBacked() const {
1015        return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1016    }
1017
1018    ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1019            const BlobType type) {
1020        char filename[NAME_MAX];
1021        encode_key_for_uid(filename, uid, keyName);
1022
1023        UserState* userState = getUserState(uid);
1024        android::String8 filepath8;
1025
1026        filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1027        if (filepath8.string() == NULL) {
1028            ALOGW("can't create filepath for key %s", filename);
1029            return SYSTEM_ERROR;
1030        }
1031
1032        ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1033        if (responseCode == NO_ERROR) {
1034            return responseCode;
1035        }
1036
1037        // If this is one of the legacy UID->UID mappings, use it.
1038        uid_t euid = get_keystore_euid(uid);
1039        if (euid != uid) {
1040            encode_key_for_uid(filename, euid, keyName);
1041            filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1042            responseCode = get(filepath8.string(), keyBlob, type, uid);
1043            if (responseCode == NO_ERROR) {
1044                return responseCode;
1045            }
1046        }
1047
1048        // They might be using a granted key.
1049        encode_key(filename, keyName);
1050        char* end;
1051        strtoul(filename, &end, 10);
1052        if (end[0] != '_' || end[1] == 0) {
1053            return KEY_NOT_FOUND;
1054        }
1055        filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1056        if (!hasGrant(filepath8.string(), uid)) {
1057            return responseCode;
1058        }
1059
1060        // It is a granted key. Try to load it.
1061        return get(filepath8.string(), keyBlob, type, uid);
1062    }
1063
1064    /**
1065     * Returns any existing UserState or creates it if it doesn't exist.
1066     */
1067    UserState* getUserState(uid_t uid) {
1068        uid_t userId = get_user_id(uid);
1069
1070        for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1071                it != mMasterKeys.end(); it++) {
1072            UserState* state = *it;
1073            if (state->getUserId() == userId) {
1074                return state;
1075            }
1076        }
1077
1078        UserState* userState = new UserState(userId);
1079        if (!userState->initialize()) {
1080            /* There's not much we can do if initialization fails. Trying to
1081             * unlock the keystore for that user will fail as well, so any
1082             * subsequent request for this user will just return SYSTEM_ERROR.
1083             */
1084            ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1085        }
1086        mMasterKeys.add(userState);
1087        return userState;
1088    }
1089
1090    /**
1091     * Returns NULL if the UserState doesn't already exist.
1092     */
1093    const UserState* getUserState(uid_t uid) const {
1094        uid_t userId = get_user_id(uid);
1095
1096        for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1097                it != mMasterKeys.end(); it++) {
1098            UserState* state = *it;
1099            if (state->getUserId() == userId) {
1100                return state;
1101            }
1102        }
1103
1104        return NULL;
1105    }
1106
1107private:
1108    static const char* sOldMasterKey;
1109    static const char* sMetaDataFile;
1110    Entropy* mEntropy;
1111
1112    keymaster_device_t* mDevice;
1113
1114    android::Vector<UserState*> mMasterKeys;
1115
1116    android::Vector<grant_t*> mGrants;
1117
1118    typedef struct {
1119        uint32_t version;
1120    } keystore_metadata_t;
1121
1122    keystore_metadata_t mMetaData;
1123
1124    const grant_t* getGrant(const char* filename, uid_t uid) const {
1125        for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1126                it != mGrants.end(); it++) {
1127            grant_t* grant = *it;
1128            if (grant->uid == uid
1129                    && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1130                return grant;
1131            }
1132        }
1133        return NULL;
1134    }
1135
1136    /**
1137     * Upgrade code. This will upgrade the key from the current version
1138     * to whatever is newest.
1139     */
1140    bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1141            const BlobType type, uid_t uid) {
1142        bool updated = false;
1143        uint8_t version = oldVersion;
1144
1145        /* From V0 -> V1: All old types were unknown */
1146        if (version == 0) {
1147            ALOGV("upgrading to version 1 and setting type %d", type);
1148
1149            blob->setType(type);
1150            if (type == TYPE_KEY_PAIR) {
1151                importBlobAsKey(blob, filename, uid);
1152            }
1153            version = 1;
1154            updated = true;
1155        }
1156
1157        /*
1158         * If we've updated, set the key blob to the right version
1159         * and write it.
1160         */
1161        if (updated) {
1162            ALOGV("updated and writing file %s", filename);
1163            blob->setVersion(version);
1164        }
1165
1166        return updated;
1167    }
1168
1169    /**
1170     * Takes a blob that is an PEM-encoded RSA key as a byte array and
1171     * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1172     * Then it overwrites the original blob with the new blob
1173     * format that is returned from the keymaster.
1174     */
1175    ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
1176        // We won't even write to the blob directly with this BIO, so const_cast is okay.
1177        Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1178        if (b.get() == NULL) {
1179            ALOGE("Problem instantiating BIO");
1180            return SYSTEM_ERROR;
1181        }
1182
1183        Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1184        if (pkey.get() == NULL) {
1185            ALOGE("Couldn't read old PEM file");
1186            return SYSTEM_ERROR;
1187        }
1188
1189        Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1190        int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1191        if (len < 0) {
1192            ALOGE("Couldn't measure PKCS#8 length");
1193            return SYSTEM_ERROR;
1194        }
1195
1196        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1197        uint8_t* tmp = pkcs8key.get();
1198        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1199            ALOGE("Couldn't convert to PKCS#8");
1200            return SYSTEM_ERROR;
1201        }
1202
1203        ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid);
1204        if (rc != NO_ERROR) {
1205            return rc;
1206        }
1207
1208        return get(filename, blob, TYPE_KEY_PAIR, uid);
1209    }
1210
1211    void readMetaData() {
1212        int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1213        if (in < 0) {
1214            return;
1215        }
1216        size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1217        if (fileLength != sizeof(mMetaData)) {
1218            ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1219                    sizeof(mMetaData));
1220        }
1221        close(in);
1222    }
1223
1224    void writeMetaData() {
1225        const char* tmpFileName = ".metadata.tmp";
1226        int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1227                O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1228        if (out < 0) {
1229            ALOGE("couldn't write metadata file: %s", strerror(errno));
1230            return;
1231        }
1232        size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1233        if (fileLength != sizeof(mMetaData)) {
1234            ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1235                    sizeof(mMetaData));
1236        }
1237        close(out);
1238        rename(tmpFileName, sMetaDataFile);
1239    }
1240
1241    bool upgradeKeystore() {
1242        bool upgraded = false;
1243
1244        if (mMetaData.version == 0) {
1245            UserState* userState = getUserState(0);
1246
1247            // Initialize first so the directory is made.
1248            userState->initialize();
1249
1250            // Migrate the old .masterkey file to user 0.
1251            if (access(sOldMasterKey, R_OK) == 0) {
1252                if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1253                    ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1254                    return false;
1255                }
1256            }
1257
1258            // Initialize again in case we had a key.
1259            userState->initialize();
1260
1261            // Try to migrate existing keys.
1262            DIR* dir = opendir(".");
1263            if (!dir) {
1264                // Give up now; maybe we can upgrade later.
1265                ALOGE("couldn't open keystore's directory; something is wrong");
1266                return false;
1267            }
1268
1269            struct dirent* file;
1270            while ((file = readdir(dir)) != NULL) {
1271                // We only care about files.
1272                if (file->d_type != DT_REG) {
1273                    continue;
1274                }
1275
1276                // Skip anything that starts with a "."
1277                if (file->d_name[0] == '.') {
1278                    continue;
1279                }
1280
1281                // Find the current file's user.
1282                char* end;
1283                unsigned long thisUid = strtoul(file->d_name, &end, 10);
1284                if (end[0] != '_' || end[1] == 0) {
1285                    continue;
1286                }
1287                UserState* otherUser = getUserState(thisUid);
1288                if (otherUser->getUserId() != 0) {
1289                    unlinkat(dirfd(dir), file->d_name, 0);
1290                }
1291
1292                // Rename the file into user directory.
1293                DIR* otherdir = opendir(otherUser->getUserDirName());
1294                if (otherdir == NULL) {
1295                    ALOGW("couldn't open user directory for rename");
1296                    continue;
1297                }
1298                if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1299                    ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1300                }
1301                closedir(otherdir);
1302            }
1303            closedir(dir);
1304
1305            mMetaData.version = 1;
1306            upgraded = true;
1307        }
1308
1309        return upgraded;
1310    }
1311};
1312
1313const char* KeyStore::sOldMasterKey = ".masterkey";
1314const char* KeyStore::sMetaDataFile = ".metadata";
1315
1316namespace android {
1317class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1318public:
1319    KeyStoreProxy(KeyStore* keyStore)
1320        : mKeyStore(keyStore)
1321    {
1322    }
1323
1324    void binderDied(const wp<IBinder>&) {
1325        ALOGE("binder death detected");
1326    }
1327
1328    int32_t test() {
1329        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1330        if (!has_permission(callingUid, P_TEST)) {
1331            ALOGW("permission denied for %d: test", callingUid);
1332            return ::PERMISSION_DENIED;
1333        }
1334
1335        return mKeyStore->getState(callingUid);
1336    }
1337
1338    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
1339        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1340        if (!has_permission(callingUid, P_GET)) {
1341            ALOGW("permission denied for %d: get", callingUid);
1342            return ::PERMISSION_DENIED;
1343        }
1344
1345        State state = mKeyStore->getState(callingUid);
1346        if (!isKeystoreUnlocked(state)) {
1347            ALOGD("calling get in state: %d", state);
1348            return state;
1349        }
1350
1351        String8 name8(name);
1352        Blob keyBlob;
1353
1354        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1355                TYPE_GENERIC);
1356        if (responseCode != ::NO_ERROR) {
1357            ALOGW("Could not read %s", name8.string());
1358            *item = NULL;
1359            *itemLength = 0;
1360            return responseCode;
1361        }
1362
1363        *item = (uint8_t*) malloc(keyBlob.getLength());
1364        memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1365        *itemLength = keyBlob.getLength();
1366
1367        return ::NO_ERROR;
1368    }
1369
1370    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
1371        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1372        if (!has_permission(callingUid, P_INSERT)) {
1373            ALOGW("permission denied for %d: insert", callingUid);
1374            return ::PERMISSION_DENIED;
1375        }
1376
1377        if (targetUid == -1) {
1378            targetUid = callingUid;
1379        } else if (!is_granted_to(callingUid, targetUid)) {
1380            return ::PERMISSION_DENIED;
1381        }
1382
1383        State state = mKeyStore->getState(callingUid);
1384        if (!isKeystoreUnlocked(state)) {
1385            ALOGD("calling insert in state: %d", state);
1386            return state;
1387        }
1388
1389        String8 name8(name);
1390        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1391
1392        Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1393        return mKeyStore->put(filename.string(), &keyBlob, callingUid);
1394    }
1395
1396    int32_t del(const String16& name, int targetUid) {
1397        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1398        if (!has_permission(callingUid, P_DELETE)) {
1399            ALOGW("permission denied for %d: del", callingUid);
1400            return ::PERMISSION_DENIED;
1401        }
1402
1403        if (targetUid == -1) {
1404            targetUid = callingUid;
1405        } else if (!is_granted_to(callingUid, targetUid)) {
1406            return ::PERMISSION_DENIED;
1407        }
1408
1409        String8 name8(name);
1410        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1411
1412        Blob keyBlob;
1413        ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1414                callingUid);
1415        if (responseCode != ::NO_ERROR) {
1416            return responseCode;
1417        }
1418        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1419    }
1420
1421    int32_t exist(const String16& name, int targetUid) {
1422        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1423        if (!has_permission(callingUid, P_EXIST)) {
1424            ALOGW("permission denied for %d: exist", callingUid);
1425            return ::PERMISSION_DENIED;
1426        }
1427
1428        if (targetUid == -1) {
1429            targetUid = callingUid;
1430        } else if (!is_granted_to(callingUid, targetUid)) {
1431            return ::PERMISSION_DENIED;
1432        }
1433
1434        String8 name8(name);
1435        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
1436
1437        if (access(filename.string(), R_OK) == -1) {
1438            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1439        }
1440        return ::NO_ERROR;
1441    }
1442
1443    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1444        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1445        if (!has_permission(callingUid, P_SAW)) {
1446            ALOGW("permission denied for %d: saw", callingUid);
1447            return ::PERMISSION_DENIED;
1448        }
1449
1450        if (targetUid == -1) {
1451            targetUid = callingUid;
1452        } else if (!is_granted_to(callingUid, targetUid)) {
1453            return ::PERMISSION_DENIED;
1454        }
1455
1456        UserState* userState = mKeyStore->getUserState(targetUid);
1457        DIR* dir = opendir(userState->getUserDirName());
1458        if (!dir) {
1459            ALOGW("can't open directory for user: %s", strerror(errno));
1460            return ::SYSTEM_ERROR;
1461        }
1462
1463        const String8 prefix8(prefix);
1464        String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1465        size_t n = filename.length();
1466
1467        struct dirent* file;
1468        while ((file = readdir(dir)) != NULL) {
1469            // We only care about files.
1470            if (file->d_type != DT_REG) {
1471                continue;
1472            }
1473
1474            // Skip anything that starts with a "."
1475            if (file->d_name[0] == '.') {
1476                continue;
1477            }
1478
1479            if (!strncmp(filename.string(), file->d_name, n)) {
1480                const char* p = &file->d_name[n];
1481                size_t plen = strlen(p);
1482
1483                size_t extra = decode_key_length(p, plen);
1484                char *match = (char*) malloc(extra + 1);
1485                if (match != NULL) {
1486                    decode_key(match, p, plen);
1487                    matches->push(String16(match, extra));
1488                    free(match);
1489                } else {
1490                    ALOGW("could not allocate match of size %zd", extra);
1491                }
1492            }
1493        }
1494        closedir(dir);
1495
1496        return ::NO_ERROR;
1497    }
1498
1499    int32_t reset() {
1500        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1501        if (!has_permission(callingUid, P_RESET)) {
1502            ALOGW("permission denied for %d: reset", callingUid);
1503            return ::PERMISSION_DENIED;
1504        }
1505
1506        ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
1507
1508        const keymaster_device_t* device = mKeyStore->getDevice();
1509        if (device == NULL) {
1510            ALOGE("No keymaster device!");
1511            return ::SYSTEM_ERROR;
1512        }
1513
1514        if (device->delete_all == NULL) {
1515            ALOGV("keymaster device doesn't implement delete_all");
1516            return rc;
1517        }
1518
1519        if (device->delete_all(device)) {
1520            ALOGE("Problem calling keymaster's delete_all");
1521            return ::SYSTEM_ERROR;
1522        }
1523
1524        return rc;
1525    }
1526
1527    /*
1528     * Here is the history. To improve the security, the parameters to generate the
1529     * master key has been changed. To make a seamless transition, we update the
1530     * file using the same password when the user unlock it for the first time. If
1531     * any thing goes wrong during the transition, the new file will not overwrite
1532     * the old one. This avoids permanent damages of the existing data.
1533     */
1534    int32_t password(const String16& password) {
1535        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1536        if (!has_permission(callingUid, P_PASSWORD)) {
1537            ALOGW("permission denied for %d: password", callingUid);
1538            return ::PERMISSION_DENIED;
1539        }
1540
1541        const String8 password8(password);
1542
1543        switch (mKeyStore->getState(callingUid)) {
1544            case ::STATE_UNINITIALIZED: {
1545                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1546                return mKeyStore->initializeUser(password8, callingUid);
1547            }
1548            case ::STATE_NO_ERROR: {
1549                // rewrite master key with new password.
1550                return mKeyStore->writeMasterKey(password8, callingUid);
1551            }
1552            case ::STATE_LOCKED: {
1553                // read master key, decrypt with password, initialize mMasterKey*.
1554                return mKeyStore->readMasterKey(password8, callingUid);
1555            }
1556        }
1557        return ::SYSTEM_ERROR;
1558    }
1559
1560    int32_t lock() {
1561        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1562        if (!has_permission(callingUid, P_LOCK)) {
1563            ALOGW("permission denied for %d: lock", callingUid);
1564            return ::PERMISSION_DENIED;
1565        }
1566
1567        State state = mKeyStore->getState(callingUid);
1568        if (state != ::STATE_NO_ERROR) {
1569            ALOGD("calling lock in state: %d", state);
1570            return state;
1571        }
1572
1573        mKeyStore->lock(callingUid);
1574        return ::NO_ERROR;
1575    }
1576
1577    int32_t unlock(const String16& pw) {
1578        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1579        if (!has_permission(callingUid, P_UNLOCK)) {
1580            ALOGW("permission denied for %d: unlock", callingUid);
1581            return ::PERMISSION_DENIED;
1582        }
1583
1584        State state = mKeyStore->getState(callingUid);
1585        if (state != ::STATE_LOCKED) {
1586            ALOGD("calling unlock when not locked");
1587            return state;
1588        }
1589
1590        const String8 password8(pw);
1591        return password(pw);
1592    }
1593
1594    int32_t zero() {
1595        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1596        if (!has_permission(callingUid, P_ZERO)) {
1597            ALOGW("permission denied for %d: zero", callingUid);
1598            return -1;
1599        }
1600
1601        return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
1602    }
1603
1604    int32_t generate(const String16& name, int targetUid) {
1605        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1606        if (!has_permission(callingUid, P_INSERT)) {
1607            ALOGW("permission denied for %d: generate", callingUid);
1608            return ::PERMISSION_DENIED;
1609        }
1610
1611        if (targetUid == -1) {
1612            targetUid = callingUid;
1613        } else if (!is_granted_to(callingUid, targetUid)) {
1614            return ::PERMISSION_DENIED;
1615        }
1616
1617        State state = mKeyStore->getState(callingUid);
1618        if (!isKeystoreUnlocked(state)) {
1619            ALOGD("calling generate in state: %d", state);
1620            return state;
1621        }
1622
1623        uint8_t* data;
1624        size_t dataLength;
1625        int rc;
1626
1627        const keymaster_device_t* device = mKeyStore->getDevice();
1628        if (device == NULL) {
1629            return ::SYSTEM_ERROR;
1630        }
1631
1632        if (device->generate_keypair == NULL) {
1633            return ::SYSTEM_ERROR;
1634        }
1635
1636        keymaster_rsa_keygen_params_t rsa_params;
1637        rsa_params.modulus_size = 2048;
1638        rsa_params.public_exponent = 0x10001;
1639
1640        rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1641        if (rc) {
1642            return ::SYSTEM_ERROR;
1643        }
1644
1645        String8 name8(name);
1646        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1647
1648        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1649        free(data);
1650
1651        return mKeyStore->put(filename.string(), &keyBlob, callingUid);
1652    }
1653
1654    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
1655        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1656        if (!has_permission(callingUid, P_INSERT)) {
1657            ALOGW("permission denied for %d: import", callingUid);
1658            return ::PERMISSION_DENIED;
1659        }
1660
1661        if (targetUid == -1) {
1662            targetUid = callingUid;
1663        } else if (!is_granted_to(callingUid, targetUid)) {
1664            return ::PERMISSION_DENIED;
1665        }
1666
1667        State state = mKeyStore->getState(callingUid);
1668        if (!isKeystoreUnlocked(state)) {
1669            ALOGD("calling import in state: %d", state);
1670            return state;
1671        }
1672
1673        String8 name8(name);
1674        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1675
1676        return mKeyStore->importKey(data, length, filename.string(), callingUid);
1677    }
1678
1679    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1680            size_t* outLength) {
1681        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1682        if (!has_permission(callingUid, P_SIGN)) {
1683            ALOGW("permission denied for %d: saw", callingUid);
1684            return ::PERMISSION_DENIED;
1685        }
1686
1687        State state = mKeyStore->getState(callingUid);
1688        if (!isKeystoreUnlocked(state)) {
1689            ALOGD("calling sign in state: %d", state);
1690            return state;
1691        }
1692
1693        Blob keyBlob;
1694        String8 name8(name);
1695
1696        ALOGV("sign %s from uid %d", name8.string(), callingUid);
1697        int rc;
1698
1699        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1700                ::TYPE_KEY_PAIR);
1701        if (responseCode != ::NO_ERROR) {
1702            return responseCode;
1703        }
1704
1705        const keymaster_device_t* device = mKeyStore->getDevice();
1706        if (device == NULL) {
1707            ALOGE("no keymaster device; cannot sign");
1708            return ::SYSTEM_ERROR;
1709        }
1710
1711        if (device->sign_data == NULL) {
1712            ALOGE("device doesn't implement signing");
1713            return ::SYSTEM_ERROR;
1714        }
1715
1716        keymaster_rsa_sign_params_t params;
1717        params.digest_type = DIGEST_NONE;
1718        params.padding_type = PADDING_NONE;
1719
1720        rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1721                data, length, out, outLength);
1722        if (rc) {
1723            ALOGW("device couldn't sign data");
1724            return ::SYSTEM_ERROR;
1725        }
1726
1727        return ::NO_ERROR;
1728    }
1729
1730    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1731            const uint8_t* signature, size_t signatureLength) {
1732        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1733        if (!has_permission(callingUid, P_VERIFY)) {
1734            ALOGW("permission denied for %d: verify", callingUid);
1735            return ::PERMISSION_DENIED;
1736        }
1737
1738        State state = mKeyStore->getState(callingUid);
1739        if (!isKeystoreUnlocked(state)) {
1740            ALOGD("calling verify in state: %d", state);
1741            return state;
1742        }
1743
1744        Blob keyBlob;
1745        String8 name8(name);
1746        int rc;
1747
1748        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1749                TYPE_KEY_PAIR);
1750        if (responseCode != ::NO_ERROR) {
1751            return responseCode;
1752        }
1753
1754        const keymaster_device_t* device = mKeyStore->getDevice();
1755        if (device == NULL) {
1756            return ::SYSTEM_ERROR;
1757        }
1758
1759        if (device->verify_data == NULL) {
1760            return ::SYSTEM_ERROR;
1761        }
1762
1763        keymaster_rsa_sign_params_t params;
1764        params.digest_type = DIGEST_NONE;
1765        params.padding_type = PADDING_NONE;
1766
1767        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1768                data, dataLength, signature, signatureLength);
1769        if (rc) {
1770            return ::SYSTEM_ERROR;
1771        } else {
1772            return ::NO_ERROR;
1773        }
1774    }
1775
1776    /*
1777     * TODO: The abstraction between things stored in hardware and regular blobs
1778     * of data stored on the filesystem should be moved down to keystore itself.
1779     * Unfortunately the Java code that calls this has naming conventions that it
1780     * knows about. Ideally keystore shouldn't be used to store random blobs of
1781     * data.
1782     *
1783     * Until that happens, it's necessary to have a separate "get_pubkey" and
1784     * "del_key" since the Java code doesn't really communicate what it's
1785     * intentions are.
1786     */
1787    int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
1788        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1789        if (!has_permission(callingUid, P_GET)) {
1790            ALOGW("permission denied for %d: get_pubkey", callingUid);
1791            return ::PERMISSION_DENIED;
1792        }
1793
1794        State state = mKeyStore->getState(callingUid);
1795        if (!isKeystoreUnlocked(state)) {
1796            ALOGD("calling get_pubkey in state: %d", state);
1797            return state;
1798        }
1799
1800        Blob keyBlob;
1801        String8 name8(name);
1802
1803        ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
1804
1805        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
1806                TYPE_KEY_PAIR);
1807        if (responseCode != ::NO_ERROR) {
1808            return responseCode;
1809        }
1810
1811        const keymaster_device_t* device = mKeyStore->getDevice();
1812        if (device == NULL) {
1813            return ::SYSTEM_ERROR;
1814        }
1815
1816        if (device->get_keypair_public == NULL) {
1817            ALOGE("device has no get_keypair_public implementation!");
1818            return ::SYSTEM_ERROR;
1819        }
1820
1821        int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1822                pubkeyLength);
1823        if (rc) {
1824            return ::SYSTEM_ERROR;
1825        }
1826
1827        return ::NO_ERROR;
1828    }
1829
1830    int32_t del_key(const String16& name, int targetUid) {
1831        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1832        if (!has_permission(callingUid, P_DELETE)) {
1833            ALOGW("permission denied for %d: del_key", callingUid);
1834            return ::PERMISSION_DENIED;
1835        }
1836
1837        if (targetUid == -1) {
1838            targetUid = callingUid;
1839        } else if (!is_granted_to(callingUid, targetUid)) {
1840            return ::PERMISSION_DENIED;
1841        }
1842
1843        String8 name8(name);
1844        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1845
1846        Blob keyBlob;
1847        ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
1848                callingUid);
1849        if (responseCode != ::NO_ERROR) {
1850            return responseCode;
1851        }
1852
1853        ResponseCode rc = ::NO_ERROR;
1854
1855        const keymaster_device_t* device = mKeyStore->getDevice();
1856        if (device == NULL) {
1857            rc = ::SYSTEM_ERROR;
1858        } else {
1859            // A device doesn't have to implement delete_keypair.
1860            if (device->delete_keypair != NULL) {
1861                if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1862                    rc = ::SYSTEM_ERROR;
1863                }
1864            }
1865        }
1866
1867        if (rc != ::NO_ERROR) {
1868            return rc;
1869        }
1870
1871        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1872    }
1873
1874    int32_t grant(const String16& name, int32_t granteeUid) {
1875        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1876        if (!has_permission(callingUid, P_GRANT)) {
1877            ALOGW("permission denied for %d: grant", callingUid);
1878            return ::PERMISSION_DENIED;
1879        }
1880
1881        State state = mKeyStore->getState(callingUid);
1882        if (!isKeystoreUnlocked(state)) {
1883            ALOGD("calling grant in state: %d", state);
1884            return state;
1885        }
1886
1887        String8 name8(name);
1888        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1889
1890        if (access(filename.string(), R_OK) == -1) {
1891            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1892        }
1893
1894        mKeyStore->addGrant(filename.string(), granteeUid);
1895        return ::NO_ERROR;
1896    }
1897
1898    int32_t ungrant(const String16& name, int32_t granteeUid) {
1899        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1900        if (!has_permission(callingUid, P_GRANT)) {
1901            ALOGW("permission denied for %d: ungrant", callingUid);
1902            return ::PERMISSION_DENIED;
1903        }
1904
1905        State state = mKeyStore->getState(callingUid);
1906        if (!isKeystoreUnlocked(state)) {
1907            ALOGD("calling ungrant in state: %d", state);
1908            return state;
1909        }
1910
1911        String8 name8(name);
1912        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1913
1914        if (access(filename.string(), R_OK) == -1) {
1915            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1916        }
1917
1918        return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1919    }
1920
1921    int64_t getmtime(const String16& name) {
1922        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1923        if (!has_permission(callingUid, P_GET)) {
1924            ALOGW("permission denied for %d: getmtime", callingUid);
1925            return -1L;
1926        }
1927
1928        String8 name8(name);
1929        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
1930
1931        if (access(filename.string(), R_OK) == -1) {
1932            ALOGW("could not access %s for getmtime", filename.string());
1933            return -1L;
1934        }
1935
1936        int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
1937        if (fd < 0) {
1938            ALOGW("could not open %s for getmtime", filename.string());
1939            return -1L;
1940        }
1941
1942        struct stat s;
1943        int ret = fstat(fd, &s);
1944        close(fd);
1945        if (ret == -1) {
1946            ALOGW("could not stat %s for getmtime", filename.string());
1947            return -1L;
1948        }
1949
1950        return static_cast<int64_t>(s.st_mtime);
1951    }
1952
1953    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1954            int32_t destUid) {
1955        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1956        if (!has_permission(callingUid, P_DUPLICATE)) {
1957            ALOGW("permission denied for %d: duplicate", callingUid);
1958            return -1L;
1959        }
1960
1961        State state = mKeyStore->getState(callingUid);
1962        if (!isKeystoreUnlocked(state)) {
1963            ALOGD("calling duplicate in state: %d", state);
1964            return state;
1965        }
1966
1967        if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1968            srcUid = callingUid;
1969        } else if (!is_granted_to(callingUid, srcUid)) {
1970            ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
1971            return ::PERMISSION_DENIED;
1972        }
1973
1974        if (destUid == -1) {
1975            destUid = callingUid;
1976        }
1977
1978        if (srcUid != destUid) {
1979            if (static_cast<uid_t>(srcUid) != callingUid) {
1980                ALOGD("can only duplicate from caller to other or to same uid: "
1981                      "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1982                return ::PERMISSION_DENIED;
1983            }
1984
1985            if (!is_granted_to(callingUid, destUid)) {
1986                ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1987                return ::PERMISSION_DENIED;
1988            }
1989        }
1990
1991        String8 source8(srcKey);
1992        String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
1993
1994        String8 target8(destKey);
1995        String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
1996
1997        if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
1998            ALOGD("destination already exists: %s", targetFile.string());
1999            return ::SYSTEM_ERROR;
2000        }
2001
2002        Blob keyBlob;
2003        ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2004                callingUid);
2005        if (responseCode != ::NO_ERROR) {
2006            return responseCode;
2007        }
2008
2009        return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
2010    }
2011
2012    int32_t is_hardware_backed() {
2013        return mKeyStore->isHardwareBacked() ? 1 : 0;
2014    }
2015
2016    int32_t clear_uid(int64_t targetUid) {
2017        uid_t callingUid = IPCThreadState::self()->getCallingUid();
2018        if (!has_permission(callingUid, P_CLEAR_UID)) {
2019            ALOGW("permission denied for %d: clear_uid", callingUid);
2020            return ::PERMISSION_DENIED;
2021        }
2022
2023        State state = mKeyStore->getState(callingUid);
2024        if (!isKeystoreUnlocked(state)) {
2025            ALOGD("calling clear_uid in state: %d", state);
2026            return state;
2027        }
2028
2029        const keymaster_device_t* device = mKeyStore->getDevice();
2030        if (device == NULL) {
2031            ALOGW("can't get keymaster device");
2032            return ::SYSTEM_ERROR;
2033        }
2034
2035        UserState* userState = mKeyStore->getUserState(callingUid);
2036        DIR* dir = opendir(userState->getUserDirName());
2037        if (!dir) {
2038            ALOGW("can't open user directory: %s", strerror(errno));
2039            return ::SYSTEM_ERROR;
2040        }
2041
2042        char prefix[NAME_MAX];
2043        int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
2044
2045        ResponseCode rc = ::NO_ERROR;
2046
2047        struct dirent* file;
2048        while ((file = readdir(dir)) != NULL) {
2049            // We only care about files.
2050            if (file->d_type != DT_REG) {
2051                continue;
2052            }
2053
2054            // Skip anything that starts with a "."
2055            if (file->d_name[0] == '.') {
2056                continue;
2057            }
2058
2059            if (strncmp(prefix, file->d_name, n)) {
2060                continue;
2061            }
2062
2063            String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
2064            Blob keyBlob;
2065            if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2066                    != ::NO_ERROR) {
2067                ALOGW("couldn't open %s", filename.string());
2068                continue;
2069            }
2070
2071            if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2072                // A device doesn't have to implement delete_keypair.
2073                if (device->delete_keypair != NULL) {
2074                    if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2075                        rc = ::SYSTEM_ERROR;
2076                        ALOGW("device couldn't remove %s", filename.string());
2077                    }
2078                }
2079            }
2080
2081            if (unlinkat(dirfd(dir), filename.string(), 0) && errno != ENOENT) {
2082                rc = ::SYSTEM_ERROR;
2083                ALOGW("couldn't unlink %s", filename.string());
2084            }
2085        }
2086        closedir(dir);
2087
2088        return rc;
2089    }
2090
2091private:
2092    inline bool isKeystoreUnlocked(State state) {
2093        switch (state) {
2094        case ::STATE_NO_ERROR:
2095            return true;
2096        case ::STATE_UNINITIALIZED:
2097        case ::STATE_LOCKED:
2098            return false;
2099        }
2100        return false;
2101    }
2102
2103    ::KeyStore* mKeyStore;
2104};
2105
2106}; // namespace android
2107
2108int main(int argc, char* argv[]) {
2109    if (argc < 2) {
2110        ALOGE("A directory must be specified!");
2111        return 1;
2112    }
2113    if (chdir(argv[1]) == -1) {
2114        ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2115        return 1;
2116    }
2117
2118    Entropy entropy;
2119    if (!entropy.open()) {
2120        return 1;
2121    }
2122
2123    keymaster_device_t* dev;
2124    if (keymaster_device_initialize(&dev)) {
2125        ALOGE("keystore keymaster could not be initialized; exiting");
2126        return 1;
2127    }
2128
2129    KeyStore keyStore(&entropy, dev);
2130    keyStore.initialize();
2131    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2132    android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2133    android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2134    if (ret != android::OK) {
2135        ALOGE("Couldn't register binder service!");
2136        return -1;
2137    }
2138
2139    /*
2140     * We're the only thread in existence, so we're just going to process
2141     * Binder transaction as a single-threaded program.
2142     */
2143    android::IPCThreadState::self()->joinThreadPool();
2144
2145    keymaster_device_release(dev);
2146    return 1;
2147}
2148