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