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