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