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