blob: f20f4ba2a854ce9b57495e2bbc1539914ba0f3b5 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 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#include "key_store_service.h"
18
19#include <fcntl.h>
20#include <sys/stat.h>
21
22#include <sstream>
23
24#include <binder/IPCThreadState.h>
25
26#include <private/android_filesystem_config.h>
27
28#include <hardware/keymaster_defs.h>
29
30#include "defaults.h"
31#include "keystore_utils.h"
32
33namespace android {
34
35const size_t MAX_OPERATIONS = 15;
36
37struct BIGNUM_Delete {
38 void operator()(BIGNUM* p) const { BN_free(p); }
39};
40typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
41
42void KeyStoreService::binderDied(const wp<IBinder>& who) {
43 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
44 for (auto token : operations) {
45 abort(token);
46 }
47}
48
49int32_t KeyStoreService::getState(int32_t userId) {
50 if (!checkBinderPermission(P_GET_STATE)) {
51 return ::PERMISSION_DENIED;
52 }
53
54 return mKeyStore->getState(userId);
55}
56
57int32_t KeyStoreService::get(const String16& name, int32_t uid, uint8_t** item,
58 size_t* itemLength) {
59 uid_t targetUid = getEffectiveUid(uid);
60 if (!checkBinderPermission(P_GET, targetUid)) {
61 return ::PERMISSION_DENIED;
62 }
63
64 String8 name8(name);
65 Blob keyBlob;
66
67 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
68 if (responseCode != ::NO_ERROR) {
69 *item = NULL;
70 *itemLength = 0;
71 return responseCode;
72 }
73
74 *item = (uint8_t*)malloc(keyBlob.getLength());
75 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
76 *itemLength = keyBlob.getLength();
77
78 return ::NO_ERROR;
79}
80
81int32_t KeyStoreService::insert(const String16& name, const uint8_t* item, size_t itemLength,
82 int targetUid, int32_t flags) {
83 targetUid = getEffectiveUid(targetUid);
84 int32_t result =
85 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
86 if (result != ::NO_ERROR) {
87 return result;
88 }
89
90 String8 name8(name);
91 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
92
93 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
94 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
95
96 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
97}
98
99int32_t KeyStoreService::del(const String16& name, int targetUid) {
100 targetUid = getEffectiveUid(targetUid);
101 if (!checkBinderPermission(P_DELETE, targetUid)) {
102 return ::PERMISSION_DENIED;
103 }
104 String8 name8(name);
105 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
106 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
107}
108
109int32_t KeyStoreService::exist(const String16& name, int targetUid) {
110 targetUid = getEffectiveUid(targetUid);
111 if (!checkBinderPermission(P_EXIST, targetUid)) {
112 return ::PERMISSION_DENIED;
113 }
114
115 String8 name8(name);
116 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
117
118 if (access(filename.string(), R_OK) == -1) {
119 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
120 }
121 return ::NO_ERROR;
122}
123
124int32_t KeyStoreService::list(const String16& prefix, int targetUid, Vector<String16>* matches) {
125 targetUid = getEffectiveUid(targetUid);
126 if (!checkBinderPermission(P_LIST, targetUid)) {
127 return ::PERMISSION_DENIED;
128 }
129 const String8 prefix8(prefix);
130 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
131
132 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
133 return ::SYSTEM_ERROR;
134 }
135 return ::NO_ERROR;
136}
137
138int32_t KeyStoreService::reset() {
139 if (!checkBinderPermission(P_RESET)) {
140 return ::PERMISSION_DENIED;
141 }
142
143 uid_t callingUid = IPCThreadState::self()->getCallingUid();
144 mKeyStore->resetUser(get_user_id(callingUid), false);
145 return ::NO_ERROR;
146}
147
148int32_t KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password) {
149 if (!checkBinderPermission(P_PASSWORD)) {
150 return ::PERMISSION_DENIED;
151 }
152
153 const String8 password8(password);
154 // Flush the auth token table to prevent stale tokens from sticking
155 // around.
156 mAuthTokenTable.Clear();
157
158 if (password.size() == 0) {
159 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
160 mKeyStore->resetUser(userId, true);
161 return ::NO_ERROR;
162 } else {
163 switch (mKeyStore->getState(userId)) {
164 case ::STATE_UNINITIALIZED: {
165 // generate master key, encrypt with password, write to file,
166 // initialize mMasterKey*.
167 return mKeyStore->initializeUser(password8, userId);
168 }
169 case ::STATE_NO_ERROR: {
170 // rewrite master key with new password.
171 return mKeyStore->writeMasterKey(password8, userId);
172 }
173 case ::STATE_LOCKED: {
174 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
175 mKeyStore->resetUser(userId, true);
176 return mKeyStore->initializeUser(password8, userId);
177 }
178 }
179 return ::SYSTEM_ERROR;
180 }
181}
182
183int32_t KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
184 if (!checkBinderPermission(P_USER_CHANGED)) {
185 return ::PERMISSION_DENIED;
186 }
187
188 // Sanity check that the new user has an empty keystore.
189 if (!mKeyStore->isEmpty(userId)) {
190 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
191 }
192 // Unconditionally clear the keystore, just to be safe.
193 mKeyStore->resetUser(userId, false);
194 if (parentId != -1) {
195 // This profile must share the same master key password as the parent profile. Because the
196 // password of the parent profile is not known here, the best we can do is copy the parent's
197 // master key and master key file. This makes this profile use the same master key as the
198 // parent profile, forever.
199 return mKeyStore->copyMasterKey(parentId, userId);
200 } else {
201 return ::NO_ERROR;
202 }
203}
204
205int32_t KeyStoreService::onUserRemoved(int32_t userId) {
206 if (!checkBinderPermission(P_USER_CHANGED)) {
207 return ::PERMISSION_DENIED;
208 }
209
210 mKeyStore->resetUser(userId, false);
211 return ::NO_ERROR;
212}
213
214int32_t KeyStoreService::lock(int32_t userId) {
215 if (!checkBinderPermission(P_LOCK)) {
216 return ::PERMISSION_DENIED;
217 }
218
219 State state = mKeyStore->getState(userId);
220 if (state != ::STATE_NO_ERROR) {
221 ALOGD("calling lock in state: %d", state);
222 return state;
223 }
224
225 mKeyStore->lock(userId);
226 return ::NO_ERROR;
227}
228
229int32_t KeyStoreService::unlock(int32_t userId, const String16& pw) {
230 if (!checkBinderPermission(P_UNLOCK)) {
231 return ::PERMISSION_DENIED;
232 }
233
234 State state = mKeyStore->getState(userId);
235 if (state != ::STATE_LOCKED) {
236 switch (state) {
237 case ::STATE_NO_ERROR:
238 ALOGI("calling unlock when already unlocked, ignoring.");
239 break;
240 case ::STATE_UNINITIALIZED:
241 ALOGE("unlock called on uninitialized keystore.");
242 break;
243 default:
244 ALOGE("unlock called on keystore in unknown state: %d", state);
245 break;
246 }
247 return state;
248 }
249
250 const String8 password8(pw);
251 // read master key, decrypt with password, initialize mMasterKey*.
252 return mKeyStore->readMasterKey(password8, userId);
253}
254
255bool KeyStoreService::isEmpty(int32_t userId) {
256 if (!checkBinderPermission(P_IS_EMPTY)) {
257 return false;
258 }
259
260 return mKeyStore->isEmpty(userId);
261}
262
263int32_t KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
264 int32_t keySize, int32_t flags, Vector<sp<KeystoreArg>>* args) {
265 targetUid = getEffectiveUid(targetUid);
266 int32_t result =
267 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
268 if (result != ::NO_ERROR) {
269 return result;
270 }
271
272 KeymasterArguments params;
273 add_legacy_key_authorizations(keyType, &params.params);
274
275 switch (keyType) {
276 case EVP_PKEY_EC: {
277 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
278 if (keySize == -1) {
279 keySize = EC_DEFAULT_KEY_SIZE;
280 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
281 ALOGI("invalid key size %d", keySize);
282 return ::SYSTEM_ERROR;
283 }
284 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
285 break;
286 }
287 case EVP_PKEY_RSA: {
288 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
289 if (keySize == -1) {
290 keySize = RSA_DEFAULT_KEY_SIZE;
291 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
292 ALOGI("invalid key size %d", keySize);
293 return ::SYSTEM_ERROR;
294 }
295 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
296 unsigned long exponent = RSA_DEFAULT_EXPONENT;
297 if (args->size() > 1) {
298 ALOGI("invalid number of arguments: %zu", args->size());
299 return ::SYSTEM_ERROR;
300 } else if (args->size() == 1) {
301 sp<KeystoreArg> expArg = args->itemAt(0);
302 if (expArg != NULL) {
303 Unique_BIGNUM pubExpBn(BN_bin2bn(
304 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
305 if (pubExpBn.get() == NULL) {
306 ALOGI("Could not convert public exponent to BN");
307 return ::SYSTEM_ERROR;
308 }
309 exponent = BN_get_word(pubExpBn.get());
310 if (exponent == 0xFFFFFFFFL) {
311 ALOGW("cannot represent public exponent as a long value");
312 return ::SYSTEM_ERROR;
313 }
314 } else {
315 ALOGW("public exponent not read");
316 return ::SYSTEM_ERROR;
317 }
318 }
319 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, exponent));
320 break;
321 }
322 default: {
323 ALOGW("Unsupported key type %d", keyType);
324 return ::SYSTEM_ERROR;
325 }
326 }
327
328 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
329 /*outCharacteristics*/ NULL);
330 if (rc != ::NO_ERROR) {
331 ALOGW("generate failed: %d", rc);
332 }
333 return translateResultToLegacyResult(rc);
334}
335
336int32_t KeyStoreService::import(const String16& name, const uint8_t* data, size_t length,
337 int targetUid, int32_t flags) {
338 const uint8_t* ptr = data;
339
340 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
341 if (!pkcs8.get()) {
342 return ::SYSTEM_ERROR;
343 }
344 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
345 if (!pkey.get()) {
346 return ::SYSTEM_ERROR;
347 }
348 int type = EVP_PKEY_type(pkey->type);
349 KeymasterArguments params;
350 add_legacy_key_authorizations(type, &params.params);
351 switch (type) {
352 case EVP_PKEY_RSA:
353 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
354 break;
355 case EVP_PKEY_EC:
356 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
357 break;
358 default:
359 ALOGW("Unsupported key type %d", type);
360 return ::SYSTEM_ERROR;
361 }
362 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
363 /*outCharacteristics*/ NULL);
364 if (rc != ::NO_ERROR) {
365 ALOGW("importKey failed: %d", rc);
366 }
367 return translateResultToLegacyResult(rc);
368}
369
370int32_t KeyStoreService::sign(const String16& name, const uint8_t* data, size_t length,
371 uint8_t** out, size_t* outLength) {
372 if (!checkBinderPermission(P_SIGN)) {
373 return ::PERMISSION_DENIED;
374 }
375 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
376}
377
378int32_t KeyStoreService::verify(const String16& name, const uint8_t* data, size_t dataLength,
379 const uint8_t* signature, size_t signatureLength) {
380 if (!checkBinderPermission(P_VERIFY)) {
381 return ::PERMISSION_DENIED;
382 }
383 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
384 KM_PURPOSE_VERIFY);
385}
386
387/*
388 * TODO: The abstraction between things stored in hardware and regular blobs
389 * of data stored on the filesystem should be moved down to keystore itself.
390 * Unfortunately the Java code that calls this has naming conventions that it
391 * knows about. Ideally keystore shouldn't be used to store random blobs of
392 * data.
393 *
394 * Until that happens, it's necessary to have a separate "get_pubkey" and
395 * "del_key" since the Java code doesn't really communicate what it's
396 * intentions are.
397 */
398int32_t KeyStoreService::get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
399 ExportResult result;
400 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, UID_SELF, &result);
401 if (result.resultCode != ::NO_ERROR) {
402 ALOGW("export failed: %d", result.resultCode);
403 return translateResultToLegacyResult(result.resultCode);
404 }
405
406 *pubkey = result.exportData.release();
407 *pubkeyLength = result.dataLength;
408 return ::NO_ERROR;
409}
410
411int32_t KeyStoreService::grant(const String16& name, int32_t granteeUid) {
412 uid_t callingUid = IPCThreadState::self()->getCallingUid();
413 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
414 if (result != ::NO_ERROR) {
415 return result;
416 }
417
418 String8 name8(name);
419 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
420
421 if (access(filename.string(), R_OK) == -1) {
422 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
423 }
424
425 mKeyStore->addGrant(filename.string(), granteeUid);
426 return ::NO_ERROR;
427}
428
429int32_t KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
430 uid_t callingUid = IPCThreadState::self()->getCallingUid();
431 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
432 if (result != ::NO_ERROR) {
433 return result;
434 }
435
436 String8 name8(name);
437 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
438
439 if (access(filename.string(), R_OK) == -1) {
440 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
441 }
442
443 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
444}
445
446int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
447 uid_t targetUid = getEffectiveUid(uid);
448 if (!checkBinderPermission(P_GET, targetUid)) {
449 ALOGW("permission denied for %d: getmtime", targetUid);
450 return -1L;
451 }
452
453 String8 name8(name);
454 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
455
456 if (access(filename.string(), R_OK) == -1) {
457 ALOGW("could not access %s for getmtime", filename.string());
458 return -1L;
459 }
460
461 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
462 if (fd < 0) {
463 ALOGW("could not open %s for getmtime", filename.string());
464 return -1L;
465 }
466
467 struct stat s;
468 int ret = fstat(fd, &s);
469 close(fd);
470 if (ret == -1) {
471 ALOGW("could not stat %s for getmtime", filename.string());
472 return -1L;
473 }
474
475 return static_cast<int64_t>(s.st_mtime);
476}
477
478int32_t KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
479 int32_t destUid) {
480 uid_t callingUid = IPCThreadState::self()->getCallingUid();
481 pid_t spid = IPCThreadState::self()->getCallingPid();
482 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
483 ALOGW("permission denied for %d: duplicate", callingUid);
484 return -1L;
485 }
486
487 State state = mKeyStore->getState(get_user_id(callingUid));
488 if (!isKeystoreUnlocked(state)) {
489 ALOGD("calling duplicate in state: %d", state);
490 return state;
491 }
492
493 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
494 srcUid = callingUid;
495 } else if (!is_granted_to(callingUid, srcUid)) {
496 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
497 return ::PERMISSION_DENIED;
498 }
499
500 if (destUid == -1) {
501 destUid = callingUid;
502 }
503
504 if (srcUid != destUid) {
505 if (static_cast<uid_t>(srcUid) != callingUid) {
506 ALOGD("can only duplicate from caller to other or to same uid: "
507 "calling=%d, srcUid=%d, destUid=%d",
508 callingUid, srcUid, destUid);
509 return ::PERMISSION_DENIED;
510 }
511
512 if (!is_granted_to(callingUid, destUid)) {
513 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
514 return ::PERMISSION_DENIED;
515 }
516 }
517
518 String8 source8(srcKey);
519 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
520
521 String8 target8(destKey);
522 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
523
524 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
525 ALOGD("destination already exists: %s", targetFile.string());
526 return ::SYSTEM_ERROR;
527 }
528
529 Blob keyBlob;
530 ResponseCode responseCode =
531 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
532 if (responseCode != ::NO_ERROR) {
533 return responseCode;
534 }
535
536 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
537}
538
539int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
540 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
541}
542
543int32_t KeyStoreService::clear_uid(int64_t targetUid64) {
544 uid_t targetUid = getEffectiveUid(targetUid64);
545 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
546 return ::PERMISSION_DENIED;
547 }
548
549 String8 prefix = String8::format("%u_", targetUid);
550 Vector<String16> aliases;
551 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
552 return ::SYSTEM_ERROR;
553 }
554
555 for (uint32_t i = 0; i < aliases.size(); i++) {
556 String8 name8(aliases[i]);
557 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
558 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
559 }
560 return ::NO_ERROR;
561}
562
563int32_t KeyStoreService::addRngEntropy(const uint8_t* data, size_t dataLength) {
564 const keymaster1_device_t* device = mKeyStore->getDevice();
565 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
566 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
567 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
568 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
569 device->add_rng_entropy != NULL) {
570 devResult = device->add_rng_entropy(device, data, dataLength);
571 }
572 if (fallback->add_rng_entropy) {
573 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
574 }
575 if (devResult) {
576 return devResult;
577 }
578 if (fallbackResult) {
579 return fallbackResult;
580 }
581 return ::NO_ERROR;
582}
583
584int32_t KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
585 const uint8_t* entropy, size_t entropyLength, int uid,
586 int flags, KeyCharacteristics* outCharacteristics) {
587 uid = getEffectiveUid(uid);
588 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
589 if (rc != ::NO_ERROR) {
590 return rc;
591 }
592
593 rc = KM_ERROR_UNIMPLEMENTED;
594 bool isFallback = false;
595 keymaster_key_blob_t blob;
596 keymaster_key_characteristics_t* out = NULL;
597
598 const keymaster1_device_t* device = mKeyStore->getDevice();
599 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
600 std::vector<keymaster_key_param_t> opParams(params.params);
601 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
602 if (device == NULL) {
603 return ::SYSTEM_ERROR;
604 }
605 // TODO: Seed from Linux RNG before this.
606 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
607 device->generate_key != NULL) {
608 if (!entropy) {
609 rc = KM_ERROR_OK;
610 } else if (device->add_rng_entropy) {
611 rc = device->add_rng_entropy(device, entropy, entropyLength);
612 } else {
613 rc = KM_ERROR_UNIMPLEMENTED;
614 }
615 if (rc == KM_ERROR_OK) {
616 rc = device->generate_key(device, &inParams, &blob, &out);
617 }
618 }
619 // If the HW device didn't support generate_key or generate_key failed
620 // fall back to the software implementation.
621 if (rc && fallback->generate_key != NULL) {
622 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
623 isFallback = true;
624 if (!entropy) {
625 rc = KM_ERROR_OK;
626 } else if (fallback->add_rng_entropy) {
627 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
628 } else {
629 rc = KM_ERROR_UNIMPLEMENTED;
630 }
631 if (rc == KM_ERROR_OK) {
632 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
633 }
634 }
635
636 if (out) {
637 if (outCharacteristics) {
638 outCharacteristics->characteristics = *out;
639 } else {
640 keymaster_free_characteristics(out);
641 }
642 free(out);
643 }
644
645 if (rc) {
646 return rc;
647 }
648
649 String8 name8(name);
650 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
651
652 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
653 keyBlob.setFallback(isFallback);
654 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
655
656 free(const_cast<uint8_t*>(blob.key_material));
657
658 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
659}
660
661int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
662 const keymaster_blob_t* clientId,
663 const keymaster_blob_t* appData, int32_t uid,
664 KeyCharacteristics* outCharacteristics) {
665 if (!outCharacteristics) {
666 return KM_ERROR_UNEXPECTED_NULL_POINTER;
667 }
668
669 uid_t targetUid = getEffectiveUid(uid);
670 uid_t callingUid = IPCThreadState::self()->getCallingUid();
671 if (!is_granted_to(callingUid, targetUid)) {
672 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
673 targetUid);
674 return ::PERMISSION_DENIED;
675 }
676
677 Blob keyBlob;
678 String8 name8(name);
679 int rc;
680
681 ResponseCode responseCode =
682 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
683 if (responseCode != ::NO_ERROR) {
684 return responseCode;
685 }
686 keymaster_key_blob_t key;
687 key.key_material_size = keyBlob.getLength();
688 key.key_material = keyBlob.getValue();
689 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
690 keymaster_key_characteristics_t* out = NULL;
691 if (!dev->get_key_characteristics) {
692 ALOGW("device does not implement get_key_characteristics");
693 return KM_ERROR_UNIMPLEMENTED;
694 }
695 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
696 if (out) {
697 outCharacteristics->characteristics = *out;
698 free(out);
699 }
700 return rc ? rc : ::NO_ERROR;
701}
702
703int32_t KeyStoreService::importKey(const String16& name, const KeymasterArguments& params,
704 keymaster_key_format_t format, const uint8_t* keyData,
705 size_t keyLength, int uid, int flags,
706 KeyCharacteristics* outCharacteristics) {
707 uid = getEffectiveUid(uid);
708 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
709 if (rc != ::NO_ERROR) {
710 return rc;
711 }
712
713 rc = KM_ERROR_UNIMPLEMENTED;
714 bool isFallback = false;
715 keymaster_key_blob_t blob;
716 keymaster_key_characteristics_t* out = NULL;
717
718 const keymaster1_device_t* device = mKeyStore->getDevice();
719 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
720 std::vector<keymaster_key_param_t> opParams(params.params);
721 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
722 const keymaster_blob_t input = {keyData, keyLength};
723 if (device == NULL) {
724 return ::SYSTEM_ERROR;
725 }
726 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
727 device->import_key != NULL) {
728 rc = device->import_key(device, &inParams, format, &input, &blob, &out);
729 }
730 if (rc && fallback->import_key != NULL) {
731 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
732 isFallback = true;
733 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
734 }
735 if (out) {
736 if (outCharacteristics) {
737 outCharacteristics->characteristics = *out;
738 } else {
739 keymaster_free_characteristics(out);
740 }
741 free(out);
742 }
743 if (rc) {
744 return rc;
745 }
746
747 String8 name8(name);
748 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
749
750 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
751 keyBlob.setFallback(isFallback);
752 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
753
754 free((void*)blob.key_material);
755
756 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
757}
758
759void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
760 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
761 int32_t uid, ExportResult* result) {
762
763 uid_t targetUid = getEffectiveUid(uid);
764 uid_t callingUid = IPCThreadState::self()->getCallingUid();
765 if (!is_granted_to(callingUid, targetUid)) {
766 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
767 result->resultCode = ::PERMISSION_DENIED;
768 return;
769 }
770
771 Blob keyBlob;
772 String8 name8(name);
773 int rc;
774
775 ResponseCode responseCode =
776 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
777 if (responseCode != ::NO_ERROR) {
778 result->resultCode = responseCode;
779 return;
780 }
781 keymaster_key_blob_t key;
782 key.key_material_size = keyBlob.getLength();
783 key.key_material = keyBlob.getValue();
784 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
785 if (!dev->export_key) {
786 result->resultCode = KM_ERROR_UNIMPLEMENTED;
787 return;
788 }
789 keymaster_blob_t output = {NULL, 0};
790 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
791 result->exportData.reset(const_cast<uint8_t*>(output.data));
792 result->dataLength = output.data_length;
793 result->resultCode = rc ? rc : ::NO_ERROR;
794}
795
796void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
797 keymaster_purpose_t purpose, bool pruneable,
798 const KeymasterArguments& params, const uint8_t* entropy,
799 size_t entropyLength, int32_t uid, OperationResult* result) {
800 uid_t callingUid = IPCThreadState::self()->getCallingUid();
801 uid_t targetUid = getEffectiveUid(uid);
802 if (!is_granted_to(callingUid, targetUid)) {
803 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
804 result->resultCode = ::PERMISSION_DENIED;
805 return;
806 }
807 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
808 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
809 result->resultCode = ::PERMISSION_DENIED;
810 return;
811 }
812 if (!checkAllowedOperationParams(params.params)) {
813 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
814 return;
815 }
816 Blob keyBlob;
817 String8 name8(name);
818 ResponseCode responseCode =
819 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
820 if (responseCode != ::NO_ERROR) {
821 result->resultCode = responseCode;
822 return;
823 }
824 keymaster_key_blob_t key;
825 key.key_material_size = keyBlob.getLength();
826 key.key_material = keyBlob.getValue();
827 keymaster_operation_handle_t handle;
828 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
829 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
830 std::vector<keymaster_key_param_t> opParams(params.params);
831 Unique_keymaster_key_characteristics characteristics;
832 characteristics.reset(new keymaster_key_characteristics_t);
833 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
834 if (err) {
835 result->resultCode = err;
836 return;
837 }
838 const hw_auth_token_t* authToken = NULL;
839 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
840 /*failOnTokenMissing*/ false);
841 // If per-operation auth is needed we need to begin the operation and
842 // the client will need to authorize that operation before calling
843 // update. Any other auth issues stop here.
844 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
845 result->resultCode = authResult;
846 return;
847 }
848 addAuthToParams(&opParams, authToken);
849 // Add entropy to the device first.
850 if (entropy) {
851 if (dev->add_rng_entropy) {
852 err = dev->add_rng_entropy(dev, entropy, entropyLength);
853 } else {
854 err = KM_ERROR_UNIMPLEMENTED;
855 }
856 if (err) {
857 result->resultCode = err;
858 return;
859 }
860 }
861 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
862
863 // Create a keyid for this key.
864 keymaster::km_id_t keyid;
865 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
866 ALOGE("Failed to create a key ID for authorization checking.");
867 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
868 return;
869 }
870
871 // Check that all key authorization policy requirements are met.
872 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
873 key_auths.push_back(characteristics->sw_enforced);
874 keymaster::AuthorizationSet operation_params(inParams);
875 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
876 0 /* op_handle */, true /* is_begin_operation */);
877 if (err) {
878 result->resultCode = err;
879 return;
880 }
881
882 keymaster_key_param_set_t outParams = {NULL, 0};
883
884 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
885 // pruneable.
886 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
887 ALOGD("Reached or exceeded concurrent operations limit");
888 if (!pruneOperation()) {
889 break;
890 }
891 }
892
893 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
894 if (err != KM_ERROR_OK) {
895 ALOGE("Got error %d from begin()", err);
896 }
897
898 // If there are too many operations abort the oldest operation that was
899 // started as pruneable and try again.
900 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
901 ALOGE("Ran out of operation handles");
902 if (!pruneOperation()) {
903 break;
904 }
905 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
906 }
907 if (err) {
908 result->resultCode = err;
909 return;
910 }
911
912 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev, appToken,
913 characteristics.release(), pruneable);
914 if (authToken) {
915 mOperationMap.setOperationAuthToken(operationToken, authToken);
916 }
917 // Return the authentication lookup result. If this is a per operation
918 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
919 // application should get an auth token using the handle before the
920 // first call to update, which will fail if keystore hasn't received the
921 // auth token.
922 result->resultCode = authResult;
923 result->token = operationToken;
924 result->handle = handle;
925 if (outParams.params) {
926 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
927 free(outParams.params);
928 }
929}
930
931void KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
932 const uint8_t* data, size_t dataLength, OperationResult* result) {
933 if (!checkAllowedOperationParams(params.params)) {
934 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
935 return;
936 }
937 const keymaster1_device_t* dev;
938 keymaster_operation_handle_t handle;
939 keymaster_purpose_t purpose;
940 keymaster::km_id_t keyid;
941 const keymaster_key_characteristics_t* characteristics;
942 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
943 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
944 return;
945 }
946 std::vector<keymaster_key_param_t> opParams(params.params);
947 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
948 if (authResult != ::NO_ERROR) {
949 result->resultCode = authResult;
950 return;
951 }
952 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
953 keymaster_blob_t input = {data, dataLength};
954 size_t consumed = 0;
955 keymaster_blob_t output = {NULL, 0};
956 keymaster_key_param_set_t outParams = {NULL, 0};
957
958 // Check that all key authorization policy requirements are met.
959 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
960 key_auths.push_back(characteristics->sw_enforced);
961 keymaster::AuthorizationSet operation_params(inParams);
962 result->resultCode = enforcement_policy.AuthorizeOperation(
963 purpose, keyid, key_auths, operation_params, handle, false /* is_begin_operation */);
964 if (result->resultCode) {
965 return;
966 }
967
968 keymaster_error_t err =
969 dev->update(dev, handle, &inParams, &input, &consumed, &outParams, &output);
970 result->data.reset(const_cast<uint8_t*>(output.data));
971 result->dataLength = output.data_length;
972 result->inputConsumed = consumed;
973 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
974 if (outParams.params) {
975 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
976 free(outParams.params);
977 }
978}
979
980void KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
981 const uint8_t* signature, size_t signatureLength,
982 const uint8_t* entropy, size_t entropyLength,
983 OperationResult* result) {
984 if (!checkAllowedOperationParams(params.params)) {
985 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
986 return;
987 }
988 const keymaster1_device_t* dev;
989 keymaster_operation_handle_t handle;
990 keymaster_purpose_t purpose;
991 keymaster::km_id_t keyid;
992 const keymaster_key_characteristics_t* characteristics;
993 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
994 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
995 return;
996 }
997 std::vector<keymaster_key_param_t> opParams(params.params);
998 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
999 if (authResult != ::NO_ERROR) {
1000 result->resultCode = authResult;
1001 return;
1002 }
1003 keymaster_error_t err;
1004 if (entropy) {
1005 if (dev->add_rng_entropy) {
1006 err = dev->add_rng_entropy(dev, entropy, entropyLength);
1007 } else {
1008 err = KM_ERROR_UNIMPLEMENTED;
1009 }
1010 if (err) {
1011 result->resultCode = err;
1012 return;
1013 }
1014 }
1015
1016 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1017 keymaster_blob_t input = {signature, signatureLength};
1018 keymaster_blob_t output = {NULL, 0};
1019 keymaster_key_param_set_t outParams = {NULL, 0};
1020
1021 // Check that all key authorization policy requirements are met.
1022 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1023 key_auths.push_back(characteristics->sw_enforced);
1024 keymaster::AuthorizationSet operation_params(inParams);
1025 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params, handle,
1026 false /* is_begin_operation */);
1027 if (err) {
1028 result->resultCode = err;
1029 return;
1030 }
1031
1032 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
1033 // Remove the operation regardless of the result
1034 mOperationMap.removeOperation(token);
1035 mAuthTokenTable.MarkCompleted(handle);
1036
1037 result->data.reset(const_cast<uint8_t*>(output.data));
1038 result->dataLength = output.data_length;
1039 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1040 if (outParams.params) {
1041 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1042 free(outParams.params);
1043 }
1044}
1045
1046int32_t KeyStoreService::abort(const sp<IBinder>& token) {
1047 const keymaster1_device_t* dev;
1048 keymaster_operation_handle_t handle;
1049 keymaster_purpose_t purpose;
1050 keymaster::km_id_t keyid;
1051 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
1052 return KM_ERROR_INVALID_OPERATION_HANDLE;
1053 }
1054 mOperationMap.removeOperation(token);
1055 int32_t rc;
1056 if (!dev->abort) {
1057 rc = KM_ERROR_UNIMPLEMENTED;
1058 } else {
1059 rc = dev->abort(dev, handle);
1060 }
1061 mAuthTokenTable.MarkCompleted(handle);
1062 if (rc) {
1063 return rc;
1064 }
1065 return ::NO_ERROR;
1066}
1067
1068bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
1069 const keymaster1_device_t* dev;
1070 keymaster_operation_handle_t handle;
1071 const keymaster_key_characteristics_t* characteristics;
1072 keymaster_purpose_t purpose;
1073 keymaster::km_id_t keyid;
1074 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1075 return false;
1076 }
1077 const hw_auth_token_t* authToken = NULL;
1078 mOperationMap.getOperationAuthToken(token, &authToken);
1079 std::vector<keymaster_key_param_t> ignored;
1080 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1081 return authResult == ::NO_ERROR;
1082}
1083
1084int32_t KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1085 if (!checkBinderPermission(P_ADD_AUTH)) {
1086 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
1087 return ::PERMISSION_DENIED;
1088 }
1089 if (length != sizeof(hw_auth_token_t)) {
1090 return KM_ERROR_INVALID_ARGUMENT;
1091 }
1092 hw_auth_token_t* authToken = new hw_auth_token_t;
1093 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
1094 // The table takes ownership of authToken.
1095 mAuthTokenTable.AddAuthenticationToken(authToken);
1096 return ::NO_ERROR;
1097}
1098
1099/**
1100 * Prune the oldest pruneable operation.
1101 */
1102bool KeyStoreService::pruneOperation() {
1103 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1104 ALOGD("Trying to prune operation %p", oldest.get());
1105 size_t op_count_before_abort = mOperationMap.getOperationCount();
1106 // We mostly ignore errors from abort() because all we care about is whether at least
1107 // one operation has been removed.
1108 int abort_error = abort(oldest);
1109 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1110 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1111 return false;
1112 }
1113 return true;
1114}
1115
1116/**
1117 * Get the effective target uid for a binder operation that takes an
1118 * optional uid as the target.
1119 */
1120uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1121 if (targetUid == UID_SELF) {
1122 return IPCThreadState::self()->getCallingUid();
1123 }
1124 return static_cast<uid_t>(targetUid);
1125}
1126
1127/**
1128 * Check if the caller of the current binder method has the required
1129 * permission and if acting on other uids the grants to do so.
1130 */
1131bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1132 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1133 pid_t spid = IPCThreadState::self()->getCallingPid();
1134 if (!has_permission(callingUid, permission, spid)) {
1135 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1136 return false;
1137 }
1138 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1139 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1140 return false;
1141 }
1142 return true;
1143}
1144
1145/**
1146 * Check if the caller of the current binder method has the required
1147 * permission and the target uid is the caller or the caller is system.
1148 */
1149bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1150 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1151 pid_t spid = IPCThreadState::self()->getCallingPid();
1152 if (!has_permission(callingUid, permission, spid)) {
1153 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1154 return false;
1155 }
1156 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1157}
1158
1159/**
1160 * Check if the caller of the current binder method has the required
1161 * permission or the target of the operation is the caller's uid. This is
1162 * for operation where the permission is only for cross-uid activity and all
1163 * uids are allowed to act on their own (ie: clearing all entries for a
1164 * given uid).
1165 */
1166bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1167 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1168 if (getEffectiveUid(targetUid) == callingUid) {
1169 return true;
1170 } else {
1171 return checkBinderPermission(permission, targetUid);
1172 }
1173}
1174
1175/**
1176 * Helper method to check that the caller has the required permission as
1177 * well as the keystore is in the unlocked state if checkUnlocked is true.
1178 *
1179 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1180 * otherwise the state of keystore when not unlocked and checkUnlocked is
1181 * true.
1182 */
1183int32_t KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1184 bool checkUnlocked) {
1185 if (!checkBinderPermission(permission, targetUid)) {
1186 return ::PERMISSION_DENIED;
1187 }
1188 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1189 if (checkUnlocked && !isKeystoreUnlocked(state)) {
1190 return state;
1191 }
1192
1193 return ::NO_ERROR;
1194}
1195
1196bool KeyStoreService::isKeystoreUnlocked(State state) {
1197 switch (state) {
1198 case ::STATE_NO_ERROR:
1199 return true;
1200 case ::STATE_UNINITIALIZED:
1201 case ::STATE_LOCKED:
1202 return false;
1203 }
1204 return false;
1205}
1206
1207bool KeyStoreService::isKeyTypeSupported(const keymaster1_device_t* device,
1208 keymaster_keypair_t keyType) {
1209 const int32_t device_api = device->common.module->module_api_version;
1210 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
1211 switch (keyType) {
1212 case TYPE_RSA:
1213 case TYPE_DSA:
1214 case TYPE_EC:
1215 return true;
1216 default:
1217 return false;
1218 }
1219 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
1220 switch (keyType) {
1221 case TYPE_RSA:
1222 return true;
1223 case TYPE_DSA:
1224 return device->flags & KEYMASTER_SUPPORTS_DSA;
1225 case TYPE_EC:
1226 return device->flags & KEYMASTER_SUPPORTS_EC;
1227 default:
1228 return false;
1229 }
1230 } else {
1231 return keyType == TYPE_RSA;
1232 }
1233}
1234
1235/**
1236 * Check that all keymaster_key_param_t's provided by the application are
1237 * allowed. Any parameter that keystore adds itself should be disallowed here.
1238 */
1239bool KeyStoreService::checkAllowedOperationParams(
1240 const std::vector<keymaster_key_param_t>& params) {
1241 for (auto param : params) {
1242 switch (param.tag) {
1243 case KM_TAG_AUTH_TOKEN:
1244 return false;
1245 default:
1246 break;
1247 }
1248 }
1249 return true;
1250}
1251
1252keymaster_error_t KeyStoreService::getOperationCharacteristics(
1253 const keymaster_key_blob_t& key, const keymaster1_device_t* dev,
1254 const std::vector<keymaster_key_param_t>& params, keymaster_key_characteristics_t* out) {
1255 UniquePtr<keymaster_blob_t> appId;
1256 UniquePtr<keymaster_blob_t> appData;
1257 for (auto param : params) {
1258 if (param.tag == KM_TAG_APPLICATION_ID) {
1259 appId.reset(new keymaster_blob_t);
1260 appId->data = param.blob.data;
1261 appId->data_length = param.blob.data_length;
1262 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
1263 appData.reset(new keymaster_blob_t);
1264 appData->data = param.blob.data;
1265 appData->data_length = param.blob.data_length;
1266 }
1267 }
1268 keymaster_key_characteristics_t* result = NULL;
1269 if (!dev->get_key_characteristics) {
1270 return KM_ERROR_UNIMPLEMENTED;
1271 }
1272 keymaster_error_t error =
1273 dev->get_key_characteristics(dev, &key, appId.get(), appData.get(), &result);
1274 if (result) {
1275 *out = *result;
1276 free(result);
1277 }
1278 return error;
1279}
1280
1281/**
1282 * Get the auth token for this operation from the auth token table.
1283 *
1284 * Returns ::NO_ERROR if the auth token was set or none was required.
1285 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1286 * authorization token exists for that operation and
1287 * failOnTokenMissing is false.
1288 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1289 * token for the operation
1290 */
1291int32_t KeyStoreService::getAuthToken(const keymaster_key_characteristics_t* characteristics,
1292 keymaster_operation_handle_t handle,
1293 keymaster_purpose_t purpose,
1294 const hw_auth_token_t** authToken, bool failOnTokenMissing) {
1295
1296 std::vector<keymaster_key_param_t> allCharacteristics;
1297 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1298 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
1299 }
1300 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1301 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
1302 }
1303 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1304 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
1305 switch (err) {
1306 case keymaster::AuthTokenTable::OK:
1307 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
1308 return ::NO_ERROR;
1309 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1310 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
1311 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1312 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
1313 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
1314 return failOnTokenMissing ? (int32_t)KM_ERROR_KEY_USER_NOT_AUTHENTICATED
1315 : (int32_t)::OP_AUTH_NEEDED;
1316 default:
1317 ALOGE("Unexpected FindAuthorization return value %d", err);
1318 return KM_ERROR_INVALID_ARGUMENT;
1319 }
1320}
1321
1322inline void KeyStoreService::addAuthToParams(std::vector<keymaster_key_param_t>* params,
1323 const hw_auth_token_t* token) {
1324 if (token) {
1325 params->push_back(keymaster_param_blob(
1326 KM_TAG_AUTH_TOKEN, reinterpret_cast<const uint8_t*>(token), sizeof(hw_auth_token_t)));
1327 }
1328}
1329
1330/**
1331 * Add the auth token for the operation to the param list if the operation
1332 * requires authorization. Uses the cached result in the OperationMap if available
1333 * otherwise gets the token from the AuthTokenTable and caches the result.
1334 *
1335 * Returns ::NO_ERROR if the auth token was added or not needed.
1336 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1337 * authenticated.
1338 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1339 * operation token.
1340 */
1341int32_t KeyStoreService::addOperationAuthTokenIfNeeded(sp<IBinder> token,
1342 std::vector<keymaster_key_param_t>* params) {
1343 const hw_auth_token_t* authToken = NULL;
1344 mOperationMap.getOperationAuthToken(token, &authToken);
1345 if (!authToken) {
1346 const keymaster1_device_t* dev;
1347 keymaster_operation_handle_t handle;
1348 const keymaster_key_characteristics_t* characteristics = NULL;
1349 keymaster_purpose_t purpose;
1350 keymaster::km_id_t keyid;
1351 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1352 return KM_ERROR_INVALID_OPERATION_HANDLE;
1353 }
1354 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
1355 if (result != ::NO_ERROR) {
1356 return result;
1357 }
1358 if (authToken) {
1359 mOperationMap.setOperationAuthToken(token, authToken);
1360 }
1361 }
1362 addAuthToParams(params, authToken);
1363 return ::NO_ERROR;
1364}
1365
1366/**
1367 * Translate a result value to a legacy return value. All keystore errors are
1368 * preserved and keymaster errors become SYSTEM_ERRORs
1369 */
1370int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
1371 if (result > 0) {
1372 return result;
1373 }
1374 return ::SYSTEM_ERROR;
1375}
1376
1377keymaster_key_param_t*
1378KeyStoreService::getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
1379 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1380 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1381 return &characteristics->hw_enforced.params[i];
1382 }
1383 }
1384 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1385 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1386 return &characteristics->sw_enforced.params[i];
1387 }
1388 }
1389 return NULL;
1390}
1391
1392void KeyStoreService::addLegacyBeginParams(const String16& name,
1393 std::vector<keymaster_key_param_t>& params) {
1394 // All legacy keys are DIGEST_NONE/PAD_NONE.
1395 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
1396 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
1397
1398 // Look up the algorithm of the key.
1399 KeyCharacteristics characteristics;
1400 int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
1401 if (rc != ::NO_ERROR) {
1402 ALOGE("Failed to get key characteristics");
1403 return;
1404 }
1405 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
1406 if (!algorithm) {
1407 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1408 return;
1409 }
1410 params.push_back(*algorithm);
1411}
1412
1413int32_t KeyStoreService::doLegacySignVerify(const String16& name, const uint8_t* data,
1414 size_t length, uint8_t** out, size_t* outLength,
1415 const uint8_t* signature, size_t signatureLength,
1416 keymaster_purpose_t purpose) {
1417
1418 std::basic_stringstream<uint8_t> outBuffer;
1419 OperationResult result;
1420 KeymasterArguments inArgs;
1421 addLegacyBeginParams(name, inArgs.params);
1422 sp<IBinder> appToken(new BBinder);
1423 sp<IBinder> token;
1424
1425 begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
1426 if (result.resultCode != ResponseCode::NO_ERROR) {
1427 if (result.resultCode == ::KEY_NOT_FOUND) {
1428 ALOGW("Key not found");
1429 } else {
1430 ALOGW("Error in begin: %d", result.resultCode);
1431 }
1432 return translateResultToLegacyResult(result.resultCode);
1433 }
1434 inArgs.params.clear();
1435 token = result.token;
1436 size_t consumed = 0;
1437 size_t lastConsumed = 0;
1438 do {
1439 update(token, inArgs, data + consumed, length - consumed, &result);
1440 if (result.resultCode != ResponseCode::NO_ERROR) {
1441 ALOGW("Error in update: %d", result.resultCode);
1442 return translateResultToLegacyResult(result.resultCode);
1443 }
1444 if (out) {
1445 outBuffer.write(result.data.get(), result.dataLength);
1446 }
1447 lastConsumed = result.inputConsumed;
1448 consumed += lastConsumed;
1449 } while (consumed < length && lastConsumed > 0);
1450
1451 if (consumed != length) {
1452 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
1453 return ::SYSTEM_ERROR;
1454 }
1455
1456 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
1457 if (result.resultCode != ResponseCode::NO_ERROR) {
1458 ALOGW("Error in finish: %d", result.resultCode);
1459 return translateResultToLegacyResult(result.resultCode);
1460 }
1461 if (out) {
1462 outBuffer.write(result.data.get(), result.dataLength);
1463 }
1464
1465 if (out) {
1466 auto buf = outBuffer.str();
1467 *out = new uint8_t[buf.size()];
1468 memcpy(*out, buf.c_str(), buf.size());
1469 *outLength = buf.size();
1470 }
1471
1472 return ::NO_ERROR;
1473}
1474
1475} // namespace android