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