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