keystore.cpp revision d53bc92f1cc4eb669ec015480cebe5ae7aaaf7cf
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
745private:
746    static const char* MASTER_KEY_FILE;
747    static const int MASTER_KEY_SIZE_BYTES = 16;
748    static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
749
750    static const int MAX_RETRY = 4;
751    static const size_t SALT_SIZE = 16;
752
753    Entropy* mEntropy;
754
755    keymaster_device_t* mDevice;
756
757    State mState;
758    int8_t mRetry;
759
760    uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
761    uint8_t mSalt[SALT_SIZE];
762
763    AES_KEY mMasterKeyEncryption;
764    AES_KEY mMasterKeyDecryption;
765
766    struct listnode mGrants;
767
768    void setState(State state) {
769        mState = state;
770        if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
771            mRetry = MAX_RETRY;
772        }
773    }
774
775    bool generateSalt() {
776        return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
777    }
778
779    bool generateMasterKey() {
780        if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
781            return false;
782        }
783        if (!generateSalt()) {
784            return false;
785        }
786        return true;
787    }
788
789    void setupMasterKeys() {
790        AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
791        AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
792        setState(STATE_NO_ERROR);
793    }
794
795    void clearMasterKeys() {
796        memset(mMasterKey, 0, sizeof(mMasterKey));
797        memset(mSalt, 0, sizeof(mSalt));
798        memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
799        memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
800    }
801
802    static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
803            uint8_t* salt) {
804        size_t saltSize;
805        if (salt != NULL) {
806            saltSize = SALT_SIZE;
807        } else {
808            // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
809            salt = (uint8_t*) "keystore";
810            // sizeof = 9, not strlen = 8
811            saltSize = sizeof("keystore");
812        }
813
814        PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
815                saltSize, 8192, keySize, key);
816    }
817
818    static bool isKeyFile(const char* filename) {
819        return ((strcmp(filename, MASTER_KEY_FILE) != 0)
820                && (strcmp(filename, ".") != 0)
821                && (strcmp(filename, "..") != 0));
822    }
823
824    grant_t* getGrant(const char* filename, uid_t uid) const {
825        struct listnode *node;
826        grant_t *grant;
827
828        list_for_each(node, &mGrants) {
829            grant = node_to_item(node, grant_t, plist);
830            if (grant->uid == uid
831                    && !strcmp(reinterpret_cast<const char*>(grant->filename),
832                               filename)) {
833                return grant;
834            }
835        }
836
837        return NULL;
838    }
839
840    /**
841     * Upgrade code. This will upgrade the key from the current version
842     * to whatever is newest.
843     */
844    void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
845        bool updated = false;
846        uint8_t version = oldVersion;
847
848        /* From V0 -> V1: All old types were unknown */
849        if (version == 0) {
850            ALOGV("upgrading to version 1 and setting type %d", type);
851
852            blob->setType(type);
853            if (type == TYPE_KEY_PAIR) {
854                importBlobAsKey(blob, filename);
855            }
856            version = 1;
857            updated = true;
858        }
859
860        /*
861         * If we've updated, set the key blob to the right version
862         * and write it.
863         * */
864        if (updated) {
865            ALOGV("updated and writing file %s", filename);
866            blob->setVersion(version);
867            this->put(filename, blob);
868        }
869    }
870
871    /**
872     * Takes a blob that is an PEM-encoded RSA key as a byte array and
873     * converts it to a DER-encoded PKCS#8 for import into a keymaster.
874     * Then it overwrites the original blob with the new blob
875     * format that is returned from the keymaster.
876     */
877    ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
878        // We won't even write to the blob directly with this BIO, so const_cast is okay.
879        Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
880        if (b.get() == NULL) {
881            ALOGE("Problem instantiating BIO");
882            return SYSTEM_ERROR;
883        }
884
885        Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
886        if (pkey.get() == NULL) {
887            ALOGE("Couldn't read old PEM file");
888            return SYSTEM_ERROR;
889        }
890
891        Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
892        int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
893        if (len < 0) {
894            ALOGE("Couldn't measure PKCS#8 length");
895            return SYSTEM_ERROR;
896        }
897
898        UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
899        uint8_t* tmp = pkcs8key.get();
900        if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
901            ALOGE("Couldn't convert to PKCS#8");
902            return SYSTEM_ERROR;
903        }
904
905        ResponseCode rc = importKey(pkcs8key.get(), len, filename);
906        if (rc != NO_ERROR) {
907            return rc;
908        }
909
910        return get(filename, blob, TYPE_KEY_PAIR);
911    }
912};
913
914const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
915
916static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
917        const android::String8& keyName, const uid_t uid, const BlobType type) {
918    char filename[NAME_MAX];
919
920    encode_key_for_uid(filename, uid, keyName);
921    ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
922    if (responseCode == NO_ERROR) {
923        return responseCode;
924    }
925
926    // If this is one of the legacy UID->UID mappings, use it.
927    uid_t euid = get_keystore_euid(uid);
928    if (euid != uid) {
929        encode_key_for_uid(filename, euid, keyName);
930        responseCode = keyStore->get(filename, keyBlob, type);
931        if (responseCode == NO_ERROR) {
932            return responseCode;
933        }
934    }
935
936    // They might be using a granted key.
937    encode_key(filename, keyName);
938    if (!keyStore->hasGrant(filename, uid)) {
939        return responseCode;
940    }
941
942    // It is a granted key. Try to load it.
943    return keyStore->get(filename, keyBlob, type);
944}
945
946namespace android {
947class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
948public:
949    KeyStoreProxy(KeyStore* keyStore)
950        : mKeyStore(keyStore)
951    {
952    }
953
954    void binderDied(const wp<IBinder>&) {
955        ALOGE("binder death detected");
956    }
957
958    int32_t test() {
959        uid_t callingUid = IPCThreadState::self()->getCallingUid();
960        if (!has_permission(callingUid, P_TEST)) {
961            ALOGW("permission denied for %d: test", callingUid);
962            return ::PERMISSION_DENIED;
963        }
964
965        return mKeyStore->getState();
966    }
967
968    int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
969        uid_t callingUid = IPCThreadState::self()->getCallingUid();
970        if (!has_permission(callingUid, P_GET)) {
971            ALOGW("permission denied for %d: get", callingUid);
972            return ::PERMISSION_DENIED;
973        }
974
975        State state = mKeyStore->getState();
976        if (!isKeystoreUnlocked(state)) {
977            ALOGD("calling get in state: %d", state);
978            return state;
979        }
980
981        String8 name8(name);
982        char filename[NAME_MAX];
983        Blob keyBlob;
984
985        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
986                TYPE_GENERIC);
987        if (responseCode != ::NO_ERROR) {
988            ALOGW("Could not read %s", filename);
989            *item = NULL;
990            *itemLength = 0;
991            return responseCode;
992        }
993
994        *item = (uint8_t*) malloc(keyBlob.getLength());
995        memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
996        *itemLength = keyBlob.getLength();
997
998        return ::NO_ERROR;
999    }
1000
1001    int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
1002        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1003        if (!has_permission(callingUid, P_INSERT)) {
1004            ALOGW("permission denied for %d: insert", callingUid);
1005            return ::PERMISSION_DENIED;
1006        }
1007
1008        if (targetUid == -1) {
1009            targetUid = callingUid;
1010        } else if (!is_granted_to(callingUid, targetUid)) {
1011            return ::PERMISSION_DENIED;
1012        }
1013
1014        State state = mKeyStore->getState();
1015        if (!isKeystoreUnlocked(state)) {
1016            ALOGD("calling insert in state: %d", state);
1017            return state;
1018        }
1019
1020        String8 name8(name);
1021        char filename[NAME_MAX];
1022
1023        encode_key_for_uid(filename, targetUid, name8);
1024
1025        Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1026        return mKeyStore->put(filename, &keyBlob);
1027    }
1028
1029    int32_t del(const String16& name, int targetUid) {
1030        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1031        if (!has_permission(callingUid, P_DELETE)) {
1032            ALOGW("permission denied for %d: del", callingUid);
1033            return ::PERMISSION_DENIED;
1034        }
1035
1036        if (targetUid == -1) {
1037            targetUid = callingUid;
1038        } else if (!is_granted_to(callingUid, targetUid)) {
1039            return ::PERMISSION_DENIED;
1040        }
1041
1042        String8 name8(name);
1043        char filename[NAME_MAX];
1044
1045        encode_key_for_uid(filename, targetUid, name8);
1046
1047        Blob keyBlob;
1048        ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1049        if (responseCode != ::NO_ERROR) {
1050            return responseCode;
1051        }
1052        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1053    }
1054
1055    int32_t exist(const String16& name, int targetUid) {
1056        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1057        if (!has_permission(callingUid, P_EXIST)) {
1058            ALOGW("permission denied for %d: exist", callingUid);
1059            return ::PERMISSION_DENIED;
1060        }
1061
1062        if (targetUid == -1) {
1063            targetUid = callingUid;
1064        } else if (!is_granted_to(callingUid, targetUid)) {
1065            return ::PERMISSION_DENIED;
1066        }
1067
1068        String8 name8(name);
1069        char filename[NAME_MAX];
1070
1071        encode_key_for_uid(filename, targetUid, name8);
1072
1073        if (access(filename, R_OK) == -1) {
1074            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1075        }
1076        return ::NO_ERROR;
1077    }
1078
1079    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
1080        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1081        if (!has_permission(callingUid, P_SAW)) {
1082            ALOGW("permission denied for %d: saw", callingUid);
1083            return ::PERMISSION_DENIED;
1084        }
1085
1086        if (targetUid == -1) {
1087            targetUid = callingUid;
1088        } else if (!is_granted_to(callingUid, targetUid)) {
1089            return ::PERMISSION_DENIED;
1090        }
1091
1092        DIR* dir = opendir(".");
1093        if (!dir) {
1094            return ::SYSTEM_ERROR;
1095        }
1096
1097        const String8 prefix8(prefix);
1098        char filename[NAME_MAX];
1099
1100        int n = encode_key_for_uid(filename, targetUid, prefix8);
1101
1102        struct dirent* file;
1103        while ((file = readdir(dir)) != NULL) {
1104            if (!strncmp(filename, file->d_name, n)) {
1105                const char* p = &file->d_name[n];
1106                size_t plen = strlen(p);
1107
1108                size_t extra = decode_key_length(p, plen);
1109                char *match = (char*) malloc(extra + 1);
1110                if (match != NULL) {
1111                    decode_key(match, p, plen);
1112                    matches->push(String16(match, extra));
1113                    free(match);
1114                } else {
1115                    ALOGW("could not allocate match of size %zd", extra);
1116                }
1117            }
1118        }
1119        closedir(dir);
1120
1121        return ::NO_ERROR;
1122    }
1123
1124    int32_t reset() {
1125        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1126        if (!has_permission(callingUid, P_RESET)) {
1127            ALOGW("permission denied for %d: reset", callingUid);
1128            return ::PERMISSION_DENIED;
1129        }
1130
1131        ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1132
1133        const keymaster_device_t* device = mKeyStore->getDevice();
1134        if (device == NULL) {
1135            ALOGE("No keymaster device!");
1136            return ::SYSTEM_ERROR;
1137        }
1138
1139        if (device->delete_all == NULL) {
1140            ALOGV("keymaster device doesn't implement delete_all");
1141            return rc;
1142        }
1143
1144        if (device->delete_all(device)) {
1145            ALOGE("Problem calling keymaster's delete_all");
1146            return ::SYSTEM_ERROR;
1147        }
1148
1149        return rc;
1150    }
1151
1152    /*
1153     * Here is the history. To improve the security, the parameters to generate the
1154     * master key has been changed. To make a seamless transition, we update the
1155     * file using the same password when the user unlock it for the first time. If
1156     * any thing goes wrong during the transition, the new file will not overwrite
1157     * the old one. This avoids permanent damages of the existing data.
1158     */
1159    int32_t password(const String16& password) {
1160        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1161        if (!has_permission(callingUid, P_PASSWORD)) {
1162            ALOGW("permission denied for %d: password", callingUid);
1163            return ::PERMISSION_DENIED;
1164        }
1165
1166        const String8 password8(password);
1167
1168        switch (mKeyStore->getState()) {
1169            case ::STATE_UNINITIALIZED: {
1170                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1171                return mKeyStore->initialize(password8);
1172            }
1173            case ::STATE_NO_ERROR: {
1174                // rewrite master key with new password.
1175                return mKeyStore->writeMasterKey(password8);
1176            }
1177            case ::STATE_LOCKED: {
1178                // read master key, decrypt with password, initialize mMasterKey*.
1179                return mKeyStore->readMasterKey(password8);
1180            }
1181        }
1182        return ::SYSTEM_ERROR;
1183    }
1184
1185    int32_t lock() {
1186        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1187        if (!has_permission(callingUid, P_LOCK)) {
1188            ALOGW("permission denied for %d: lock", callingUid);
1189            return ::PERMISSION_DENIED;
1190        }
1191
1192        State state = mKeyStore->getState();
1193        if (state != ::STATE_NO_ERROR) {
1194            ALOGD("calling lock in state: %d", state);
1195            return state;
1196        }
1197
1198        mKeyStore->lock();
1199        return ::NO_ERROR;
1200    }
1201
1202    int32_t unlock(const String16& pw) {
1203        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1204        if (!has_permission(callingUid, P_UNLOCK)) {
1205            ALOGW("permission denied for %d: unlock", callingUid);
1206            return ::PERMISSION_DENIED;
1207        }
1208
1209        State state = mKeyStore->getState();
1210        if (state != ::STATE_LOCKED) {
1211            ALOGD("calling unlock when not locked");
1212            return state;
1213        }
1214
1215        const String8 password8(pw);
1216        return password(pw);
1217    }
1218
1219    int32_t zero() {
1220        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1221        if (!has_permission(callingUid, P_ZERO)) {
1222            ALOGW("permission denied for %d: zero", callingUid);
1223            return -1;
1224        }
1225
1226        return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
1227    }
1228
1229    int32_t generate(const String16& name, int targetUid) {
1230        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1231        if (!has_permission(callingUid, P_INSERT)) {
1232            ALOGW("permission denied for %d: generate", callingUid);
1233            return ::PERMISSION_DENIED;
1234        }
1235
1236        if (targetUid == -1) {
1237            targetUid = callingUid;
1238        } else if (!is_granted_to(callingUid, targetUid)) {
1239            return ::PERMISSION_DENIED;
1240        }
1241
1242        State state = mKeyStore->getState();
1243        if (!isKeystoreUnlocked(state)) {
1244            ALOGD("calling generate in state: %d", state);
1245            return state;
1246        }
1247
1248        String8 name8(name);
1249        char filename[NAME_MAX];
1250
1251        uint8_t* data;
1252        size_t dataLength;
1253        int rc;
1254
1255        const keymaster_device_t* device = mKeyStore->getDevice();
1256        if (device == NULL) {
1257            return ::SYSTEM_ERROR;
1258        }
1259
1260        if (device->generate_keypair == NULL) {
1261            return ::SYSTEM_ERROR;
1262        }
1263
1264        keymaster_rsa_keygen_params_t rsa_params;
1265        rsa_params.modulus_size = 2048;
1266        rsa_params.public_exponent = 0x10001;
1267
1268        rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1269        if (rc) {
1270            return ::SYSTEM_ERROR;
1271        }
1272
1273        encode_key_for_uid(filename, targetUid, name8);
1274
1275        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1276        free(data);
1277
1278        return mKeyStore->put(filename, &keyBlob);
1279    }
1280
1281    int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
1282        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1283        if (!has_permission(callingUid, P_INSERT)) {
1284            ALOGW("permission denied for %d: import", callingUid);
1285            return ::PERMISSION_DENIED;
1286        }
1287
1288        if (targetUid == -1) {
1289            targetUid = callingUid;
1290        } else if (!is_granted_to(callingUid, targetUid)) {
1291            return ::PERMISSION_DENIED;
1292        }
1293
1294        State state = mKeyStore->getState();
1295        if (!isKeystoreUnlocked(state)) {
1296            ALOGD("calling import in state: %d", state);
1297            return state;
1298        }
1299
1300        String8 name8(name);
1301        char filename[NAME_MAX];
1302
1303        encode_key_for_uid(filename, targetUid, name8);
1304
1305        return mKeyStore->importKey(data, length, filename);
1306    }
1307
1308    int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1309            size_t* outLength) {
1310        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1311        if (!has_permission(callingUid, P_SIGN)) {
1312            ALOGW("permission denied for %d: saw", callingUid);
1313            return ::PERMISSION_DENIED;
1314        }
1315
1316        State state = mKeyStore->getState();
1317        if (!isKeystoreUnlocked(state)) {
1318            ALOGD("calling sign in state: %d", state);
1319            return state;
1320        }
1321
1322        Blob keyBlob;
1323        String8 name8(name);
1324
1325        ALOGV("sign %s from uid %d", name8.string(), callingUid);
1326        int rc;
1327
1328        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1329                ::TYPE_KEY_PAIR);
1330        if (responseCode != ::NO_ERROR) {
1331            return responseCode;
1332        }
1333
1334        const keymaster_device_t* device = mKeyStore->getDevice();
1335        if (device == NULL) {
1336            ALOGE("no keymaster device; cannot sign");
1337            return ::SYSTEM_ERROR;
1338        }
1339
1340        if (device->sign_data == NULL) {
1341            ALOGE("device doesn't implement signing");
1342            return ::SYSTEM_ERROR;
1343        }
1344
1345        keymaster_rsa_sign_params_t params;
1346        params.digest_type = DIGEST_NONE;
1347        params.padding_type = PADDING_NONE;
1348
1349        rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1350                data, length, out, outLength);
1351        if (rc) {
1352            ALOGW("device couldn't sign data");
1353            return ::SYSTEM_ERROR;
1354        }
1355
1356        return ::NO_ERROR;
1357    }
1358
1359    int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1360            const uint8_t* signature, size_t signatureLength) {
1361        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1362        if (!has_permission(callingUid, P_VERIFY)) {
1363            ALOGW("permission denied for %d: verify", callingUid);
1364            return ::PERMISSION_DENIED;
1365        }
1366
1367        State state = mKeyStore->getState();
1368        if (!isKeystoreUnlocked(state)) {
1369            ALOGD("calling verify in state: %d", state);
1370            return state;
1371        }
1372
1373        Blob keyBlob;
1374        String8 name8(name);
1375        int rc;
1376
1377        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1378                TYPE_KEY_PAIR);
1379        if (responseCode != ::NO_ERROR) {
1380            return responseCode;
1381        }
1382
1383        const keymaster_device_t* device = mKeyStore->getDevice();
1384        if (device == NULL) {
1385            return ::SYSTEM_ERROR;
1386        }
1387
1388        if (device->verify_data == NULL) {
1389            return ::SYSTEM_ERROR;
1390        }
1391
1392        keymaster_rsa_sign_params_t params;
1393        params.digest_type = DIGEST_NONE;
1394        params.padding_type = PADDING_NONE;
1395
1396        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1397                data, dataLength, signature, signatureLength);
1398        if (rc) {
1399            return ::SYSTEM_ERROR;
1400        } else {
1401            return ::NO_ERROR;
1402        }
1403    }
1404
1405    /*
1406     * TODO: The abstraction between things stored in hardware and regular blobs
1407     * of data stored on the filesystem should be moved down to keystore itself.
1408     * Unfortunately the Java code that calls this has naming conventions that it
1409     * knows about. Ideally keystore shouldn't be used to store random blobs of
1410     * data.
1411     *
1412     * Until that happens, it's necessary to have a separate "get_pubkey" and
1413     * "del_key" since the Java code doesn't really communicate what it's
1414     * intentions are.
1415     */
1416    int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
1417        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1418        if (!has_permission(callingUid, P_GET)) {
1419            ALOGW("permission denied for %d: get_pubkey", callingUid);
1420            return ::PERMISSION_DENIED;
1421        }
1422
1423        State state = mKeyStore->getState();
1424        if (!isKeystoreUnlocked(state)) {
1425            ALOGD("calling get_pubkey in state: %d", state);
1426            return state;
1427        }
1428
1429        Blob keyBlob;
1430        String8 name8(name);
1431
1432        ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
1433
1434        ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1435                TYPE_KEY_PAIR);
1436        if (responseCode != ::NO_ERROR) {
1437            return responseCode;
1438        }
1439
1440        const keymaster_device_t* device = mKeyStore->getDevice();
1441        if (device == NULL) {
1442            return ::SYSTEM_ERROR;
1443        }
1444
1445        if (device->get_keypair_public == NULL) {
1446            ALOGE("device has no get_keypair_public implementation!");
1447            return ::SYSTEM_ERROR;
1448        }
1449
1450        int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1451                pubkeyLength);
1452        if (rc) {
1453            return ::SYSTEM_ERROR;
1454        }
1455
1456        return ::NO_ERROR;
1457    }
1458
1459    int32_t del_key(const String16& name, int targetUid) {
1460        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1461        if (!has_permission(callingUid, P_DELETE)) {
1462            ALOGW("permission denied for %d: del_key", callingUid);
1463            return ::PERMISSION_DENIED;
1464        }
1465
1466        if (targetUid == -1) {
1467            targetUid = callingUid;
1468        } else if (!is_granted_to(callingUid, targetUid)) {
1469            return ::PERMISSION_DENIED;
1470        }
1471
1472        String8 name8(name);
1473        char filename[NAME_MAX];
1474
1475        encode_key_for_uid(filename, targetUid, name8);
1476
1477        Blob keyBlob;
1478        ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1479        if (responseCode != ::NO_ERROR) {
1480            return responseCode;
1481        }
1482
1483        ResponseCode rc = ::NO_ERROR;
1484
1485        const keymaster_device_t* device = mKeyStore->getDevice();
1486        if (device == NULL) {
1487            rc = ::SYSTEM_ERROR;
1488        } else {
1489            // A device doesn't have to implement delete_keypair.
1490            if (device->delete_keypair != NULL) {
1491                if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1492                    rc = ::SYSTEM_ERROR;
1493                }
1494            }
1495        }
1496
1497        if (rc != ::NO_ERROR) {
1498            return rc;
1499        }
1500
1501        return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1502    }
1503
1504    int32_t grant(const String16& name, int32_t granteeUid) {
1505        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1506        if (!has_permission(callingUid, P_GRANT)) {
1507            ALOGW("permission denied for %d: grant", callingUid);
1508            return ::PERMISSION_DENIED;
1509        }
1510
1511        State state = mKeyStore->getState();
1512        if (!isKeystoreUnlocked(state)) {
1513            ALOGD("calling grant in state: %d", state);
1514            return state;
1515        }
1516
1517        String8 name8(name);
1518        char filename[NAME_MAX];
1519
1520        encode_key_for_uid(filename, callingUid, name8);
1521
1522        if (access(filename, R_OK) == -1) {
1523            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1524        }
1525
1526        mKeyStore->addGrant(filename, granteeUid);
1527        return ::NO_ERROR;
1528    }
1529
1530    int32_t ungrant(const String16& name, int32_t granteeUid) {
1531        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1532        if (!has_permission(callingUid, P_GRANT)) {
1533            ALOGW("permission denied for %d: ungrant", callingUid);
1534            return ::PERMISSION_DENIED;
1535        }
1536
1537        State state = mKeyStore->getState();
1538        if (!isKeystoreUnlocked(state)) {
1539            ALOGD("calling ungrant in state: %d", state);
1540            return state;
1541        }
1542
1543        String8 name8(name);
1544        char filename[NAME_MAX];
1545
1546        encode_key_for_uid(filename, callingUid, name8);
1547
1548        if (access(filename, R_OK) == -1) {
1549            return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1550        }
1551
1552        return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1553    }
1554
1555    int64_t getmtime(const String16& name) {
1556        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1557        if (!has_permission(callingUid, P_GET)) {
1558            ALOGW("permission denied for %d: getmtime", callingUid);
1559            return -1L;
1560        }
1561
1562        String8 name8(name);
1563        char filename[NAME_MAX];
1564
1565        encode_key_for_uid(filename, callingUid, name8);
1566
1567        if (access(filename, R_OK) == -1) {
1568            ALOGW("could not access %s for getmtime", filename);
1569            return -1L;
1570        }
1571
1572        int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
1573        if (fd < 0) {
1574            ALOGW("could not open %s for getmtime", filename);
1575            return -1L;
1576        }
1577
1578        struct stat s;
1579        int ret = fstat(fd, &s);
1580        close(fd);
1581        if (ret == -1) {
1582            ALOGW("could not stat %s for getmtime", filename);
1583            return -1L;
1584        }
1585
1586        return static_cast<int64_t>(s.st_mtime);
1587    }
1588
1589    int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1590            int32_t destUid) {
1591        uid_t callingUid = IPCThreadState::self()->getCallingUid();
1592        if (!has_permission(callingUid, P_DUPLICATE)) {
1593            ALOGW("permission denied for %d: duplicate", callingUid);
1594            return -1L;
1595        }
1596
1597        State state = mKeyStore->getState();
1598        if (!isKeystoreUnlocked(state)) {
1599            ALOGD("calling duplicate in state: %d", state);
1600            return state;
1601        }
1602
1603        if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1604            srcUid = callingUid;
1605        } else if (!is_granted_to(callingUid, srcUid)) {
1606            ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
1607            return ::PERMISSION_DENIED;
1608        }
1609
1610        if (destUid == -1) {
1611            destUid = callingUid;
1612        }
1613
1614        if (srcUid != destUid) {
1615            if (static_cast<uid_t>(srcUid) != callingUid) {
1616                ALOGD("can only duplicate from caller to other or to same uid: "
1617                      "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1618                return ::PERMISSION_DENIED;
1619            }
1620
1621            if (!is_granted_to(callingUid, destUid)) {
1622                ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1623                return ::PERMISSION_DENIED;
1624            }
1625        }
1626
1627        String8 source8(srcKey);
1628        char source[NAME_MAX];
1629
1630        encode_key_for_uid(source, srcUid, source8);
1631
1632        String8 target8(destKey);
1633        char target[NAME_MAX];
1634
1635        encode_key_for_uid(target, destUid, target8);
1636
1637        if (access(target, W_OK) != -1 || errno != ENOENT) {
1638            ALOGD("destination already exists: %s", target);
1639            return ::SYSTEM_ERROR;
1640        }
1641
1642        Blob keyBlob;
1643        ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
1644        if (responseCode != ::NO_ERROR) {
1645            return responseCode;
1646        }
1647
1648        return mKeyStore->put(target, &keyBlob);
1649    }
1650
1651private:
1652    inline bool isKeystoreUnlocked(State state) {
1653        switch (state) {
1654        case ::STATE_NO_ERROR:
1655            return true;
1656        case ::STATE_UNINITIALIZED:
1657        case ::STATE_LOCKED:
1658            return false;
1659        }
1660        return false;
1661    }
1662
1663    ::KeyStore* mKeyStore;
1664};
1665
1666}; // namespace android
1667
1668int main(int argc, char* argv[]) {
1669    if (argc < 2) {
1670        ALOGE("A directory must be specified!");
1671        return 1;
1672    }
1673    if (chdir(argv[1]) == -1) {
1674        ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1675        return 1;
1676    }
1677
1678    Entropy entropy;
1679    if (!entropy.open()) {
1680        return 1;
1681    }
1682
1683    keymaster_device_t* dev;
1684    if (keymaster_device_initialize(&dev)) {
1685        ALOGE("keystore keymaster could not be initialized; exiting");
1686        return 1;
1687    }
1688
1689    KeyStore keyStore(&entropy, dev);
1690    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1691    android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1692    android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1693    if (ret != android::OK) {
1694        ALOGE("Couldn't register binder service!");
1695        return -1;
1696    }
1697
1698    /*
1699     * We're the only thread in existence, so we're just going to process
1700     * Binder transaction as a single-threaded program.
1701     */
1702    android::IPCThreadState::self()->joinThreadPool();
1703
1704    keymaster_device_release(dev);
1705    return 1;
1706}
1707