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