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