blob: e02ef8b60c0a85e8dc6178e1c8c1747b4804800c [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) {
Shawn Willden715d0232016-01-21 00:45:13 -0700564 const auto* device = mKeyStore->getDevice();
565 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566 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;
Shawn Willden715d0232016-01-21 00:45:13 -0700596 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597
Shawn Willden715d0232016-01-21 00:45:13 -0700598 const auto* device = mKeyStore->getDevice();
599 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700600 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) {
Shawn Willden715d0232016-01-21 00:45:13 -0700616 rc =
617 device->generate_key(device, &inParams, &blob, outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700618 }
619 }
620 // If the HW device didn't support generate_key or generate_key failed
621 // fall back to the software implementation.
622 if (rc && fallback->generate_key != NULL) {
623 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
624 isFallback = true;
625 if (!entropy) {
626 rc = KM_ERROR_OK;
627 } else if (fallback->add_rng_entropy) {
628 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
629 } else {
630 rc = KM_ERROR_UNIMPLEMENTED;
631 }
632 if (rc == KM_ERROR_OK) {
Shawn Willden715d0232016-01-21 00:45:13 -0700633 rc = fallback->generate_key(fallback, &inParams, &blob,
634 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635 }
636 }
637
Shawn Willden715d0232016-01-21 00:45:13 -0700638 if (outCharacteristics) {
639 outCharacteristics->characteristics = out;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700640 }
641
642 if (rc) {
643 return rc;
644 }
645
646 String8 name8(name);
647 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
648
649 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
650 keyBlob.setFallback(isFallback);
651 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
652
653 free(const_cast<uint8_t*>(blob.key_material));
654
655 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
656}
657
658int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
659 const keymaster_blob_t* clientId,
660 const keymaster_blob_t* appData, int32_t uid,
661 KeyCharacteristics* outCharacteristics) {
662 if (!outCharacteristics) {
663 return KM_ERROR_UNEXPECTED_NULL_POINTER;
664 }
665
666 uid_t targetUid = getEffectiveUid(uid);
667 uid_t callingUid = IPCThreadState::self()->getCallingUid();
668 if (!is_granted_to(callingUid, targetUid)) {
669 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
670 targetUid);
671 return ::PERMISSION_DENIED;
672 }
673
674 Blob keyBlob;
675 String8 name8(name);
676 int rc;
677
678 ResponseCode responseCode =
679 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
680 if (responseCode != ::NO_ERROR) {
681 return responseCode;
682 }
683 keymaster_key_blob_t key;
684 key.key_material_size = keyBlob.getLength();
685 key.key_material = keyBlob.getValue();
Shawn Willden715d0232016-01-21 00:45:13 -0700686 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
687 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700688 if (!dev->get_key_characteristics) {
Shawn Willden715d0232016-01-21 00:45:13 -0700689 ALOGE("device does not implement get_key_characteristics");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700690 return KM_ERROR_UNIMPLEMENTED;
691 }
692 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Shawn Willden715d0232016-01-21 00:45:13 -0700693 if (rc != KM_ERROR_OK) {
694 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700695 }
Shawn Willden715d0232016-01-21 00:45:13 -0700696
697 outCharacteristics->characteristics = out;
698 return ::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700699}
700
701int32_t KeyStoreService::importKey(const String16& name, const KeymasterArguments& params,
702 keymaster_key_format_t format, const uint8_t* keyData,
703 size_t keyLength, int uid, int flags,
704 KeyCharacteristics* outCharacteristics) {
705 uid = getEffectiveUid(uid);
706 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
707 if (rc != ::NO_ERROR) {
708 return rc;
709 }
710
711 rc = KM_ERROR_UNIMPLEMENTED;
712 bool isFallback = false;
713 keymaster_key_blob_t blob;
Shawn Willden715d0232016-01-21 00:45:13 -0700714 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700715
Shawn Willden715d0232016-01-21 00:45:13 -0700716 const auto* device = mKeyStore->getDevice();
717 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700718 std::vector<keymaster_key_param_t> opParams(params.params);
719 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
720 const keymaster_blob_t input = {keyData, keyLength};
721 if (device == NULL) {
722 return ::SYSTEM_ERROR;
723 }
724 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
725 device->import_key != NULL) {
Shawn Willden715d0232016-01-21 00:45:13 -0700726 rc = device->import_key(device, &inParams, format, &input, &blob,
727 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700728 }
729 if (rc && fallback->import_key != NULL) {
730 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
731 isFallback = true;
Shawn Willden715d0232016-01-21 00:45:13 -0700732 rc = fallback->import_key(fallback, &inParams, format, &input, &blob,
733 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700734 }
Shawn Willden715d0232016-01-21 00:45:13 -0700735 if (outCharacteristics) {
736 outCharacteristics->characteristics = out;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700737 }
Shawn Willden715d0232016-01-21 00:45:13 -0700738
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700739 if (rc) {
740 return rc;
741 }
742
743 String8 name8(name);
744 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
745
746 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
747 keyBlob.setFallback(isFallback);
748 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
749
Shawn Willden715d0232016-01-21 00:45:13 -0700750 free(const_cast<uint8_t*>(blob.key_material));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751
752 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
753}
754
755void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
756 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
757 int32_t uid, ExportResult* result) {
758
759 uid_t targetUid = getEffectiveUid(uid);
760 uid_t callingUid = IPCThreadState::self()->getCallingUid();
761 if (!is_granted_to(callingUid, targetUid)) {
762 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
763 result->resultCode = ::PERMISSION_DENIED;
764 return;
765 }
766
767 Blob keyBlob;
768 String8 name8(name);
769 int rc;
770
771 ResponseCode responseCode =
772 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
773 if (responseCode != ::NO_ERROR) {
774 result->resultCode = responseCode;
775 return;
776 }
777 keymaster_key_blob_t key;
778 key.key_material_size = keyBlob.getLength();
779 key.key_material = keyBlob.getValue();
Shawn Willden715d0232016-01-21 00:45:13 -0700780 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781 if (!dev->export_key) {
782 result->resultCode = KM_ERROR_UNIMPLEMENTED;
783 return;
784 }
785 keymaster_blob_t output = {NULL, 0};
786 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
787 result->exportData.reset(const_cast<uint8_t*>(output.data));
788 result->dataLength = output.data_length;
789 result->resultCode = rc ? rc : ::NO_ERROR;
790}
791
792void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
793 keymaster_purpose_t purpose, bool pruneable,
794 const KeymasterArguments& params, const uint8_t* entropy,
795 size_t entropyLength, int32_t uid, OperationResult* result) {
796 uid_t callingUid = IPCThreadState::self()->getCallingUid();
797 uid_t targetUid = getEffectiveUid(uid);
798 if (!is_granted_to(callingUid, targetUid)) {
799 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
800 result->resultCode = ::PERMISSION_DENIED;
801 return;
802 }
803 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
804 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
805 result->resultCode = ::PERMISSION_DENIED;
806 return;
807 }
808 if (!checkAllowedOperationParams(params.params)) {
809 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
810 return;
811 }
812 Blob keyBlob;
813 String8 name8(name);
814 ResponseCode responseCode =
815 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
816 if (responseCode != ::NO_ERROR) {
817 result->resultCode = responseCode;
818 return;
819 }
820 keymaster_key_blob_t key;
821 key.key_material_size = keyBlob.getLength();
822 key.key_material = keyBlob.getValue();
823 keymaster_operation_handle_t handle;
Shawn Willden715d0232016-01-21 00:45:13 -0700824 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
826 std::vector<keymaster_key_param_t> opParams(params.params);
827 Unique_keymaster_key_characteristics characteristics;
828 characteristics.reset(new keymaster_key_characteristics_t);
829 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
830 if (err) {
831 result->resultCode = err;
832 return;
833 }
834 const hw_auth_token_t* authToken = NULL;
835 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
836 /*failOnTokenMissing*/ false);
837 // If per-operation auth is needed we need to begin the operation and
838 // the client will need to authorize that operation before calling
839 // update. Any other auth issues stop here.
840 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
841 result->resultCode = authResult;
842 return;
843 }
844 addAuthToParams(&opParams, authToken);
845 // Add entropy to the device first.
846 if (entropy) {
847 if (dev->add_rng_entropy) {
848 err = dev->add_rng_entropy(dev, entropy, entropyLength);
849 } else {
850 err = KM_ERROR_UNIMPLEMENTED;
851 }
852 if (err) {
853 result->resultCode = err;
854 return;
855 }
856 }
857 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
858
859 // Create a keyid for this key.
860 keymaster::km_id_t keyid;
861 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
862 ALOGE("Failed to create a key ID for authorization checking.");
863 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
864 return;
865 }
866
867 // Check that all key authorization policy requirements are met.
868 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
869 key_auths.push_back(characteristics->sw_enforced);
870 keymaster::AuthorizationSet operation_params(inParams);
871 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
872 0 /* op_handle */, true /* is_begin_operation */);
873 if (err) {
874 result->resultCode = err;
875 return;
876 }
877
878 keymaster_key_param_set_t outParams = {NULL, 0};
879
880 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
881 // pruneable.
882 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
883 ALOGD("Reached or exceeded concurrent operations limit");
884 if (!pruneOperation()) {
885 break;
886 }
887 }
888
889 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
890 if (err != KM_ERROR_OK) {
891 ALOGE("Got error %d from begin()", err);
892 }
893
894 // If there are too many operations abort the oldest operation that was
895 // started as pruneable and try again.
896 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
897 ALOGE("Ran out of operation handles");
898 if (!pruneOperation()) {
899 break;
900 }
901 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
902 }
903 if (err) {
904 result->resultCode = err;
905 return;
906 }
907
908 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev, appToken,
909 characteristics.release(), pruneable);
910 if (authToken) {
911 mOperationMap.setOperationAuthToken(operationToken, authToken);
912 }
913 // Return the authentication lookup result. If this is a per operation
914 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
915 // application should get an auth token using the handle before the
916 // first call to update, which will fail if keystore hasn't received the
917 // auth token.
918 result->resultCode = authResult;
919 result->token = operationToken;
920 result->handle = handle;
921 if (outParams.params) {
922 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
923 free(outParams.params);
924 }
925}
926
927void KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
928 const uint8_t* data, size_t dataLength, OperationResult* result) {
929 if (!checkAllowedOperationParams(params.params)) {
930 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
931 return;
932 }
Shawn Willden715d0232016-01-21 00:45:13 -0700933 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700934 keymaster_operation_handle_t handle;
935 keymaster_purpose_t purpose;
936 keymaster::km_id_t keyid;
937 const keymaster_key_characteristics_t* characteristics;
938 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
939 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
940 return;
941 }
942 std::vector<keymaster_key_param_t> opParams(params.params);
943 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
944 if (authResult != ::NO_ERROR) {
945 result->resultCode = authResult;
946 return;
947 }
948 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
949 keymaster_blob_t input = {data, dataLength};
950 size_t consumed = 0;
951 keymaster_blob_t output = {NULL, 0};
952 keymaster_key_param_set_t outParams = {NULL, 0};
953
954 // Check that all key authorization policy requirements are met.
955 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
956 key_auths.push_back(characteristics->sw_enforced);
957 keymaster::AuthorizationSet operation_params(inParams);
958 result->resultCode = enforcement_policy.AuthorizeOperation(
959 purpose, keyid, key_auths, operation_params, handle, false /* is_begin_operation */);
960 if (result->resultCode) {
961 return;
962 }
963
964 keymaster_error_t err =
965 dev->update(dev, handle, &inParams, &input, &consumed, &outParams, &output);
966 result->data.reset(const_cast<uint8_t*>(output.data));
967 result->dataLength = output.data_length;
968 result->inputConsumed = consumed;
969 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
970 if (outParams.params) {
971 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
972 free(outParams.params);
973 }
974}
975
976void KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
977 const uint8_t* signature, size_t signatureLength,
978 const uint8_t* entropy, size_t entropyLength,
979 OperationResult* result) {
980 if (!checkAllowedOperationParams(params.params)) {
981 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
982 return;
983 }
Shawn Willden715d0232016-01-21 00:45:13 -0700984 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700985 keymaster_operation_handle_t handle;
986 keymaster_purpose_t purpose;
987 keymaster::km_id_t keyid;
988 const keymaster_key_characteristics_t* characteristics;
989 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
990 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
991 return;
992 }
993 std::vector<keymaster_key_param_t> opParams(params.params);
994 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
995 if (authResult != ::NO_ERROR) {
996 result->resultCode = authResult;
997 return;
998 }
999 keymaster_error_t err;
1000 if (entropy) {
1001 if (dev->add_rng_entropy) {
1002 err = dev->add_rng_entropy(dev, entropy, entropyLength);
1003 } else {
1004 err = KM_ERROR_UNIMPLEMENTED;
1005 }
1006 if (err) {
1007 result->resultCode = err;
1008 return;
1009 }
1010 }
1011
1012 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Shawn Willden715d0232016-01-21 00:45:13 -07001013 keymaster_blob_t input = {nullptr, 0};
1014 keymaster_blob_t sig = {signature, signatureLength};
1015 keymaster_blob_t output = {nullptr, 0};
1016 keymaster_key_param_set_t outParams = {nullptr, 0};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001017
1018 // Check that all key authorization policy requirements are met.
1019 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1020 key_auths.push_back(characteristics->sw_enforced);
1021 keymaster::AuthorizationSet operation_params(inParams);
1022 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params, handle,
1023 false /* is_begin_operation */);
1024 if (err) {
1025 result->resultCode = err;
1026 return;
1027 }
1028
Shawn Willden715d0232016-01-21 00:45:13 -07001029 err =
1030 dev->finish(dev, handle, &inParams, &input /* TODO(swillden): wire up input to finish() */,
1031 &sig, &outParams, &output);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001032 // Remove the operation regardless of the result
1033 mOperationMap.removeOperation(token);
1034 mAuthTokenTable.MarkCompleted(handle);
1035
1036 result->data.reset(const_cast<uint8_t*>(output.data));
1037 result->dataLength = output.data_length;
1038 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1039 if (outParams.params) {
1040 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1041 free(outParams.params);
1042 }
1043}
1044
1045int32_t KeyStoreService::abort(const sp<IBinder>& token) {
Shawn Willden715d0232016-01-21 00:45:13 -07001046 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001047 keymaster_operation_handle_t handle;
1048 keymaster_purpose_t purpose;
1049 keymaster::km_id_t keyid;
1050 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
1051 return KM_ERROR_INVALID_OPERATION_HANDLE;
1052 }
1053 mOperationMap.removeOperation(token);
1054 int32_t rc;
1055 if (!dev->abort) {
1056 rc = KM_ERROR_UNIMPLEMENTED;
1057 } else {
1058 rc = dev->abort(dev, handle);
1059 }
1060 mAuthTokenTable.MarkCompleted(handle);
1061 if (rc) {
1062 return rc;
1063 }
1064 return ::NO_ERROR;
1065}
1066
1067bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Shawn Willden715d0232016-01-21 00:45:13 -07001068 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001069 keymaster_operation_handle_t handle;
1070 const keymaster_key_characteristics_t* characteristics;
1071 keymaster_purpose_t purpose;
1072 keymaster::km_id_t keyid;
1073 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1074 return false;
1075 }
1076 const hw_auth_token_t* authToken = NULL;
1077 mOperationMap.getOperationAuthToken(token, &authToken);
1078 std::vector<keymaster_key_param_t> ignored;
1079 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1080 return authResult == ::NO_ERROR;
1081}
1082
1083int32_t KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1084 if (!checkBinderPermission(P_ADD_AUTH)) {
1085 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
1086 return ::PERMISSION_DENIED;
1087 }
1088 if (length != sizeof(hw_auth_token_t)) {
1089 return KM_ERROR_INVALID_ARGUMENT;
1090 }
1091 hw_auth_token_t* authToken = new hw_auth_token_t;
1092 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
1093 // The table takes ownership of authToken.
1094 mAuthTokenTable.AddAuthenticationToken(authToken);
1095 return ::NO_ERROR;
1096}
1097
Shawn Willden50eb1b22016-01-21 12:41:23 -07001098int32_t KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1099 KeymasterCertificateChain* outChain) {
1100 if (!outChain)
1101 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1102
1103 if (!checkAllowedOperationParams(params.params)) {
1104 return KM_ERROR_INVALID_ARGUMENT;
1105 }
1106
1107 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1108
1109 Blob keyBlob;
1110 String8 name8(name);
1111 ResponseCode responseCode =
1112 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1113 if (responseCode != ::NO_ERROR) {
1114 return responseCode;
1115 }
1116
1117 keymaster_key_blob_t key = {keyBlob.getValue(),
1118 static_cast<size_t>(std::max(0, keyBlob.getLength()))};
1119 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
1120 if (!dev->attest_key)
1121 return KM_ERROR_UNIMPLEMENTED;
1122
1123 const keymaster_key_param_set_t in_params = {
1124 const_cast<keymaster_key_param_t*>(params.params.data()), params.params.size()};
1125 outChain->chain = {nullptr, 0};
1126 int32_t rc = dev->attest_key(dev, &key, &in_params, &outChain->chain);
1127 if (rc)
1128 return rc;
1129 return ::NO_ERROR;
1130}
1131
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001132/**
1133 * Prune the oldest pruneable operation.
1134 */
1135bool KeyStoreService::pruneOperation() {
1136 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1137 ALOGD("Trying to prune operation %p", oldest.get());
1138 size_t op_count_before_abort = mOperationMap.getOperationCount();
1139 // We mostly ignore errors from abort() because all we care about is whether at least
1140 // one operation has been removed.
1141 int abort_error = abort(oldest);
1142 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1143 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1144 return false;
1145 }
1146 return true;
1147}
1148
1149/**
1150 * Get the effective target uid for a binder operation that takes an
1151 * optional uid as the target.
1152 */
1153uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1154 if (targetUid == UID_SELF) {
1155 return IPCThreadState::self()->getCallingUid();
1156 }
1157 return static_cast<uid_t>(targetUid);
1158}
1159
1160/**
1161 * Check if the caller of the current binder method has the required
1162 * permission and if acting on other uids the grants to do so.
1163 */
1164bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1165 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1166 pid_t spid = IPCThreadState::self()->getCallingPid();
1167 if (!has_permission(callingUid, permission, spid)) {
1168 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1169 return false;
1170 }
1171 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1172 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1173 return false;
1174 }
1175 return true;
1176}
1177
1178/**
1179 * Check if the caller of the current binder method has the required
1180 * permission and the target uid is the caller or the caller is system.
1181 */
1182bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1183 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1184 pid_t spid = IPCThreadState::self()->getCallingPid();
1185 if (!has_permission(callingUid, permission, spid)) {
1186 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1187 return false;
1188 }
1189 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1190}
1191
1192/**
1193 * Check if the caller of the current binder method has the required
1194 * permission or the target of the operation is the caller's uid. This is
1195 * for operation where the permission is only for cross-uid activity and all
1196 * uids are allowed to act on their own (ie: clearing all entries for a
1197 * given uid).
1198 */
1199bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1200 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1201 if (getEffectiveUid(targetUid) == callingUid) {
1202 return true;
1203 } else {
1204 return checkBinderPermission(permission, targetUid);
1205 }
1206}
1207
1208/**
1209 * Helper method to check that the caller has the required permission as
1210 * well as the keystore is in the unlocked state if checkUnlocked is true.
1211 *
1212 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1213 * otherwise the state of keystore when not unlocked and checkUnlocked is
1214 * true.
1215 */
1216int32_t KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1217 bool checkUnlocked) {
1218 if (!checkBinderPermission(permission, targetUid)) {
1219 return ::PERMISSION_DENIED;
1220 }
1221 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1222 if (checkUnlocked && !isKeystoreUnlocked(state)) {
1223 return state;
1224 }
1225
1226 return ::NO_ERROR;
1227}
1228
1229bool KeyStoreService::isKeystoreUnlocked(State state) {
1230 switch (state) {
1231 case ::STATE_NO_ERROR:
1232 return true;
1233 case ::STATE_UNINITIALIZED:
1234 case ::STATE_LOCKED:
1235 return false;
1236 }
1237 return false;
1238}
1239
Shawn Willden715d0232016-01-21 00:45:13 -07001240bool KeyStoreService::isKeyTypeSupported(const keymaster2_device_t* device,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001241 keymaster_keypair_t keyType) {
1242 const int32_t device_api = device->common.module->module_api_version;
1243 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
1244 switch (keyType) {
1245 case TYPE_RSA:
1246 case TYPE_DSA:
1247 case TYPE_EC:
1248 return true;
1249 default:
1250 return false;
1251 }
1252 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
1253 switch (keyType) {
1254 case TYPE_RSA:
1255 return true;
1256 case TYPE_DSA:
1257 return device->flags & KEYMASTER_SUPPORTS_DSA;
1258 case TYPE_EC:
1259 return device->flags & KEYMASTER_SUPPORTS_EC;
1260 default:
1261 return false;
1262 }
1263 } else {
1264 return keyType == TYPE_RSA;
1265 }
1266}
1267
1268/**
1269 * Check that all keymaster_key_param_t's provided by the application are
1270 * allowed. Any parameter that keystore adds itself should be disallowed here.
1271 */
1272bool KeyStoreService::checkAllowedOperationParams(
1273 const std::vector<keymaster_key_param_t>& params) {
1274 for (auto param : params) {
1275 switch (param.tag) {
1276 case KM_TAG_AUTH_TOKEN:
1277 return false;
1278 default:
1279 break;
1280 }
1281 }
1282 return true;
1283}
1284
1285keymaster_error_t KeyStoreService::getOperationCharacteristics(
Shawn Willden715d0232016-01-21 00:45:13 -07001286 const keymaster_key_blob_t& key, const keymaster2_device_t* dev,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001287 const std::vector<keymaster_key_param_t>& params, keymaster_key_characteristics_t* out) {
1288 UniquePtr<keymaster_blob_t> appId;
1289 UniquePtr<keymaster_blob_t> appData;
1290 for (auto param : params) {
1291 if (param.tag == KM_TAG_APPLICATION_ID) {
1292 appId.reset(new keymaster_blob_t);
1293 appId->data = param.blob.data;
1294 appId->data_length = param.blob.data_length;
1295 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
1296 appData.reset(new keymaster_blob_t);
1297 appData->data = param.blob.data;
1298 appData->data_length = param.blob.data_length;
1299 }
1300 }
Shawn Willden715d0232016-01-21 00:45:13 -07001301 keymaster_key_characteristics_t result = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001302 if (!dev->get_key_characteristics) {
1303 return KM_ERROR_UNIMPLEMENTED;
1304 }
1305 keymaster_error_t error =
1306 dev->get_key_characteristics(dev, &key, appId.get(), appData.get(), &result);
Shawn Willden715d0232016-01-21 00:45:13 -07001307 if (error == KM_ERROR_OK) {
1308 *out = result;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001309 }
1310 return error;
1311}
1312
1313/**
1314 * Get the auth token for this operation from the auth token table.
1315 *
1316 * Returns ::NO_ERROR if the auth token was set or none was required.
1317 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1318 * authorization token exists for that operation and
1319 * failOnTokenMissing is false.
1320 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1321 * token for the operation
1322 */
1323int32_t KeyStoreService::getAuthToken(const keymaster_key_characteristics_t* characteristics,
1324 keymaster_operation_handle_t handle,
1325 keymaster_purpose_t purpose,
1326 const hw_auth_token_t** authToken, bool failOnTokenMissing) {
1327
1328 std::vector<keymaster_key_param_t> allCharacteristics;
1329 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1330 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
1331 }
1332 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1333 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
1334 }
1335 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1336 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
1337 switch (err) {
1338 case keymaster::AuthTokenTable::OK:
1339 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
1340 return ::NO_ERROR;
1341 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1342 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
1343 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1344 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
1345 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
1346 return failOnTokenMissing ? (int32_t)KM_ERROR_KEY_USER_NOT_AUTHENTICATED
1347 : (int32_t)::OP_AUTH_NEEDED;
1348 default:
1349 ALOGE("Unexpected FindAuthorization return value %d", err);
1350 return KM_ERROR_INVALID_ARGUMENT;
1351 }
1352}
1353
1354inline void KeyStoreService::addAuthToParams(std::vector<keymaster_key_param_t>* params,
1355 const hw_auth_token_t* token) {
1356 if (token) {
1357 params->push_back(keymaster_param_blob(
1358 KM_TAG_AUTH_TOKEN, reinterpret_cast<const uint8_t*>(token), sizeof(hw_auth_token_t)));
1359 }
1360}
1361
1362/**
1363 * Add the auth token for the operation to the param list if the operation
1364 * requires authorization. Uses the cached result in the OperationMap if available
1365 * otherwise gets the token from the AuthTokenTable and caches the result.
1366 *
1367 * Returns ::NO_ERROR if the auth token was added or not needed.
1368 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1369 * authenticated.
1370 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1371 * operation token.
1372 */
1373int32_t KeyStoreService::addOperationAuthTokenIfNeeded(sp<IBinder> token,
1374 std::vector<keymaster_key_param_t>* params) {
1375 const hw_auth_token_t* authToken = NULL;
1376 mOperationMap.getOperationAuthToken(token, &authToken);
1377 if (!authToken) {
Shawn Willden715d0232016-01-21 00:45:13 -07001378 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001379 keymaster_operation_handle_t handle;
1380 const keymaster_key_characteristics_t* characteristics = NULL;
1381 keymaster_purpose_t purpose;
1382 keymaster::km_id_t keyid;
1383 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1384 return KM_ERROR_INVALID_OPERATION_HANDLE;
1385 }
1386 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
1387 if (result != ::NO_ERROR) {
1388 return result;
1389 }
1390 if (authToken) {
1391 mOperationMap.setOperationAuthToken(token, authToken);
1392 }
1393 }
1394 addAuthToParams(params, authToken);
1395 return ::NO_ERROR;
1396}
1397
1398/**
1399 * Translate a result value to a legacy return value. All keystore errors are
1400 * preserved and keymaster errors become SYSTEM_ERRORs
1401 */
1402int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
1403 if (result > 0) {
1404 return result;
1405 }
1406 return ::SYSTEM_ERROR;
1407}
1408
1409keymaster_key_param_t*
1410KeyStoreService::getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
1411 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1412 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1413 return &characteristics->hw_enforced.params[i];
1414 }
1415 }
1416 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1417 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1418 return &characteristics->sw_enforced.params[i];
1419 }
1420 }
1421 return NULL;
1422}
1423
1424void KeyStoreService::addLegacyBeginParams(const String16& name,
1425 std::vector<keymaster_key_param_t>& params) {
1426 // All legacy keys are DIGEST_NONE/PAD_NONE.
1427 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
1428 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
1429
1430 // Look up the algorithm of the key.
1431 KeyCharacteristics characteristics;
1432 int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
1433 if (rc != ::NO_ERROR) {
1434 ALOGE("Failed to get key characteristics");
1435 return;
1436 }
1437 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
1438 if (!algorithm) {
1439 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1440 return;
1441 }
1442 params.push_back(*algorithm);
1443}
1444
1445int32_t KeyStoreService::doLegacySignVerify(const String16& name, const uint8_t* data,
1446 size_t length, uint8_t** out, size_t* outLength,
1447 const uint8_t* signature, size_t signatureLength,
1448 keymaster_purpose_t purpose) {
1449
1450 std::basic_stringstream<uint8_t> outBuffer;
1451 OperationResult result;
1452 KeymasterArguments inArgs;
1453 addLegacyBeginParams(name, inArgs.params);
1454 sp<IBinder> appToken(new BBinder);
1455 sp<IBinder> token;
1456
1457 begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
1458 if (result.resultCode != ResponseCode::NO_ERROR) {
1459 if (result.resultCode == ::KEY_NOT_FOUND) {
1460 ALOGW("Key not found");
1461 } else {
1462 ALOGW("Error in begin: %d", result.resultCode);
1463 }
1464 return translateResultToLegacyResult(result.resultCode);
1465 }
1466 inArgs.params.clear();
1467 token = result.token;
1468 size_t consumed = 0;
1469 size_t lastConsumed = 0;
1470 do {
1471 update(token, inArgs, data + consumed, length - consumed, &result);
1472 if (result.resultCode != ResponseCode::NO_ERROR) {
1473 ALOGW("Error in update: %d", result.resultCode);
1474 return translateResultToLegacyResult(result.resultCode);
1475 }
1476 if (out) {
1477 outBuffer.write(result.data.get(), result.dataLength);
1478 }
1479 lastConsumed = result.inputConsumed;
1480 consumed += lastConsumed;
1481 } while (consumed < length && lastConsumed > 0);
1482
1483 if (consumed != length) {
1484 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
1485 return ::SYSTEM_ERROR;
1486 }
1487
1488 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
1489 if (result.resultCode != ResponseCode::NO_ERROR) {
1490 ALOGW("Error in finish: %d", result.resultCode);
1491 return translateResultToLegacyResult(result.resultCode);
1492 }
1493 if (out) {
1494 outBuffer.write(result.data.get(), result.dataLength);
1495 }
1496
1497 if (out) {
1498 auto buf = outBuffer.str();
1499 *out = new uint8_t[buf.size()];
1500 memcpy(*out, buf.c_str(), buf.size());
1501 *outLength = buf.size();
1502 }
1503
1504 return ::NO_ERROR;
1505}
1506
1507} // namespace android