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