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