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