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