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