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