keystore.cpp revision 483407eaca108d3717bb49770915d6d95d5d0e0c
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 <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
27#include <fcntl.h>
28#include <limits.h>
29#include <assert.h>
30#include <sys/types.h>
31#include <sys/socket.h>
32#include <sys/stat.h>
33#include <sys/time.h>
34#include <arpa/inet.h>
35
36#include <openssl/aes.h>
37#include <openssl/bio.h>
38#include <openssl/evp.h>
39#include <openssl/md5.h>
40#include <openssl/pem.h>
41
42#include <hardware/keymaster.h>
43
44#include <utils/UniquePtr.h>
45
46#include <cutils/list.h>
47
48#include <keystore/IKeystoreService.h>
49#include <binder/IPCThreadState.h>
50#include <binder/IServiceManager.h>
51
52#include <cutils/log.h>
53#include <cutils/sockets.h>
54#include <private/android_filesystem_config.h>
55
56#include <keystore/keystore.h>
57
58/* KeyStore is a secured storage for key-value pairs. In this implementation,
59 * each file stores one key-value pair. Keys are encoded in file names, and
60 * values are encrypted with checksums. The encryption key is protected by a
61 * user-defined password. To keep things simple, buffers are always larger than
62 * the maximum space we needed, so boundary checks on buffers are omitted. */
63
64#define KEY_SIZE        ((NAME_MAX - 15) / 2)
65#define VALUE_SIZE      32768
66#define PASSWORD_SIZE   VALUE_SIZE
67
68
69struct BIO_Delete {
70    void operator()(BIO* p) const {
71        BIO_free(p);
72    }
73};
74typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
75
76struct EVP_PKEY_Delete {
77    void operator()(EVP_PKEY* p) const {
78        EVP_PKEY_free(p);
79    }
80};
81typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
82
83struct PKCS8_PRIV_KEY_INFO_Delete {
84    void operator()(PKCS8_PRIV_KEY_INFO* p) const {
85        PKCS8_PRIV_KEY_INFO_free(p);
86    }
87};
88typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
89
90
91static int keymaster_device_initialize(keymaster_device_t** dev) {
92    int rc;
93
94    const hw_module_t* mod;
95    rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
96    if (rc) {
97        ALOGE("could not find any keystore module");
98        goto out;
99    }
100
101    rc = keymaster_open(mod, dev);
102    if (rc) {
103        ALOGE("could not open keymaster device in %s (%s)",
104            KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
105        goto out;
106    }
107
108    return 0;
109
110out:
111    *dev = NULL;
112    return rc;
113}
114
115static void keymaster_device_release(keymaster_device_t* dev) {
116    keymaster_close(dev);
117}
118
119/***************
120 * PERMISSIONS *
121 ***************/
122
123/* Here are the permissions, actions, users, and the main function. */
124typedef enum {
125    P_TEST      = 1 << 0,
126    P_GET       = 1 << 1,
127    P_INSERT    = 1 << 2,
128    P_DELETE    = 1 << 3,
129    P_EXIST     = 1 << 4,
130    P_SAW       = 1 << 5,
131    P_RESET     = 1 << 6,
132    P_PASSWORD  = 1 << 7,
133    P_LOCK      = 1 << 8,
134    P_UNLOCK    = 1 << 9,
135    P_ZERO      = 1 << 10,
136    P_SIGN      = 1 << 11,
137    P_VERIFY    = 1 << 12,
138    P_GRANT     = 1 << 13,
139    P_DUPLICATE = 1 << 14,
140    P_CLEAR_UID = 1 << 15,
141} perm_t;
142
143static struct user_euid {
144    uid_t uid;
145    uid_t euid;
146} user_euids[] = {
147    {AID_VPN, AID_SYSTEM},
148    {AID_WIFI, AID_SYSTEM},
149    {AID_ROOT, AID_SYSTEM},
150};
151
152static struct user_perm {
153    uid_t uid;
154    perm_t perms;
155} user_perms[] = {
156    {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
157    {AID_VPN,    static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
158    {AID_WIFI,   static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
159    {AID_ROOT,   static_cast<perm_t>(P_GET) },
160};
161
162static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
163        | P_VERIFY);
164
165static bool has_permission(uid_t uid, perm_t perm) {
166    for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
167        struct user_perm user = user_perms[i];
168        if (user.uid == uid) {
169            return user.perms & perm;
170        }
171    }
172
173    return DEFAULT_PERMS & perm;
174}
175
176/**
177 * Returns the UID that the callingUid should act as. This is here for
178 * legacy support of the WiFi and VPN systems and should be removed
179 * when WiFi can operate in its own namespace.
180 */
181static uid_t get_keystore_euid(uid_t uid) {
182    for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
183        struct user_euid user = user_euids[i];
184        if (user.uid == uid) {
185            return user.euid;
186        }
187    }
188
189    return uid;
190}
191
192/**
193 * Returns true if the callingUid is allowed to interact in the targetUid's
194 * namespace.
195 */
196static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
197    for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
198        struct user_euid user = user_euids[i];
199        if (user.euid == callingUid && user.uid == targetUid) {
200            return true;
201        }
202    }
203
204    return false;
205}
206
207/* Here is the encoding of keys. This is necessary in order to allow arbitrary
208 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
209 * into two bytes. The first byte is one of [+-.] which represents the first
210 * two bits of the character. The second byte encodes the rest of the bits into
211 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
212 * that Base64 cannot be used here due to the need of prefix match on keys. */
213
214static int encode_key(char* out, const android::String8& keyName) {
215    const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
216    size_t length = keyName.length();
217    for (int i = length; i > 0; --i, ++in, ++out) {
218        if (*in >= '0' && *in <= '~') {
219            *out = *in;
220        } else {
221            *out = '+' + (*in >> 6);
222            *++out = '0' + (*in & 0x3F);
223            ++length;
224        }
225    }
226    *out = '\0';
227    return length;
228}
229
230static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
231    int n = snprintf(out, NAME_MAX, "%u_", uid);
232    out += n;
233
234    return n + encode_key(out, keyName);
235}
236
237/*
238 * Converts from the "escaped" format on disk to actual name.
239 * This will be smaller than the input string.
240 *
241 * Characters that should combine with the next at the end will be truncated.
242 */
243static size_t decode_key_length(const char* in, size_t length) {
244    size_t outLength = 0;
245
246    for (const char* end = in + length; in < end; in++) {
247        /* This combines with the next character. */
248        if (*in < '0' || *in > '~') {
249            continue;
250        }
251
252        outLength++;
253    }
254    return outLength;
255}
256
257static void decode_key(char* out, const char* in, size_t length) {
258    for (const char* end = in + length; in < end; in++) {
259        if (*in < '0' || *in > '~') {
260            /* Truncate combining characters at the end. */
261            if (in + 1 >= end) {
262                break;
263            }
264
265            *out = (*in++ - '+') << 6;
266            *out++ |= (*in - '0') & 0x3F;
267        } else {
268            *out++ = *in;
269        }
270    }
271    *out = '\0';
272}
273
274static size_t readFully(int fd, uint8_t* data, size_t size) {
275    size_t remaining = size;
276    while (remaining > 0) {
277        ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
278        if (n <= 0) {
279            return size - remaining;
280        }
281        data += n;
282        remaining -= n;
283    }
284    return size;
285}
286
287static size_t writeFully(int fd, uint8_t* data, size_t size) {
288    size_t remaining = size;
289    while (remaining > 0) {
290        ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
291        if (n < 0) {
292            ALOGW("write failed: %s", strerror(errno));
293            return size - remaining;
294        }
295        data += n;
296        remaining -= n;
297    }
298    return size;
299}
300
301class Entropy {
302public:
303    Entropy() : mRandom(-1) {}
304    ~Entropy() {
305        if (mRandom >= 0) {
306            close(mRandom);
307        }
308    }
309
310    bool open() {
311        const char* randomDevice = "/dev/urandom";
312        mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
313        if (mRandom < 0) {
314            ALOGE("open: %s: %s", randomDevice, strerror(errno));
315            return false;
316        }
317        return true;
318    }
319
320    bool generate_random_data(uint8_t* data, size_t size) const {
321        return (readFully(mRandom, data, size) == size);
322    }
323
324private:
325    int mRandom;
326};
327
328/* Here is the file format. There are two parts in blob.value, the secret and
329 * the description. The secret is stored in ciphertext, and its original size
330 * can be found in blob.length. The description is stored after the secret in
331 * plaintext, and its size is specified in blob.info. The total size of the two
332 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
333 * the second is the blob's type, and the third byte is reserved. Fields other
334 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
335 * and decryptBlob(). Thus they should not be accessed from outside. */
336
337/* ** Note to future implementors of encryption: **
338 * Currently this is the construction:
339 *   metadata || Enc(MD5(data) || data)
340 *
341 * This should be the construction used for encrypting if re-implementing:
342 *
343 *   Derive independent keys for encryption and MAC:
344 *     Kenc = AES_encrypt(masterKey, "Encrypt")
345 *     Kmac = AES_encrypt(masterKey, "MAC")
346 *
347 *   Store this:
348 *     metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
349 *             HMAC(Kmac, metadata || Enc(data))
350 */
351struct __attribute__((packed)) blob {
352    uint8_t version;
353    uint8_t type;
354    uint8_t reserved;
355    uint8_t info;
356    uint8_t vector[AES_BLOCK_SIZE];
357    uint8_t encrypted[0]; // Marks offset to encrypted data.
358    uint8_t digest[MD5_DIGEST_LENGTH];
359    uint8_t digested[0]; // Marks offset to digested data.
360    int32_t length; // in network byte order when encrypted
361    uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
362};
363
364typedef enum {
365    TYPE_ANY = 0, // meta type that matches anything
366    TYPE_GENERIC = 1,
367    TYPE_MASTER_KEY = 2,
368    TYPE_KEY_PAIR = 3,
369} BlobType;
370
371static const uint8_t CURRENT_BLOB_VERSION = 1;
372
373class Blob {
374public:
375    Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
376            BlobType type) {
377        mBlob.length = valueLength;
378        memcpy(mBlob.value, value, valueLength);
379
380        mBlob.info = infoLength;
381        memcpy(mBlob.value + valueLength, info, infoLength);
382
383        mBlob.version = CURRENT_BLOB_VERSION;
384        mBlob.type = uint8_t(type);
385    }
386
387    Blob(blob b) {
388        mBlob = b;
389    }
390
391    Blob() {}
392
393    const uint8_t* getValue() const {
394        return mBlob.value;
395    }
396
397    int32_t getLength() const {
398        return mBlob.length;
399    }
400
401    const uint8_t* getInfo() const {
402        return mBlob.value + mBlob.length;
403    }
404
405    uint8_t getInfoLength() const {
406        return mBlob.info;
407    }
408
409    uint8_t getVersion() const {
410        return mBlob.version;
411    }
412
413    void setVersion(uint8_t version) {
414        mBlob.version = version;
415    }
416
417    BlobType getType() const {
418        return BlobType(mBlob.type);
419    }
420
421    void setType(BlobType type) {
422        mBlob.type = uint8_t(type);
423    }
424
425    ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
426        if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
427            ALOGW("Could not read random data for: %s", filename);
428            return SYSTEM_ERROR;
429        }
430
431        // data includes the value and the value's length
432        size_t dataLength = mBlob.length + sizeof(mBlob.length);
433        // pad data to the AES_BLOCK_SIZE
434        size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
435                                 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
436        // encrypted data includes the digest value
437        size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
438        // move info after space for padding
439        memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
440        // zero padding area
441        memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
442
443        mBlob.length = htonl(mBlob.length);
444        MD5(mBlob.digested, digestedLength, mBlob.digest);
445
446        uint8_t vector[AES_BLOCK_SIZE];
447        memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
448        AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
449                        aes_key, vector, AES_ENCRYPT);
450
451        mBlob.reserved = 0;
452        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
453        size_t fileLength = encryptedLength + headerLength + mBlob.info;
454
455        const char* tmpFileName = ".tmp";
456        int out = TEMP_FAILURE_RETRY(open(tmpFileName,
457                O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
458        if (out < 0) {
459            ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
460            return SYSTEM_ERROR;
461        }
462        size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
463        if (close(out) != 0) {
464            return SYSTEM_ERROR;
465        }
466        if (writtenBytes != fileLength) {
467            ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
468            unlink(tmpFileName);
469            return SYSTEM_ERROR;
470        }
471        if (rename(tmpFileName, filename) == -1) {
472            ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
473            return SYSTEM_ERROR;
474        }
475        return NO_ERROR;
476    }
477
478    ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
479        int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
480        if (in < 0) {
481            return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
482        }
483        // fileLength may be less than sizeof(mBlob) since the in
484        // memory version has extra padding to tolerate rounding up to
485        // the AES_BLOCK_SIZE
486        size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
487        if (close(in) != 0) {
488            return SYSTEM_ERROR;
489        }
490        size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
491        if (fileLength < headerLength) {
492            return VALUE_CORRUPTED;
493        }
494
495        ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
496        if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
497            return VALUE_CORRUPTED;
498        }
499        AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
500                        mBlob.vector, AES_DECRYPT);
501        size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
502        uint8_t computedDigest[MD5_DIGEST_LENGTH];
503        MD5(mBlob.digested, digestedLength, computedDigest);
504        if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
505            return VALUE_CORRUPTED;
506        }
507
508        ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
509        mBlob.length = ntohl(mBlob.length);
510        if (mBlob.length < 0 || mBlob.length > maxValueLength) {
511            return VALUE_CORRUPTED;
512        }
513        if (mBlob.info != 0) {
514            // move info from after padding to after data
515            memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
516        }
517        return ::NO_ERROR;
518    }
519
520private:
521    struct blob mBlob;
522};
523
524typedef struct {
525    uint32_t uid;
526    const uint8_t* filename;
527
528    struct listnode plist;
529} grant_t;
530
531class KeyStore {
532public:
533    KeyStore(Entropy* entropy, keymaster_device_t* device)
534        : mEntropy(entropy)
535        , mDevice(device)
536        , mRetry(MAX_RETRY)
537    {
538        if (access(MASTER_KEY_FILE, R_OK) == 0) {
539            setState(STATE_LOCKED);
540        } else {
541            setState(STATE_UNINITIALIZED);
542        }
543
544        list_init(&mGrants);
545    }
546
547    State getState() const {
548        return mState;
549    }
550
551    int8_t getRetry() const {
552        return mRetry;
553    }
554
555    keymaster_device_t* getDevice() const {
556        return mDevice;
557    }
558
559    ResponseCode initialize(const android::String8& pw) {
560        if (!generateMasterKey()) {
561            return SYSTEM_ERROR;
562        }
563        ResponseCode response = writeMasterKey(pw);
564        if (response != NO_ERROR) {
565            return response;
566        }
567        setupMasterKeys();
568        return ::NO_ERROR;
569    }
570
571    ResponseCode writeMasterKey(const android::String8& pw) {
572        uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
573        generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
574        AES_KEY passwordAesKey;
575        AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
576        Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
577        return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
578    }
579
580    ResponseCode readMasterKey(const android::String8& pw) {
581        int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
582        if (in < 0) {
583            return SYSTEM_ERROR;
584        }
585
586        // we read the raw blob to just to get the salt to generate
587        // the AES key, then we create the Blob to use with decryptBlob
588        blob rawBlob;
589        size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
590        if (close(in) != 0) {
591            return SYSTEM_ERROR;
592        }
593        // find salt at EOF if present, otherwise we have an old file
594        uint8_t* salt;
595        if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
596            salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
597        } else {
598            salt = NULL;
599        }
600        uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
601        generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
602        AES_KEY passwordAesKey;
603        AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
604        Blob masterKeyBlob(rawBlob);
605        ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
606        if (response == SYSTEM_ERROR) {
607            return SYSTEM_ERROR;
608        }
609        if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
610            // if salt was missing, generate one and write a new master key file with the salt.
611            if (salt == NULL) {
612                if (!generateSalt()) {
613                    return SYSTEM_ERROR;
614                }
615                response = writeMasterKey(pw);
616            }
617            if (response == NO_ERROR) {
618                memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
619                setupMasterKeys();
620            }
621            return response;
622        }
623        if (mRetry <= 0) {
624            reset();
625            return UNINITIALIZED;
626        }
627        --mRetry;
628        switch (mRetry) {
629            case 0: return WRONG_PASSWORD_0;
630            case 1: return WRONG_PASSWORD_1;
631            case 2: return WRONG_PASSWORD_2;
632            case 3: return WRONG_PASSWORD_3;
633            default: return WRONG_PASSWORD_3;
634        }
635    }
636
637    bool reset() {
638        clearMasterKeys();
639        setState(STATE_UNINITIALIZED);
640
641        DIR* dir = opendir(".");
642        struct dirent* file;
643
644        if (!dir) {
645            return false;
646        }
647        while ((file = readdir(dir)) != NULL) {
648            unlink(file->d_name);
649        }
650        closedir(dir);
651        return true;
652    }
653
654    bool isEmpty() const {
655        DIR* dir = opendir(".");
656        struct dirent* file;
657        if (!dir) {
658            return true;
659        }
660        bool result = true;
661        while ((file = readdir(dir)) != NULL) {
662            if (isKeyFile(file->d_name)) {
663                result = false;
664                break;
665            }
666        }
667        closedir(dir);
668        return result;
669    }
670
671    void lock() {
672        clearMasterKeys();
673        setState(STATE_LOCKED);
674    }
675
676    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
677        ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
678        if (rc != NO_ERROR) {
679            return rc;
680        }
681
682        const uint8_t version = keyBlob->getVersion();
683        if (version < CURRENT_BLOB_VERSION) {
684            /* If we upgrade the key, we need to write it to disk again. Then
685             * it must be read it again since the blob is encrypted each time
686             * it's written.
687             */
688            if (upgrade(filename, keyBlob, version, type)) {
689                if ((rc = this->put(filename, keyBlob)) != NO_ERROR
690                        || (rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption)) != NO_ERROR) {
691                    return rc;
692                }
693            }
694        }
695
696        if (type != TYPE_ANY && keyBlob->getType() != type) {
697            ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
698            return KEY_NOT_FOUND;
699        }
700
701        return rc;
702    }
703
704    ResponseCode put(const char* filename, Blob* keyBlob) {
705        return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
706    }
707
708    void addGrant(const char* filename, uid_t granteeUid) {
709        grant_t *grant = getGrant(filename, granteeUid);
710        if (grant == NULL) {
711            grant = new grant_t;
712            grant->uid = granteeUid;
713            grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
714            list_add_tail(&mGrants, &grant->plist);
715        }
716    }
717
718    bool removeGrant(const char* filename, uid_t granteeUid) {
719        grant_t *grant = getGrant(filename, granteeUid);
720        if (grant != NULL) {
721            list_remove(&grant->plist);
722            delete grant;
723            return true;
724        }
725
726        return false;
727    }
728
729    bool hasGrant(const char* filename, const uid_t uid) const {
730        return getGrant(filename, uid) != NULL;
731    }
732
733    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
734        uint8_t* data;
735        size_t dataLength;
736        int rc;
737
738        if (mDevice->import_keypair == NULL) {
739            ALOGE("Keymaster doesn't support import!");
740            return SYSTEM_ERROR;
741        }
742
743        rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
744        if (rc) {
745            ALOGE("Error while importing keypair: %d", rc);
746            return SYSTEM_ERROR;
747        }
748
749        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
750        free(data);
751
752        return put(filename, &keyBlob);
753    }
754
755    bool isHardwareBacked() const {
756        return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
757    }
758
759private:
760    static const char* MASTER_KEY_FILE;
761    static const int MASTER_KEY_SIZE_BYTES = 16;
762    static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
763
764    static const int MAX_RETRY = 4;
765    static const size_t SALT_SIZE = 16;
766
767    Entropy* mEntropy;
768
769    keymaster_device_t* mDevice;
770
771    State mState;
772    int8_t mRetry;
773
774    uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
775    uint8_t mSalt[SALT_SIZE];
776
777    AES_KEY mMasterKeyEncryption;
778    AES_KEY mMasterKeyDecryption;
779
780    struct listnode mGrants;
781
782    void setState(State state) {
783        mState = state;
784        if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
785            mRetry = MAX_RETRY;
786        }
787    }
788
789    bool generateSalt() {
790        return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
791    }
792
793    bool generateMasterKey() {
794        if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
795            return false;
796        }
797        if (!generateSalt()) {
798            return false;
799        }
800        return true;
801    }
802
803    void setupMasterKeys() {
804        AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
805        AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
806        setState(STATE_NO_ERROR);
807    }
808
809    void clearMasterKeys() {
810        memset(mMasterKey, 0, sizeof(mMasterKey));
811        memset(mSalt, 0, sizeof(mSalt));
812        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
813        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
814    }
815
816    static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
817            uint8_t* salt) {
818        size_t saltSize;
819        if (salt != NULL) {
820            saltSize = SALT_SIZE;
821        } else {
822            // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
823            salt = (uint8_t*) "keystore";
824            // sizeof = 9, not strlen = 8
825            saltSize = sizeof("keystore");
826        }
827
828        PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
829                saltSize, 8192, keySize, key);
830    }
831
832    static bool isKeyFile(const char* filename) {
833        return ((strcmp(filename, MASTER_KEY_FILE) != 0)
834                && (strcmp(filename, ".") != 0)
835                && (strcmp(filename, "..") != 0));
836    }
837
838    grant_t* getGrant(const char* filename, uid_t uid) const {
839        struct listnode *node;
840        grant_t *grant;
841
842        list_for_each(node, &mGrants) {
843            grant = node_to_item(node, grant_t, plist);
844            if (grant->uid == uid
845                    && !strcmp(reinterpret_cast<const char*>(grant->filename),
846                               filename)) {
847                return grant;
848            }
849        }
850
851        return NULL;
852    }
853
854    /**
855     * Upgrade code. This will upgrade the key from the current version
856     * to whatever is newest.
857     */
858    bool upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
859        bool updated = false;
860        uint8_t version = oldVersion;
861
862        /* From V0 -> V1: All old types were unknown */
863        if (version == 0) {
864            ALOGV("upgrading to version 1 and setting type %d", type);
865
866            blob->setType(type);
867            if (type == TYPE_KEY_PAIR) {
868                importBlobAsKey(blob, filename);
869            }
870            version = 1;
871            updated = true;
872        }
873
874        /*
875         * If we've updated, set the key blob to the right version
876         * and write it.
877         */
878        if (updated) {
879            ALOGV("updated and writing file %s", filename);
880            blob->setVersion(version);
881        }
882
883        return updated;
884    }
885
886    /**
887     * Takes a blob that is an PEM-encoded RSA key as a byte array and
888     * converts it to a DER-encoded PKCS#8 for import into a keymaster.
889     * Then it overwrites the original blob with the new blob
890     * format that is returned from the keymaster.
891     */
892    ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
893        // We won't even write to the blob directly with this BIO, so const_cast is okay.
894        Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
895        if (b.get() == NULL) {
896            ALOGE("Problem instantiating BIO");
897            return SYSTEM_ERROR;
898        }
899
900        Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
901        if (pkey.get() == NULL) {
902            ALOGE("Couldn't read old PEM file");
903            return SYSTEM_ERROR;
904        }
905
906        Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
907        int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
908        if (len < 0) {
909            ALOGE("Couldn't measure PKCS#8 length");
910            return SYSTEM_ERROR;
911        }
912
913        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
914        uint8_t* tmp = pkcs8key.get();
915        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
916            ALOGE("Couldn't convert to PKCS#8");
917            return SYSTEM_ERROR;
918        }
919
920        ResponseCode rc = importKey(pkcs8key.get(), len, filename);
921        if (rc != NO_ERROR) {
922            return rc;
923        }
924
925        return get(filename, blob, TYPE_KEY_PAIR);
926    }
927};
928
929const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
930
931static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
932        const android::String8& keyName, const uid_t uid, const BlobType type) {
933    char filename[NAME_MAX];
934
935    encode_key_for_uid(filename, uid, keyName);
936    ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
937    if (responseCode == NO_ERROR) {
938        return responseCode;
939    }
940
941    // If this is one of the legacy UID->UID mappings, use it.
942    uid_t euid = get_keystore_euid(uid);
943    if (euid != uid) {
944        encode_key_for_uid(filename, euid, keyName);
945        responseCode = keyStore->get(filename, keyBlob, type);
946        if (responseCode == NO_ERROR) {
947            return responseCode;
948        }
949    }
950
951    // They might be using a granted key.
952    encode_key(filename, keyName);
953    if (!keyStore->hasGrant(filename, uid)) {
954        return responseCode;
955    }
956
957    // It is a granted key. Try to load it.
958    return keyStore->get(filename, keyBlob, type);
959}
960
961namespace android {
962class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
963public:
964    KeyStoreProxy(KeyStore* keyStore)
965        : mKeyStore(keyStore)
966    {
967    }
968
969    void binderDied(const wp<IBinder>&) {
970        ALOGE("binder death detected");
971    }
972
973    int32_t test() {
974        uid_t callingUid = IPCThreadState::self()->getCallingUid();
975        if (!has_permission(callingUid, P_TEST)) {
976            ALOGW("permission denied for %d: test", callingUid);
977            return ::PERMISSION_DENIED;
978        }
979
980        return mKeyStore->getState();
981    }
982
983    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
984        uid_t callingUid = IPCThreadState::self()->getCallingUid();
985        if (!has_permission(callingUid, P_GET)) {
986            ALOGW("permission denied for %d: get", callingUid);
987            return ::PERMISSION_DENIED;
988        }
989
990        State state = mKeyStore->getState();
991        if (!isKeystoreUnlocked(state)) {
992            ALOGD("calling get in state: %d", state);
993            return state;
994        }
995
996        String8 name8(name);
997        char filename[NAME_MAX];
998        Blob keyBlob;
999
1000        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1001                TYPE_GENERIC);
1002        if (responseCode != ::NO_ERROR) {
1003            ALOGW("Could not read %s", filename);
1004            *item = NULL;
1005            *itemLength = 0;
1006            return responseCode;
1007        }
1008
1009        *item = (uint8_t*) malloc(keyBlob.getLength());
1010        memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1011        *itemLength = keyBlob.getLength();
1012
1013        return ::NO_ERROR;
1014    }
1015
1016    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
1017        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1018        if (!has_permission(callingUid, P_INSERT)) {
1019            ALOGW("permission denied for %d: insert", callingUid);
1020            return ::PERMISSION_DENIED;
1021        }
1022
1023        if (targetUid == -1) {
1024            targetUid = callingUid;
1025        } else if (!is_granted_to(callingUid, targetUid)) {
1026            return ::PERMISSION_DENIED;
1027        }
1028
1029        State state = mKeyStore->getState();
1030        if (!isKeystoreUnlocked(state)) {
1031            ALOGD("calling insert in state: %d", state);
1032            return state;
1033        }
1034
1035        String8 name8(name);
1036        char filename[NAME_MAX];
1037
1038        encode_key_for_uid(filename, targetUid, name8);
1039
1040        Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1041        return mKeyStore->put(filename, &keyBlob);
1042    }
1043
1044    int32_t del(const String16& name, int targetUid) {
1045        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1046        if (!has_permission(callingUid, P_DELETE)) {
1047            ALOGW("permission denied for %d: del", callingUid);
1048            return ::PERMISSION_DENIED;
1049        }
1050
1051        if (targetUid == -1) {
1052            targetUid = callingUid;
1053        } else if (!is_granted_to(callingUid, targetUid)) {
1054            return ::PERMISSION_DENIED;
1055        }
1056
1057        String8 name8(name);
1058        char filename[NAME_MAX];
1059
1060        encode_key_for_uid(filename, targetUid, name8);
1061
1062        Blob keyBlob;
1063        ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1064        if (responseCode != ::NO_ERROR) {
1065            return responseCode;
1066        }
1067        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1068    }
1069
1070    int32_t exist(const String16& name, int targetUid) {
1071        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1072        if (!has_permission(callingUid, P_EXIST)) {
1073            ALOGW("permission denied for %d: exist", callingUid);
1074            return ::PERMISSION_DENIED;
1075        }
1076
1077        if (targetUid == -1) {
1078            targetUid = callingUid;
1079        } else if (!is_granted_to(callingUid, targetUid)) {
1080            return ::PERMISSION_DENIED;
1081        }
1082
1083        String8 name8(name);
1084        char filename[NAME_MAX];
1085
1086        encode_key_for_uid(filename, targetUid, name8);
1087
1088        if (access(filename, R_OK) == -1) {
1089            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1090        }
1091        return ::NO_ERROR;
1092    }
1093
1094    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1095        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1096        if (!has_permission(callingUid, P_SAW)) {
1097            ALOGW("permission denied for %d: saw", callingUid);
1098            return ::PERMISSION_DENIED;
1099        }
1100
1101        if (targetUid == -1) {
1102            targetUid = callingUid;
1103        } else if (!is_granted_to(callingUid, targetUid)) {
1104            return ::PERMISSION_DENIED;
1105        }
1106
1107        DIR* dir = opendir(".");
1108        if (!dir) {
1109            return ::SYSTEM_ERROR;
1110        }
1111
1112        const String8 prefix8(prefix);
1113        char filename[NAME_MAX];
1114
1115        int n = encode_key_for_uid(filename, targetUid, prefix8);
1116
1117        struct dirent* file;
1118        while ((file = readdir(dir)) != NULL) {
1119            if (!strncmp(filename, file->d_name, n)) {
1120                const char* p = &file->d_name[n];
1121                size_t plen = strlen(p);
1122
1123                size_t extra = decode_key_length(p, plen);
1124                char *match = (char*) malloc(extra + 1);
1125                if (match != NULL) {
1126                    decode_key(match, p, plen);
1127                    matches->push(String16(match, extra));
1128                    free(match);
1129                } else {
1130                    ALOGW("could not allocate match of size %zd", extra);
1131                }
1132            }
1133        }
1134        closedir(dir);
1135
1136        return ::NO_ERROR;
1137    }
1138
1139    int32_t reset() {
1140        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1141        if (!has_permission(callingUid, P_RESET)) {
1142            ALOGW("permission denied for %d: reset", callingUid);
1143            return ::PERMISSION_DENIED;
1144        }
1145
1146        ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1147
1148        const keymaster_device_t* device = mKeyStore->getDevice();
1149        if (device == NULL) {
1150            ALOGE("No keymaster device!");
1151            return ::SYSTEM_ERROR;
1152        }
1153
1154        if (device->delete_all == NULL) {
1155            ALOGV("keymaster device doesn't implement delete_all");
1156            return rc;
1157        }
1158
1159        if (device->delete_all(device)) {
1160            ALOGE("Problem calling keymaster's delete_all");
1161            return ::SYSTEM_ERROR;
1162        }
1163
1164        return rc;
1165    }
1166
1167    /*
1168     * Here is the history. To improve the security, the parameters to generate the
1169     * master key has been changed. To make a seamless transition, we update the
1170     * file using the same password when the user unlock it for the first time. If
1171     * any thing goes wrong during the transition, the new file will not overwrite
1172     * the old one. This avoids permanent damages of the existing data.
1173     */
1174    int32_t password(const String16& password) {
1175        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1176        if (!has_permission(callingUid, P_PASSWORD)) {
1177            ALOGW("permission denied for %d: password", callingUid);
1178            return ::PERMISSION_DENIED;
1179        }
1180
1181        const String8 password8(password);
1182
1183        switch (mKeyStore->getState()) {
1184            case ::STATE_UNINITIALIZED: {
1185                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1186                return mKeyStore->initialize(password8);
1187            }
1188            case ::STATE_NO_ERROR: {
1189                // rewrite master key with new password.
1190                return mKeyStore->writeMasterKey(password8);
1191            }
1192            case ::STATE_LOCKED: {
1193                // read master key, decrypt with password, initialize mMasterKey*.
1194                return mKeyStore->readMasterKey(password8);
1195            }
1196        }
1197        return ::SYSTEM_ERROR;
1198    }
1199
1200    int32_t lock() {
1201        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1202        if (!has_permission(callingUid, P_LOCK)) {
1203            ALOGW("permission denied for %d: lock", callingUid);
1204            return ::PERMISSION_DENIED;
1205        }
1206
1207        State state = mKeyStore->getState();
1208        if (state != ::STATE_NO_ERROR) {
1209            ALOGD("calling lock in state: %d", state);
1210            return state;
1211        }
1212
1213        mKeyStore->lock();
1214        return ::NO_ERROR;
1215    }
1216
1217    int32_t unlock(const String16& pw) {
1218        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1219        if (!has_permission(callingUid, P_UNLOCK)) {
1220            ALOGW("permission denied for %d: unlock", callingUid);
1221            return ::PERMISSION_DENIED;
1222        }
1223
1224        State state = mKeyStore->getState();
1225        if (state != ::STATE_LOCKED) {
1226            ALOGD("calling unlock when not locked");
1227            return state;
1228        }
1229
1230        const String8 password8(pw);
1231        return password(pw);
1232    }
1233
1234    int32_t zero() {
1235        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1236        if (!has_permission(callingUid, P_ZERO)) {
1237            ALOGW("permission denied for %d: zero", callingUid);
1238            return -1;
1239        }
1240
1241        return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
1242    }
1243
1244    int32_t generate(const String16& name, int targetUid) {
1245        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1246        if (!has_permission(callingUid, P_INSERT)) {
1247            ALOGW("permission denied for %d: generate", callingUid);
1248            return ::PERMISSION_DENIED;
1249        }
1250
1251        if (targetUid == -1) {
1252            targetUid = callingUid;
1253        } else if (!is_granted_to(callingUid, targetUid)) {
1254            return ::PERMISSION_DENIED;
1255        }
1256
1257        State state = mKeyStore->getState();
1258        if (!isKeystoreUnlocked(state)) {
1259            ALOGD("calling generate in state: %d", state);
1260            return state;
1261        }
1262
1263        String8 name8(name);
1264        char filename[NAME_MAX];
1265
1266        uint8_t* data;
1267        size_t dataLength;
1268        int rc;
1269
1270        const keymaster_device_t* device = mKeyStore->getDevice();
1271        if (device == NULL) {
1272            return ::SYSTEM_ERROR;
1273        }
1274
1275        if (device->generate_keypair == NULL) {
1276            return ::SYSTEM_ERROR;
1277        }
1278
1279        keymaster_rsa_keygen_params_t rsa_params;
1280        rsa_params.modulus_size = 2048;
1281        rsa_params.public_exponent = 0x10001;
1282
1283        rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1284        if (rc) {
1285            return ::SYSTEM_ERROR;
1286        }
1287
1288        encode_key_for_uid(filename, targetUid, name8);
1289
1290        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1291        free(data);
1292
1293        return mKeyStore->put(filename, &keyBlob);
1294    }
1295
1296    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
1297        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1298        if (!has_permission(callingUid, P_INSERT)) {
1299            ALOGW("permission denied for %d: import", callingUid);
1300            return ::PERMISSION_DENIED;
1301        }
1302
1303        if (targetUid == -1) {
1304            targetUid = callingUid;
1305        } else if (!is_granted_to(callingUid, targetUid)) {
1306            return ::PERMISSION_DENIED;
1307        }
1308
1309        State state = mKeyStore->getState();
1310        if (!isKeystoreUnlocked(state)) {
1311            ALOGD("calling import in state: %d", state);
1312            return state;
1313        }
1314
1315        String8 name8(name);
1316        char filename[NAME_MAX];
1317
1318        encode_key_for_uid(filename, targetUid, name8);
1319
1320        return mKeyStore->importKey(data, length, filename);
1321    }
1322
1323    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1324            size_t* outLength) {
1325        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1326        if (!has_permission(callingUid, P_SIGN)) {
1327            ALOGW("permission denied for %d: saw", callingUid);
1328            return ::PERMISSION_DENIED;
1329        }
1330
1331        State state = mKeyStore->getState();
1332        if (!isKeystoreUnlocked(state)) {
1333            ALOGD("calling sign in state: %d", state);
1334            return state;
1335        }
1336
1337        Blob keyBlob;
1338        String8 name8(name);
1339
1340        ALOGV("sign %s from uid %d", name8.string(), callingUid);
1341        int rc;
1342
1343        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1344                ::TYPE_KEY_PAIR);
1345        if (responseCode != ::NO_ERROR) {
1346            return responseCode;
1347        }
1348
1349        const keymaster_device_t* device = mKeyStore->getDevice();
1350        if (device == NULL) {
1351            ALOGE("no keymaster device; cannot sign");
1352            return ::SYSTEM_ERROR;
1353        }
1354
1355        if (device->sign_data == NULL) {
1356            ALOGE("device doesn't implement signing");
1357            return ::SYSTEM_ERROR;
1358        }
1359
1360        keymaster_rsa_sign_params_t params;
1361        params.digest_type = DIGEST_NONE;
1362        params.padding_type = PADDING_NONE;
1363
1364        rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1365                data, length, out, outLength);
1366        if (rc) {
1367            ALOGW("device couldn't sign data");
1368            return ::SYSTEM_ERROR;
1369        }
1370
1371        return ::NO_ERROR;
1372    }
1373
1374    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1375            const uint8_t* signature, size_t signatureLength) {
1376        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1377        if (!has_permission(callingUid, P_VERIFY)) {
1378            ALOGW("permission denied for %d: verify", callingUid);
1379            return ::PERMISSION_DENIED;
1380        }
1381
1382        State state = mKeyStore->getState();
1383        if (!isKeystoreUnlocked(state)) {
1384            ALOGD("calling verify in state: %d", state);
1385            return state;
1386        }
1387
1388        Blob keyBlob;
1389        String8 name8(name);
1390        int rc;
1391
1392        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1393                TYPE_KEY_PAIR);
1394        if (responseCode != ::NO_ERROR) {
1395            return responseCode;
1396        }
1397
1398        const keymaster_device_t* device = mKeyStore->getDevice();
1399        if (device == NULL) {
1400            return ::SYSTEM_ERROR;
1401        }
1402
1403        if (device->verify_data == NULL) {
1404            return ::SYSTEM_ERROR;
1405        }
1406
1407        keymaster_rsa_sign_params_t params;
1408        params.digest_type = DIGEST_NONE;
1409        params.padding_type = PADDING_NONE;
1410
1411        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1412                data, dataLength, signature, signatureLength);
1413        if (rc) {
1414            return ::SYSTEM_ERROR;
1415        } else {
1416            return ::NO_ERROR;
1417        }
1418    }
1419
1420    /*
1421     * TODO: The abstraction between things stored in hardware and regular blobs
1422     * of data stored on the filesystem should be moved down to keystore itself.
1423     * Unfortunately the Java code that calls this has naming conventions that it
1424     * knows about. Ideally keystore shouldn't be used to store random blobs of
1425     * data.
1426     *
1427     * Until that happens, it's necessary to have a separate "get_pubkey" and
1428     * "del_key" since the Java code doesn't really communicate what it's
1429     * intentions are.
1430     */
1431    int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
1432        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1433        if (!has_permission(callingUid, P_GET)) {
1434            ALOGW("permission denied for %d: get_pubkey", callingUid);
1435            return ::PERMISSION_DENIED;
1436        }
1437
1438        State state = mKeyStore->getState();
1439        if (!isKeystoreUnlocked(state)) {
1440            ALOGD("calling get_pubkey in state: %d", state);
1441            return state;
1442        }
1443
1444        Blob keyBlob;
1445        String8 name8(name);
1446
1447        ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
1448
1449        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1450                TYPE_KEY_PAIR);
1451        if (responseCode != ::NO_ERROR) {
1452            return responseCode;
1453        }
1454
1455        const keymaster_device_t* device = mKeyStore->getDevice();
1456        if (device == NULL) {
1457            return ::SYSTEM_ERROR;
1458        }
1459
1460        if (device->get_keypair_public == NULL) {
1461            ALOGE("device has no get_keypair_public implementation!");
1462            return ::SYSTEM_ERROR;
1463        }
1464
1465        int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1466                pubkeyLength);
1467        if (rc) {
1468            return ::SYSTEM_ERROR;
1469        }
1470
1471        return ::NO_ERROR;
1472    }
1473
1474    int32_t del_key(const String16& name, int targetUid) {
1475        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1476        if (!has_permission(callingUid, P_DELETE)) {
1477            ALOGW("permission denied for %d: del_key", callingUid);
1478            return ::PERMISSION_DENIED;
1479        }
1480
1481        if (targetUid == -1) {
1482            targetUid = callingUid;
1483        } else if (!is_granted_to(callingUid, targetUid)) {
1484            return ::PERMISSION_DENIED;
1485        }
1486
1487        String8 name8(name);
1488        char filename[NAME_MAX];
1489
1490        encode_key_for_uid(filename, targetUid, name8);
1491
1492        Blob keyBlob;
1493        ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1494        if (responseCode != ::NO_ERROR) {
1495            return responseCode;
1496        }
1497
1498        ResponseCode rc = ::NO_ERROR;
1499
1500        const keymaster_device_t* device = mKeyStore->getDevice();
1501        if (device == NULL) {
1502            rc = ::SYSTEM_ERROR;
1503        } else {
1504            // A device doesn't have to implement delete_keypair.
1505            if (device->delete_keypair != NULL) {
1506                if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1507                    rc = ::SYSTEM_ERROR;
1508                }
1509            }
1510        }
1511
1512        if (rc != ::NO_ERROR) {
1513            return rc;
1514        }
1515
1516        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1517    }
1518
1519    int32_t grant(const String16& name, int32_t granteeUid) {
1520        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1521        if (!has_permission(callingUid, P_GRANT)) {
1522            ALOGW("permission denied for %d: grant", callingUid);
1523            return ::PERMISSION_DENIED;
1524        }
1525
1526        State state = mKeyStore->getState();
1527        if (!isKeystoreUnlocked(state)) {
1528            ALOGD("calling grant in state: %d", state);
1529            return state;
1530        }
1531
1532        String8 name8(name);
1533        char filename[NAME_MAX];
1534
1535        encode_key_for_uid(filename, callingUid, name8);
1536
1537        if (access(filename, R_OK) == -1) {
1538            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1539        }
1540
1541        mKeyStore->addGrant(filename, granteeUid);
1542        return ::NO_ERROR;
1543    }
1544
1545    int32_t ungrant(const String16& name, int32_t granteeUid) {
1546        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1547        if (!has_permission(callingUid, P_GRANT)) {
1548            ALOGW("permission denied for %d: ungrant", callingUid);
1549            return ::PERMISSION_DENIED;
1550        }
1551
1552        State state = mKeyStore->getState();
1553        if (!isKeystoreUnlocked(state)) {
1554            ALOGD("calling ungrant in state: %d", state);
1555            return state;
1556        }
1557
1558        String8 name8(name);
1559        char filename[NAME_MAX];
1560
1561        encode_key_for_uid(filename, callingUid, name8);
1562
1563        if (access(filename, R_OK) == -1) {
1564            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1565        }
1566
1567        return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1568    }
1569
1570    int64_t getmtime(const String16& name) {
1571        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1572        if (!has_permission(callingUid, P_GET)) {
1573            ALOGW("permission denied for %d: getmtime", callingUid);
1574            return -1L;
1575        }
1576
1577        String8 name8(name);
1578        char filename[NAME_MAX];
1579
1580        encode_key_for_uid(filename, callingUid, name8);
1581
1582        if (access(filename, R_OK) == -1) {
1583            ALOGW("could not access %s for getmtime", filename);
1584            return -1L;
1585        }
1586
1587        int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
1588        if (fd < 0) {
1589            ALOGW("could not open %s for getmtime", filename);
1590            return -1L;
1591        }
1592
1593        struct stat s;
1594        int ret = fstat(fd, &s);
1595        close(fd);
1596        if (ret == -1) {
1597            ALOGW("could not stat %s for getmtime", filename);
1598            return -1L;
1599        }
1600
1601        return static_cast<int64_t>(s.st_mtime);
1602    }
1603
1604    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1605            int32_t destUid) {
1606        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1607        if (!has_permission(callingUid, P_DUPLICATE)) {
1608            ALOGW("permission denied for %d: duplicate", callingUid);
1609            return -1L;
1610        }
1611
1612        State state = mKeyStore->getState();
1613        if (!isKeystoreUnlocked(state)) {
1614            ALOGD("calling duplicate in state: %d", state);
1615            return state;
1616        }
1617
1618        if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1619            srcUid = callingUid;
1620        } else if (!is_granted_to(callingUid, srcUid)) {
1621            ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
1622            return ::PERMISSION_DENIED;
1623        }
1624
1625        if (destUid == -1) {
1626            destUid = callingUid;
1627        }
1628
1629        if (srcUid != destUid) {
1630            if (static_cast<uid_t>(srcUid) != callingUid) {
1631                ALOGD("can only duplicate from caller to other or to same uid: "
1632                      "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1633                return ::PERMISSION_DENIED;
1634            }
1635
1636            if (!is_granted_to(callingUid, destUid)) {
1637                ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1638                return ::PERMISSION_DENIED;
1639            }
1640        }
1641
1642        String8 source8(srcKey);
1643        char source[NAME_MAX];
1644
1645        encode_key_for_uid(source, srcUid, source8);
1646
1647        String8 target8(destKey);
1648        char target[NAME_MAX];
1649
1650        encode_key_for_uid(target, destUid, target8);
1651
1652        if (access(target, W_OK) != -1 || errno != ENOENT) {
1653            ALOGD("destination already exists: %s", target);
1654            return ::SYSTEM_ERROR;
1655        }
1656
1657        Blob keyBlob;
1658        ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
1659        if (responseCode != ::NO_ERROR) {
1660            return responseCode;
1661        }
1662
1663        return mKeyStore->put(target, &keyBlob);
1664    }
1665
1666    int32_t is_hardware_backed() {
1667        return mKeyStore->isHardwareBacked() ? 1 : 0;
1668    }
1669
1670    int32_t clear_uid(int64_t targetUid) {
1671        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1672        if (!has_permission(callingUid, P_CLEAR_UID)) {
1673            ALOGW("permission denied for %d: clear_uid", callingUid);
1674            return ::PERMISSION_DENIED;
1675        }
1676
1677        State state = mKeyStore->getState();
1678        if (!isKeystoreUnlocked(state)) {
1679            ALOGD("calling clear_uid in state: %d", state);
1680            return state;
1681        }
1682
1683        const keymaster_device_t* device = mKeyStore->getDevice();
1684        if (device == NULL) {
1685            return ::SYSTEM_ERROR;
1686        }
1687
1688        DIR* dir = opendir(".");
1689        if (!dir) {
1690            return ::SYSTEM_ERROR;
1691        }
1692
1693        char filename[NAME_MAX];
1694        int n = snprintf(filename, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
1695        char *end = &filename[n];
1696
1697        ResponseCode rc = ::NO_ERROR;
1698
1699        struct dirent* file;
1700        while ((file = readdir(dir)) != NULL) {
1701            if (strncmp(filename, file->d_name, n)) {
1702                continue;
1703            }
1704
1705            String8 file8(&file->d_name[n]);
1706            encode_key(end, file8);
1707
1708            Blob keyBlob;
1709            if (mKeyStore->get(filename, &keyBlob, ::TYPE_ANY) != ::NO_ERROR) {
1710                ALOGW("couldn't open %s", filename);
1711                continue;
1712            }
1713
1714            if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1715                // A device doesn't have to implement delete_keypair.
1716                if (device->delete_keypair != NULL) {
1717                    if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1718                        rc = ::SYSTEM_ERROR;
1719                        ALOGW("device couldn't remove %s", filename);
1720                    }
1721                }
1722            }
1723
1724            if (unlink(filename) && errno != ENOENT) {
1725                rc = ::SYSTEM_ERROR;
1726                ALOGW("couldn't unlink %s", filename);
1727            }
1728        }
1729        closedir(dir);
1730
1731        return rc;
1732    }
1733
1734private:
1735    inline bool isKeystoreUnlocked(State state) {
1736        switch (state) {
1737        case ::STATE_NO_ERROR:
1738            return true;
1739        case ::STATE_UNINITIALIZED:
1740        case ::STATE_LOCKED:
1741            return false;
1742        }
1743        return false;
1744    }
1745
1746    ::KeyStore* mKeyStore;
1747};
1748
1749}; // namespace android
1750
1751int main(int argc, char* argv[]) {
1752    if (argc < 2) {
1753        ALOGE("A directory must be specified!");
1754        return 1;
1755    }
1756    if (chdir(argv[1]) == -1) {
1757        ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1758        return 1;
1759    }
1760
1761    Entropy entropy;
1762    if (!entropy.open()) {
1763        return 1;
1764    }
1765
1766    keymaster_device_t* dev;
1767    if (keymaster_device_initialize(&dev)) {
1768        ALOGE("keystore keymaster could not be initialized; exiting");
1769        return 1;
1770    }
1771
1772    KeyStore keyStore(&entropy, dev);
1773    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1774    android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1775    android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1776    if (ret != android::OK) {
1777        ALOGE("Couldn't register binder service!");
1778        return -1;
1779    }
1780
1781    /*
1782     * We're the only thread in existence, so we're just going to process
1783     * Binder transaction as a single-threaded program.
1784     */
1785    android::IPCThreadState::self()->joinThreadPool();
1786
1787    keymaster_device_release(dev);
1788    return 1;
1789}
1790