blob: d68c3670be05780e542fbecf7a635c46a0e3c54a [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
Shawn Willden98c59162016-03-20 09:10:18 -060033using keymaster::AuthorizationSet;
34using keymaster::AuthorizationSetBuilder;
35using keymaster::TAG_APPLICATION_DATA;
36using keymaster::TAG_APPLICATION_ID;
37
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038namespace android {
39
40const size_t MAX_OPERATIONS = 15;
41
42struct BIGNUM_Delete {
43 void operator()(BIGNUM* p) const { BN_free(p); }
44};
45typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
46
Shawn Willden98c59162016-03-20 09:10:18 -060047struct Malloc_Delete {
48 void operator()(uint8_t* p) const { free(p); }
49};
50
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070051void KeyStoreService::binderDied(const wp<IBinder>& who) {
52 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -070053 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070054 abort(token);
55 }
56}
57
58int32_t KeyStoreService::getState(int32_t userId) {
59 if (!checkBinderPermission(P_GET_STATE)) {
60 return ::PERMISSION_DENIED;
61 }
62
63 return mKeyStore->getState(userId);
64}
65
66int32_t KeyStoreService::get(const String16& name, int32_t uid, uint8_t** item,
67 size_t* itemLength) {
68 uid_t targetUid = getEffectiveUid(uid);
69 if (!checkBinderPermission(P_GET, targetUid)) {
70 return ::PERMISSION_DENIED;
71 }
72
73 String8 name8(name);
74 Blob keyBlob;
75
76 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
77 if (responseCode != ::NO_ERROR) {
78 *item = NULL;
79 *itemLength = 0;
80 return responseCode;
81 }
82
83 *item = (uint8_t*)malloc(keyBlob.getLength());
84 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
85 *itemLength = keyBlob.getLength();
86
87 return ::NO_ERROR;
88}
89
90int32_t KeyStoreService::insert(const String16& name, const uint8_t* item, size_t itemLength,
91 int targetUid, int32_t flags) {
92 targetUid = getEffectiveUid(targetUid);
93 int32_t result =
94 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
95 if (result != ::NO_ERROR) {
96 return result;
97 }
98
99 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400100 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700101
102 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
103 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
104
105 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
106}
107
108int32_t KeyStoreService::del(const String16& name, int targetUid) {
109 targetUid = getEffectiveUid(targetUid);
110 if (!checkBinderPermission(P_DELETE, targetUid)) {
111 return ::PERMISSION_DENIED;
112 }
113 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400114 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
115 int32_t result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
116 if (result != ::NO_ERROR) {
117 return result;
118 }
119
120 // Also delete any characteristics files
121 String8 chrFilename(mKeyStore->getKeyNameForUidWithDir(
122 name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
123 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700124}
125
126int32_t KeyStoreService::exist(const String16& name, int targetUid) {
127 targetUid = getEffectiveUid(targetUid);
128 if (!checkBinderPermission(P_EXIST, targetUid)) {
129 return ::PERMISSION_DENIED;
130 }
131
132 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400133 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700134
135 if (access(filename.string(), R_OK) == -1) {
136 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
137 }
138 return ::NO_ERROR;
139}
140
141int32_t KeyStoreService::list(const String16& prefix, int targetUid, Vector<String16>* matches) {
142 targetUid = getEffectiveUid(targetUid);
143 if (!checkBinderPermission(P_LIST, targetUid)) {
144 return ::PERMISSION_DENIED;
145 }
146 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400147 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148
149 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
150 return ::SYSTEM_ERROR;
151 }
152 return ::NO_ERROR;
153}
154
155int32_t KeyStoreService::reset() {
156 if (!checkBinderPermission(P_RESET)) {
157 return ::PERMISSION_DENIED;
158 }
159
160 uid_t callingUid = IPCThreadState::self()->getCallingUid();
161 mKeyStore->resetUser(get_user_id(callingUid), false);
162 return ::NO_ERROR;
163}
164
165int32_t KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password) {
166 if (!checkBinderPermission(P_PASSWORD)) {
167 return ::PERMISSION_DENIED;
168 }
169
170 const String8 password8(password);
171 // Flush the auth token table to prevent stale tokens from sticking
172 // around.
173 mAuthTokenTable.Clear();
174
175 if (password.size() == 0) {
176 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
177 mKeyStore->resetUser(userId, true);
178 return ::NO_ERROR;
179 } else {
180 switch (mKeyStore->getState(userId)) {
181 case ::STATE_UNINITIALIZED: {
182 // generate master key, encrypt with password, write to file,
183 // initialize mMasterKey*.
184 return mKeyStore->initializeUser(password8, userId);
185 }
186 case ::STATE_NO_ERROR: {
187 // rewrite master key with new password.
188 return mKeyStore->writeMasterKey(password8, userId);
189 }
190 case ::STATE_LOCKED: {
191 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
192 mKeyStore->resetUser(userId, true);
193 return mKeyStore->initializeUser(password8, userId);
194 }
195 }
196 return ::SYSTEM_ERROR;
197 }
198}
199
200int32_t KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
201 if (!checkBinderPermission(P_USER_CHANGED)) {
202 return ::PERMISSION_DENIED;
203 }
204
205 // Sanity check that the new user has an empty keystore.
206 if (!mKeyStore->isEmpty(userId)) {
207 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
208 }
209 // Unconditionally clear the keystore, just to be safe.
210 mKeyStore->resetUser(userId, false);
211 if (parentId != -1) {
212 // This profile must share the same master key password as the parent profile. Because the
213 // password of the parent profile is not known here, the best we can do is copy the parent's
214 // master key and master key file. This makes this profile use the same master key as the
215 // parent profile, forever.
216 return mKeyStore->copyMasterKey(parentId, userId);
217 } else {
218 return ::NO_ERROR;
219 }
220}
221
222int32_t KeyStoreService::onUserRemoved(int32_t userId) {
223 if (!checkBinderPermission(P_USER_CHANGED)) {
224 return ::PERMISSION_DENIED;
225 }
226
227 mKeyStore->resetUser(userId, false);
228 return ::NO_ERROR;
229}
230
231int32_t KeyStoreService::lock(int32_t userId) {
232 if (!checkBinderPermission(P_LOCK)) {
233 return ::PERMISSION_DENIED;
234 }
235
236 State state = mKeyStore->getState(userId);
237 if (state != ::STATE_NO_ERROR) {
238 ALOGD("calling lock in state: %d", state);
239 return state;
240 }
241
242 mKeyStore->lock(userId);
243 return ::NO_ERROR;
244}
245
246int32_t KeyStoreService::unlock(int32_t userId, const String16& pw) {
247 if (!checkBinderPermission(P_UNLOCK)) {
248 return ::PERMISSION_DENIED;
249 }
250
251 State state = mKeyStore->getState(userId);
252 if (state != ::STATE_LOCKED) {
253 switch (state) {
254 case ::STATE_NO_ERROR:
255 ALOGI("calling unlock when already unlocked, ignoring.");
256 break;
257 case ::STATE_UNINITIALIZED:
258 ALOGE("unlock called on uninitialized keystore.");
259 break;
260 default:
261 ALOGE("unlock called on keystore in unknown state: %d", state);
262 break;
263 }
264 return state;
265 }
266
267 const String8 password8(pw);
268 // read master key, decrypt with password, initialize mMasterKey*.
269 return mKeyStore->readMasterKey(password8, userId);
270}
271
272bool KeyStoreService::isEmpty(int32_t userId) {
273 if (!checkBinderPermission(P_IS_EMPTY)) {
274 return false;
275 }
276
277 return mKeyStore->isEmpty(userId);
278}
279
280int32_t KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
281 int32_t keySize, int32_t flags, Vector<sp<KeystoreArg>>* args) {
282 targetUid = getEffectiveUid(targetUid);
283 int32_t result =
284 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
285 if (result != ::NO_ERROR) {
286 return result;
287 }
288
289 KeymasterArguments params;
290 add_legacy_key_authorizations(keyType, &params.params);
291
292 switch (keyType) {
293 case EVP_PKEY_EC: {
294 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
295 if (keySize == -1) {
296 keySize = EC_DEFAULT_KEY_SIZE;
297 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
298 ALOGI("invalid key size %d", keySize);
299 return ::SYSTEM_ERROR;
300 }
301 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
302 break;
303 }
304 case EVP_PKEY_RSA: {
305 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
306 if (keySize == -1) {
307 keySize = RSA_DEFAULT_KEY_SIZE;
308 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
309 ALOGI("invalid key size %d", keySize);
310 return ::SYSTEM_ERROR;
311 }
312 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
313 unsigned long exponent = RSA_DEFAULT_EXPONENT;
314 if (args->size() > 1) {
315 ALOGI("invalid number of arguments: %zu", args->size());
316 return ::SYSTEM_ERROR;
317 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700318 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700319 if (expArg != NULL) {
320 Unique_BIGNUM pubExpBn(BN_bin2bn(
321 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
322 if (pubExpBn.get() == NULL) {
323 ALOGI("Could not convert public exponent to BN");
324 return ::SYSTEM_ERROR;
325 }
326 exponent = BN_get_word(pubExpBn.get());
327 if (exponent == 0xFFFFFFFFL) {
328 ALOGW("cannot represent public exponent as a long value");
329 return ::SYSTEM_ERROR;
330 }
331 } else {
332 ALOGW("public exponent not read");
333 return ::SYSTEM_ERROR;
334 }
335 }
336 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, exponent));
337 break;
338 }
339 default: {
340 ALOGW("Unsupported key type %d", keyType);
341 return ::SYSTEM_ERROR;
342 }
343 }
344
345 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
346 /*outCharacteristics*/ NULL);
347 if (rc != ::NO_ERROR) {
348 ALOGW("generate failed: %d", rc);
349 }
350 return translateResultToLegacyResult(rc);
351}
352
353int32_t KeyStoreService::import(const String16& name, const uint8_t* data, size_t length,
354 int targetUid, int32_t flags) {
355 const uint8_t* ptr = data;
356
357 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
358 if (!pkcs8.get()) {
359 return ::SYSTEM_ERROR;
360 }
361 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
362 if (!pkey.get()) {
363 return ::SYSTEM_ERROR;
364 }
365 int type = EVP_PKEY_type(pkey->type);
366 KeymasterArguments params;
367 add_legacy_key_authorizations(type, &params.params);
368 switch (type) {
369 case EVP_PKEY_RSA:
370 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
371 break;
372 case EVP_PKEY_EC:
373 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
374 break;
375 default:
376 ALOGW("Unsupported key type %d", type);
377 return ::SYSTEM_ERROR;
378 }
379 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
380 /*outCharacteristics*/ NULL);
381 if (rc != ::NO_ERROR) {
382 ALOGW("importKey failed: %d", rc);
383 }
384 return translateResultToLegacyResult(rc);
385}
386
387int32_t KeyStoreService::sign(const String16& name, const uint8_t* data, size_t length,
388 uint8_t** out, size_t* outLength) {
389 if (!checkBinderPermission(P_SIGN)) {
390 return ::PERMISSION_DENIED;
391 }
392 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
393}
394
395int32_t KeyStoreService::verify(const String16& name, const uint8_t* data, size_t dataLength,
396 const uint8_t* signature, size_t signatureLength) {
397 if (!checkBinderPermission(P_VERIFY)) {
398 return ::PERMISSION_DENIED;
399 }
400 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
401 KM_PURPOSE_VERIFY);
402}
403
404/*
405 * TODO: The abstraction between things stored in hardware and regular blobs
406 * of data stored on the filesystem should be moved down to keystore itself.
407 * Unfortunately the Java code that calls this has naming conventions that it
408 * knows about. Ideally keystore shouldn't be used to store random blobs of
409 * data.
410 *
411 * Until that happens, it's necessary to have a separate "get_pubkey" and
412 * "del_key" since the Java code doesn't really communicate what it's
413 * intentions are.
414 */
415int32_t KeyStoreService::get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
416 ExportResult result;
417 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, UID_SELF, &result);
418 if (result.resultCode != ::NO_ERROR) {
419 ALOGW("export failed: %d", result.resultCode);
420 return translateResultToLegacyResult(result.resultCode);
421 }
422
423 *pubkey = result.exportData.release();
424 *pubkeyLength = result.dataLength;
425 return ::NO_ERROR;
426}
427
428int32_t KeyStoreService::grant(const String16& name, int32_t granteeUid) {
429 uid_t callingUid = IPCThreadState::self()->getCallingUid();
430 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
431 if (result != ::NO_ERROR) {
432 return result;
433 }
434
435 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400436 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437
438 if (access(filename.string(), R_OK) == -1) {
439 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
440 }
441
442 mKeyStore->addGrant(filename.string(), granteeUid);
443 return ::NO_ERROR;
444}
445
446int32_t KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
447 uid_t callingUid = IPCThreadState::self()->getCallingUid();
448 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
449 if (result != ::NO_ERROR) {
450 return result;
451 }
452
453 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400454 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455
456 if (access(filename.string(), R_OK) == -1) {
457 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
458 }
459
460 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
461}
462
463int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
464 uid_t targetUid = getEffectiveUid(uid);
465 if (!checkBinderPermission(P_GET, targetUid)) {
466 ALOGW("permission denied for %d: getmtime", targetUid);
467 return -1L;
468 }
469
470 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400471 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472
473 if (access(filename.string(), R_OK) == -1) {
474 ALOGW("could not access %s for getmtime", filename.string());
475 return -1L;
476 }
477
478 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
479 if (fd < 0) {
480 ALOGW("could not open %s for getmtime", filename.string());
481 return -1L;
482 }
483
484 struct stat s;
485 int ret = fstat(fd, &s);
486 close(fd);
487 if (ret == -1) {
488 ALOGW("could not stat %s for getmtime", filename.string());
489 return -1L;
490 }
491
492 return static_cast<int64_t>(s.st_mtime);
493}
494
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400495// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700496int32_t KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
497 int32_t destUid) {
498 uid_t callingUid = IPCThreadState::self()->getCallingUid();
499 pid_t spid = IPCThreadState::self()->getCallingPid();
500 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
501 ALOGW("permission denied for %d: duplicate", callingUid);
502 return -1L;
503 }
504
505 State state = mKeyStore->getState(get_user_id(callingUid));
506 if (!isKeystoreUnlocked(state)) {
507 ALOGD("calling duplicate in state: %d", state);
508 return state;
509 }
510
511 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
512 srcUid = callingUid;
513 } else if (!is_granted_to(callingUid, srcUid)) {
514 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
515 return ::PERMISSION_DENIED;
516 }
517
518 if (destUid == -1) {
519 destUid = callingUid;
520 }
521
522 if (srcUid != destUid) {
523 if (static_cast<uid_t>(srcUid) != callingUid) {
524 ALOGD("can only duplicate from caller to other or to same uid: "
525 "calling=%d, srcUid=%d, destUid=%d",
526 callingUid, srcUid, destUid);
527 return ::PERMISSION_DENIED;
528 }
529
530 if (!is_granted_to(callingUid, destUid)) {
531 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
532 return ::PERMISSION_DENIED;
533 }
534 }
535
536 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400537 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700538
539 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400540 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700541
542 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
543 ALOGD("destination already exists: %s", targetFile.string());
544 return ::SYSTEM_ERROR;
545 }
546
547 Blob keyBlob;
548 ResponseCode responseCode =
549 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
550 if (responseCode != ::NO_ERROR) {
551 return responseCode;
552 }
553
554 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
555}
556
557int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
558 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
559}
560
561int32_t KeyStoreService::clear_uid(int64_t targetUid64) {
562 uid_t targetUid = getEffectiveUid(targetUid64);
563 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
564 return ::PERMISSION_DENIED;
565 }
566
567 String8 prefix = String8::format("%u_", targetUid);
568 Vector<String16> aliases;
569 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
570 return ::SYSTEM_ERROR;
571 }
572
573 for (uint32_t i = 0; i < aliases.size(); i++) {
574 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400575 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700576 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400577
578 // del() will fail silently if no cached characteristics are present for this alias.
579 String8 chr_filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid,
580 ::TYPE_KEY_CHARACTERISTICS));
581 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700582 }
583 return ::NO_ERROR;
584}
585
586int32_t KeyStoreService::addRngEntropy(const uint8_t* data, size_t dataLength) {
Shawn Willden715d0232016-01-21 00:45:13 -0700587 const auto* device = mKeyStore->getDevice();
588 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700589 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
590 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
591 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
592 device->add_rng_entropy != NULL) {
593 devResult = device->add_rng_entropy(device, data, dataLength);
594 }
595 if (fallback->add_rng_entropy) {
596 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
597 }
598 if (devResult) {
599 return devResult;
600 }
601 if (fallbackResult) {
602 return fallbackResult;
603 }
604 return ::NO_ERROR;
605}
606
607int32_t KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
608 const uint8_t* entropy, size_t entropyLength, int uid,
609 int flags, KeyCharacteristics* outCharacteristics) {
610 uid = getEffectiveUid(uid);
611 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
612 if (rc != ::NO_ERROR) {
613 return rc;
614 }
615
616 rc = KM_ERROR_UNIMPLEMENTED;
617 bool isFallback = false;
618 keymaster_key_blob_t blob;
Shawn Willden715d0232016-01-21 00:45:13 -0700619 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620
Shawn Willden715d0232016-01-21 00:45:13 -0700621 const auto* device = mKeyStore->getDevice();
622 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700623 std::vector<keymaster_key_param_t> opParams(params.params);
624 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
625 if (device == NULL) {
626 return ::SYSTEM_ERROR;
627 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400628
629 // Capture characteristics before they're potentially stripped by the device
630 AuthorizationSet keyCharacteristics(opParams.data(), opParams.size());
631 if (keyCharacteristics.is_valid() != AuthorizationSet::Error::OK) {
632 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
633 }
634 UniquePtr<uint8_t[]> kc_buf;
635 kc_buf.reset(new (std::nothrow) uint8_t[keyCharacteristics.SerializedSize()]);
636 if (!kc_buf.get()) {
637 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
638 }
639 keyCharacteristics.Serialize(kc_buf.get(), kc_buf.get() + keyCharacteristics.SerializedSize());
640
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700641 // TODO: Seed from Linux RNG before this.
642 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
643 device->generate_key != NULL) {
644 if (!entropy) {
645 rc = KM_ERROR_OK;
646 } else if (device->add_rng_entropy) {
647 rc = device->add_rng_entropy(device, entropy, entropyLength);
648 } else {
649 rc = KM_ERROR_UNIMPLEMENTED;
650 }
651 if (rc == KM_ERROR_OK) {
Shawn Willden715d0232016-01-21 00:45:13 -0700652 rc =
653 device->generate_key(device, &inParams, &blob, outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700654 }
655 }
656 // If the HW device didn't support generate_key or generate_key failed
657 // fall back to the software implementation.
658 if (rc && fallback->generate_key != NULL) {
659 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
660 isFallback = true;
661 if (!entropy) {
662 rc = KM_ERROR_OK;
663 } else if (fallback->add_rng_entropy) {
664 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
665 } else {
666 rc = KM_ERROR_UNIMPLEMENTED;
667 }
668 if (rc == KM_ERROR_OK) {
Shawn Willden715d0232016-01-21 00:45:13 -0700669 rc = fallback->generate_key(fallback, &inParams, &blob,
670 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700671 }
672 }
673
Shawn Willden715d0232016-01-21 00:45:13 -0700674 if (outCharacteristics) {
675 outCharacteristics->characteristics = out;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700676 }
677
678 if (rc) {
679 return rc;
680 }
681
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400682 // Write the key:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700683 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400684 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700685
686 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
687 keyBlob.setFallback(isFallback);
688 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
689
690 free(const_cast<uint8_t*>(blob.key_material));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400691 rc = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400693 if (rc != ::NO_ERROR) {
694 return rc;
695 }
696
697 // Write the characteristics:
698 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
699
700 Blob charBlob(kc_buf.get(), keyCharacteristics.SerializedSize(),
701 NULL, 0, ::TYPE_KEY_CHARACTERISTICS);
702 charBlob.setFallback(isFallback);
703 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
704
705 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700706}
707
708int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
709 const keymaster_blob_t* clientId,
710 const keymaster_blob_t* appData, int32_t uid,
711 KeyCharacteristics* outCharacteristics) {
712 if (!outCharacteristics) {
713 return KM_ERROR_UNEXPECTED_NULL_POINTER;
714 }
715
716 uid_t targetUid = getEffectiveUid(uid);
717 uid_t callingUid = IPCThreadState::self()->getCallingUid();
718 if (!is_granted_to(callingUid, targetUid)) {
719 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
720 targetUid);
721 return ::PERMISSION_DENIED;
722 }
723
724 Blob keyBlob;
725 String8 name8(name);
726 int rc;
727
728 ResponseCode responseCode =
729 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
730 if (responseCode != ::NO_ERROR) {
731 return responseCode;
732 }
Shawn Willden98c59162016-03-20 09:10:18 -0600733 keymaster_key_blob_t key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
Shawn Willden715d0232016-01-21 00:45:13 -0700734 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willden98c59162016-03-20 09:10:18 -0600735 keymaster_key_characteristics_t out = {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700736 if (!dev->get_key_characteristics) {
Shawn Willden715d0232016-01-21 00:45:13 -0700737 ALOGE("device does not implement get_key_characteristics");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700738 return KM_ERROR_UNIMPLEMENTED;
739 }
740 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Shawn Willden98c59162016-03-20 09:10:18 -0600741 if (rc == KM_ERROR_KEY_REQUIRES_UPGRADE) {
742 AuthorizationSet upgradeParams;
743 if (clientId && clientId->data && clientId->data_length) {
744 upgradeParams.push_back(TAG_APPLICATION_ID, *clientId);
745 }
746 if (appData && appData->data && appData->data_length) {
747 upgradeParams.push_back(TAG_APPLICATION_DATA, *appData);
748 }
749 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
750 if (rc != ::NO_ERROR) {
751 return rc;
752 }
753 key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
754 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
755 }
Shawn Willden715d0232016-01-21 00:45:13 -0700756 if (rc != KM_ERROR_OK) {
757 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700758 }
Shawn Willden715d0232016-01-21 00:45:13 -0700759
760 outCharacteristics->characteristics = out;
761 return ::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700762}
763
764int32_t KeyStoreService::importKey(const String16& name, const KeymasterArguments& params,
765 keymaster_key_format_t format, const uint8_t* keyData,
766 size_t keyLength, int uid, int flags,
767 KeyCharacteristics* outCharacteristics) {
768 uid = getEffectiveUid(uid);
769 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
770 if (rc != ::NO_ERROR) {
771 return rc;
772 }
773
774 rc = KM_ERROR_UNIMPLEMENTED;
775 bool isFallback = false;
776 keymaster_key_blob_t blob;
Shawn Willden715d0232016-01-21 00:45:13 -0700777 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700778
Shawn Willden715d0232016-01-21 00:45:13 -0700779 const auto* device = mKeyStore->getDevice();
780 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781 std::vector<keymaster_key_param_t> opParams(params.params);
782 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
783 const keymaster_blob_t input = {keyData, keyLength};
784 if (device == NULL) {
785 return ::SYSTEM_ERROR;
786 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400787
788 // Capture characteristics before they're potentially stripped
789 AuthorizationSet keyCharacteristics(opParams.data(), opParams.size());
790 if (keyCharacteristics.is_valid() != AuthorizationSet::Error::OK) {
791 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
792 }
793 UniquePtr<uint8_t[]> kc_buf;
794 kc_buf.reset(new (std::nothrow) uint8_t[keyCharacteristics.SerializedSize()]);
795 if (!kc_buf.get()) {
796 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
797 }
798 keyCharacteristics.Serialize(kc_buf.get(), kc_buf.get() + keyCharacteristics.SerializedSize());
799
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700800 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
801 device->import_key != NULL) {
Shawn Willden715d0232016-01-21 00:45:13 -0700802 rc = device->import_key(device, &inParams, format, &input, &blob,
803 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700804 }
805 if (rc && fallback->import_key != NULL) {
806 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
807 isFallback = true;
Shawn Willden715d0232016-01-21 00:45:13 -0700808 rc = fallback->import_key(fallback, &inParams, format, &input, &blob,
809 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700810 }
Shawn Willden715d0232016-01-21 00:45:13 -0700811 if (outCharacteristics) {
812 outCharacteristics->characteristics = out;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813 }
Shawn Willden715d0232016-01-21 00:45:13 -0700814
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700815 if (rc) {
816 return rc;
817 }
818
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400819 // Write the key:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700820 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400821 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822
823 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
824 keyBlob.setFallback(isFallback);
825 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
826
Shawn Willden715d0232016-01-21 00:45:13 -0700827 free(const_cast<uint8_t*>(blob.key_material));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400828 rc = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700829
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400830 if (rc != ::NO_ERROR) {
831 return rc;
832 }
833
834 // Write the characteristics:
835 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
836
837 Blob charBlob(kc_buf.get(), keyCharacteristics.SerializedSize(),
838 NULL, 0, ::TYPE_KEY_CHARACTERISTICS);
839 charBlob.setFallback(isFallback);
840 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
841
842 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700843}
844
845void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
846 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
847 int32_t uid, ExportResult* result) {
848
849 uid_t targetUid = getEffectiveUid(uid);
850 uid_t callingUid = IPCThreadState::self()->getCallingUid();
851 if (!is_granted_to(callingUid, targetUid)) {
852 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
853 result->resultCode = ::PERMISSION_DENIED;
854 return;
855 }
856
857 Blob keyBlob;
858 String8 name8(name);
859 int rc;
860
861 ResponseCode responseCode =
862 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
863 if (responseCode != ::NO_ERROR) {
864 result->resultCode = responseCode;
865 return;
866 }
867 keymaster_key_blob_t key;
868 key.key_material_size = keyBlob.getLength();
869 key.key_material = keyBlob.getValue();
Shawn Willden715d0232016-01-21 00:45:13 -0700870 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700871 if (!dev->export_key) {
872 result->resultCode = KM_ERROR_UNIMPLEMENTED;
873 return;
874 }
875 keymaster_blob_t output = {NULL, 0};
876 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
Ji Wang2c142312016-10-14 17:21:10 +0800877 if (rc == KM_ERROR_KEY_REQUIRES_UPGRADE) {
878 AuthorizationSet upgradeParams;
879 if (clientId && clientId->data && clientId->data_length) {
880 upgradeParams.push_back(TAG_APPLICATION_ID, *clientId);
881 }
882 if (appData && appData->data && appData->data_length) {
883 upgradeParams.push_back(TAG_APPLICATION_DATA, *appData);
884 }
885 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
886 if (rc != ::NO_ERROR) {
887 result->resultCode = rc;
888 return;
889 }
890 key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
891 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
892 }
893
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700894 result->exportData.reset(const_cast<uint8_t*>(output.data));
895 result->dataLength = output.data_length;
896 result->resultCode = rc ? rc : ::NO_ERROR;
897}
898
899void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
900 keymaster_purpose_t purpose, bool pruneable,
901 const KeymasterArguments& params, const uint8_t* entropy,
902 size_t entropyLength, int32_t uid, OperationResult* result) {
903 uid_t callingUid = IPCThreadState::self()->getCallingUid();
904 uid_t targetUid = getEffectiveUid(uid);
905 if (!is_granted_to(callingUid, targetUid)) {
906 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
907 result->resultCode = ::PERMISSION_DENIED;
908 return;
909 }
910 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
911 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
912 result->resultCode = ::PERMISSION_DENIED;
913 return;
914 }
915 if (!checkAllowedOperationParams(params.params)) {
916 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
917 return;
918 }
919 Blob keyBlob;
920 String8 name8(name);
921 ResponseCode responseCode =
922 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
923 if (responseCode != ::NO_ERROR) {
924 result->resultCode = responseCode;
925 return;
926 }
927 keymaster_key_blob_t key;
928 key.key_material_size = keyBlob.getLength();
929 key.key_material = keyBlob.getValue();
930 keymaster_operation_handle_t handle;
Shawn Willden715d0232016-01-21 00:45:13 -0700931 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700932 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
933 std::vector<keymaster_key_param_t> opParams(params.params);
934 Unique_keymaster_key_characteristics characteristics;
935 characteristics.reset(new keymaster_key_characteristics_t);
936 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
Shawn Willden98c59162016-03-20 09:10:18 -0600937 if (err == KM_ERROR_KEY_REQUIRES_UPGRADE) {
938 int32_t rc = upgradeKeyBlob(name, targetUid,
939 AuthorizationSet(opParams.data(), opParams.size()), &keyBlob);
940 if (rc != ::NO_ERROR) {
941 result->resultCode = rc;
942 return;
943 }
944 key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
945 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
946 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700947 if (err) {
948 result->resultCode = err;
949 return;
950 }
951 const hw_auth_token_t* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400952
953 // Merge these characteristics with the ones cached when the key was generated or imported
954 Blob charBlob;
955 AuthorizationSet persistedCharacteristics;
956 responseCode = mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
957 if (responseCode == ::NO_ERROR) {
958 const uint8_t* serializedCharacteristics = charBlob.getValue();
959 persistedCharacteristics.Deserialize(&serializedCharacteristics,
960 serializedCharacteristics + charBlob.getLength());
961 } else {
962 ALOGD("Unable to read cached characteristics for key");
963 }
964
965 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
966 persistedCharacteristics.Union(characteristics.get()->sw_enforced);
967 persistedCharacteristics.Difference(characteristics.get()->hw_enforced);
968 persistedCharacteristics.CopyToParamSet(&characteristics.get()->sw_enforced);
969
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700970 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
971 /*failOnTokenMissing*/ false);
972 // If per-operation auth is needed we need to begin the operation and
973 // the client will need to authorize that operation before calling
974 // update. Any other auth issues stop here.
975 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
976 result->resultCode = authResult;
977 return;
978 }
979 addAuthToParams(&opParams, authToken);
980 // Add entropy to the device first.
981 if (entropy) {
982 if (dev->add_rng_entropy) {
983 err = dev->add_rng_entropy(dev, entropy, entropyLength);
984 } else {
985 err = KM_ERROR_UNIMPLEMENTED;
986 }
987 if (err) {
988 result->resultCode = err;
989 return;
990 }
991 }
992 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
993
994 // Create a keyid for this key.
995 keymaster::km_id_t keyid;
996 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
997 ALOGE("Failed to create a key ID for authorization checking.");
998 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
999 return;
1000 }
1001
1002 // Check that all key authorization policy requirements are met.
1003 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1004 key_auths.push_back(characteristics->sw_enforced);
1005 keymaster::AuthorizationSet operation_params(inParams);
1006 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
1007 0 /* op_handle */, true /* is_begin_operation */);
1008 if (err) {
1009 result->resultCode = err;
1010 return;
1011 }
1012
1013 keymaster_key_param_set_t outParams = {NULL, 0};
1014
1015 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
1016 // pruneable.
1017 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1018 ALOGD("Reached or exceeded concurrent operations limit");
1019 if (!pruneOperation()) {
1020 break;
1021 }
1022 }
1023
1024 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
1025 if (err != KM_ERROR_OK) {
1026 ALOGE("Got error %d from begin()", err);
1027 }
1028
1029 // If there are too many operations abort the oldest operation that was
1030 // started as pruneable and try again.
1031 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1032 ALOGE("Ran out of operation handles");
1033 if (!pruneOperation()) {
1034 break;
1035 }
1036 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
1037 }
1038 if (err) {
1039 result->resultCode = err;
1040 return;
1041 }
1042
1043 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev, appToken,
1044 characteristics.release(), pruneable);
1045 if (authToken) {
1046 mOperationMap.setOperationAuthToken(operationToken, authToken);
1047 }
1048 // Return the authentication lookup result. If this is a per operation
1049 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1050 // application should get an auth token using the handle before the
1051 // first call to update, which will fail if keystore hasn't received the
1052 // auth token.
1053 result->resultCode = authResult;
1054 result->token = operationToken;
1055 result->handle = handle;
1056 if (outParams.params) {
1057 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1058 free(outParams.params);
1059 }
1060}
1061
1062void KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1063 const uint8_t* data, size_t dataLength, OperationResult* result) {
1064 if (!checkAllowedOperationParams(params.params)) {
1065 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
1066 return;
1067 }
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 keymaster_purpose_t purpose;
1071 keymaster::km_id_t keyid;
1072 const keymaster_key_characteristics_t* characteristics;
1073 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1074 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
1075 return;
1076 }
1077 std::vector<keymaster_key_param_t> opParams(params.params);
1078 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
1079 if (authResult != ::NO_ERROR) {
1080 result->resultCode = authResult;
1081 return;
1082 }
1083 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1084 keymaster_blob_t input = {data, dataLength};
1085 size_t consumed = 0;
1086 keymaster_blob_t output = {NULL, 0};
1087 keymaster_key_param_set_t outParams = {NULL, 0};
1088
1089 // Check that all key authorization policy requirements are met.
1090 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1091 key_auths.push_back(characteristics->sw_enforced);
1092 keymaster::AuthorizationSet operation_params(inParams);
1093 result->resultCode = enforcement_policy.AuthorizeOperation(
1094 purpose, keyid, key_auths, operation_params, handle, false /* is_begin_operation */);
1095 if (result->resultCode) {
1096 return;
1097 }
1098
1099 keymaster_error_t err =
1100 dev->update(dev, handle, &inParams, &input, &consumed, &outParams, &output);
1101 result->data.reset(const_cast<uint8_t*>(output.data));
1102 result->dataLength = output.data_length;
1103 result->inputConsumed = consumed;
1104 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1105 if (outParams.params) {
1106 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1107 free(outParams.params);
1108 }
1109}
1110
1111void KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1112 const uint8_t* signature, size_t signatureLength,
1113 const uint8_t* entropy, size_t entropyLength,
1114 OperationResult* result) {
1115 if (!checkAllowedOperationParams(params.params)) {
1116 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
1117 return;
1118 }
Shawn Willden715d0232016-01-21 00:45:13 -07001119 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001120 keymaster_operation_handle_t handle;
1121 keymaster_purpose_t purpose;
1122 keymaster::km_id_t keyid;
1123 const keymaster_key_characteristics_t* characteristics;
1124 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1125 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
1126 return;
1127 }
1128 std::vector<keymaster_key_param_t> opParams(params.params);
1129 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
1130 if (authResult != ::NO_ERROR) {
1131 result->resultCode = authResult;
1132 return;
1133 }
1134 keymaster_error_t err;
1135 if (entropy) {
1136 if (dev->add_rng_entropy) {
1137 err = dev->add_rng_entropy(dev, entropy, entropyLength);
1138 } else {
1139 err = KM_ERROR_UNIMPLEMENTED;
1140 }
1141 if (err) {
1142 result->resultCode = err;
1143 return;
1144 }
1145 }
1146
1147 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Shawn Willden715d0232016-01-21 00:45:13 -07001148 keymaster_blob_t input = {nullptr, 0};
1149 keymaster_blob_t sig = {signature, signatureLength};
1150 keymaster_blob_t output = {nullptr, 0};
1151 keymaster_key_param_set_t outParams = {nullptr, 0};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001152
1153 // Check that all key authorization policy requirements are met.
1154 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1155 key_auths.push_back(characteristics->sw_enforced);
1156 keymaster::AuthorizationSet operation_params(inParams);
1157 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params, handle,
1158 false /* is_begin_operation */);
1159 if (err) {
1160 result->resultCode = err;
1161 return;
1162 }
1163
Shawn Willden715d0232016-01-21 00:45:13 -07001164 err =
1165 dev->finish(dev, handle, &inParams, &input /* TODO(swillden): wire up input to finish() */,
1166 &sig, &outParams, &output);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001167 // Remove the operation regardless of the result
1168 mOperationMap.removeOperation(token);
1169 mAuthTokenTable.MarkCompleted(handle);
1170
1171 result->data.reset(const_cast<uint8_t*>(output.data));
1172 result->dataLength = output.data_length;
1173 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1174 if (outParams.params) {
1175 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1176 free(outParams.params);
1177 }
1178}
1179
1180int32_t KeyStoreService::abort(const sp<IBinder>& token) {
Shawn Willden715d0232016-01-21 00:45:13 -07001181 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001182 keymaster_operation_handle_t handle;
1183 keymaster_purpose_t purpose;
1184 keymaster::km_id_t keyid;
1185 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
1186 return KM_ERROR_INVALID_OPERATION_HANDLE;
1187 }
1188 mOperationMap.removeOperation(token);
1189 int32_t rc;
1190 if (!dev->abort) {
1191 rc = KM_ERROR_UNIMPLEMENTED;
1192 } else {
1193 rc = dev->abort(dev, handle);
1194 }
1195 mAuthTokenTable.MarkCompleted(handle);
1196 if (rc) {
1197 return rc;
1198 }
1199 return ::NO_ERROR;
1200}
1201
1202bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Shawn Willden715d0232016-01-21 00:45:13 -07001203 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001204 keymaster_operation_handle_t handle;
1205 const keymaster_key_characteristics_t* characteristics;
1206 keymaster_purpose_t purpose;
1207 keymaster::km_id_t keyid;
1208 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1209 return false;
1210 }
1211 const hw_auth_token_t* authToken = NULL;
1212 mOperationMap.getOperationAuthToken(token, &authToken);
1213 std::vector<keymaster_key_param_t> ignored;
1214 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1215 return authResult == ::NO_ERROR;
1216}
1217
1218int32_t KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1219 if (!checkBinderPermission(P_ADD_AUTH)) {
1220 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
1221 return ::PERMISSION_DENIED;
1222 }
1223 if (length != sizeof(hw_auth_token_t)) {
1224 return KM_ERROR_INVALID_ARGUMENT;
1225 }
1226 hw_auth_token_t* authToken = new hw_auth_token_t;
1227 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
1228 // The table takes ownership of authToken.
1229 mAuthTokenTable.AddAuthenticationToken(authToken);
1230 return ::NO_ERROR;
1231}
1232
Shawn Willden50eb1b22016-01-21 12:41:23 -07001233int32_t KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1234 KeymasterCertificateChain* outChain) {
1235 if (!outChain)
1236 return KM_ERROR_OUTPUT_PARAMETER_NULL;
1237
1238 if (!checkAllowedOperationParams(params.params)) {
1239 return KM_ERROR_INVALID_ARGUMENT;
1240 }
1241
1242 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1243
1244 Blob keyBlob;
1245 String8 name8(name);
1246 ResponseCode responseCode =
1247 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1248 if (responseCode != ::NO_ERROR) {
1249 return responseCode;
1250 }
1251
1252 keymaster_key_blob_t key = {keyBlob.getValue(),
1253 static_cast<size_t>(std::max(0, keyBlob.getLength()))};
1254 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
1255 if (!dev->attest_key)
1256 return KM_ERROR_UNIMPLEMENTED;
1257
1258 const keymaster_key_param_set_t in_params = {
1259 const_cast<keymaster_key_param_t*>(params.params.data()), params.params.size()};
1260 outChain->chain = {nullptr, 0};
1261 int32_t rc = dev->attest_key(dev, &key, &in_params, &outChain->chain);
1262 if (rc)
1263 return rc;
1264 return ::NO_ERROR;
1265}
1266
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001267int32_t KeyStoreService::onDeviceOffBody() {
1268 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1269 mAuthTokenTable.onDeviceOffBody();
1270 return ::NO_ERROR;
1271}
1272
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001273/**
1274 * Prune the oldest pruneable operation.
1275 */
1276bool KeyStoreService::pruneOperation() {
1277 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1278 ALOGD("Trying to prune operation %p", oldest.get());
1279 size_t op_count_before_abort = mOperationMap.getOperationCount();
1280 // We mostly ignore errors from abort() because all we care about is whether at least
1281 // one operation has been removed.
1282 int abort_error = abort(oldest);
1283 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1284 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1285 return false;
1286 }
1287 return true;
1288}
1289
1290/**
1291 * Get the effective target uid for a binder operation that takes an
1292 * optional uid as the target.
1293 */
1294uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1295 if (targetUid == UID_SELF) {
1296 return IPCThreadState::self()->getCallingUid();
1297 }
1298 return static_cast<uid_t>(targetUid);
1299}
1300
1301/**
1302 * Check if the caller of the current binder method has the required
1303 * permission and if acting on other uids the grants to do so.
1304 */
1305bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1306 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1307 pid_t spid = IPCThreadState::self()->getCallingPid();
1308 if (!has_permission(callingUid, permission, spid)) {
1309 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1310 return false;
1311 }
1312 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1313 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1314 return false;
1315 }
1316 return true;
1317}
1318
1319/**
1320 * Check if the caller of the current binder method has the required
1321 * permission and the target uid is the caller or the caller is system.
1322 */
1323bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1324 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1325 pid_t spid = IPCThreadState::self()->getCallingPid();
1326 if (!has_permission(callingUid, permission, spid)) {
1327 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1328 return false;
1329 }
1330 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1331}
1332
1333/**
1334 * Check if the caller of the current binder method has the required
1335 * permission or the target of the operation is the caller's uid. This is
1336 * for operation where the permission is only for cross-uid activity and all
1337 * uids are allowed to act on their own (ie: clearing all entries for a
1338 * given uid).
1339 */
1340bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1341 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1342 if (getEffectiveUid(targetUid) == callingUid) {
1343 return true;
1344 } else {
1345 return checkBinderPermission(permission, targetUid);
1346 }
1347}
1348
1349/**
1350 * Helper method to check that the caller has the required permission as
1351 * well as the keystore is in the unlocked state if checkUnlocked is true.
1352 *
1353 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1354 * otherwise the state of keystore when not unlocked and checkUnlocked is
1355 * true.
1356 */
1357int32_t KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1358 bool checkUnlocked) {
1359 if (!checkBinderPermission(permission, targetUid)) {
1360 return ::PERMISSION_DENIED;
1361 }
1362 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1363 if (checkUnlocked && !isKeystoreUnlocked(state)) {
1364 return state;
1365 }
1366
1367 return ::NO_ERROR;
1368}
1369
1370bool KeyStoreService::isKeystoreUnlocked(State state) {
1371 switch (state) {
1372 case ::STATE_NO_ERROR:
1373 return true;
1374 case ::STATE_UNINITIALIZED:
1375 case ::STATE_LOCKED:
1376 return false;
1377 }
1378 return false;
1379}
1380
Shawn Willden715d0232016-01-21 00:45:13 -07001381bool KeyStoreService::isKeyTypeSupported(const keymaster2_device_t* device,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001382 keymaster_keypair_t keyType) {
1383 const int32_t device_api = device->common.module->module_api_version;
1384 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
1385 switch (keyType) {
1386 case TYPE_RSA:
1387 case TYPE_DSA:
1388 case TYPE_EC:
1389 return true;
1390 default:
1391 return false;
1392 }
1393 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
1394 switch (keyType) {
1395 case TYPE_RSA:
1396 return true;
1397 case TYPE_DSA:
1398 return device->flags & KEYMASTER_SUPPORTS_DSA;
1399 case TYPE_EC:
1400 return device->flags & KEYMASTER_SUPPORTS_EC;
1401 default:
1402 return false;
1403 }
1404 } else {
1405 return keyType == TYPE_RSA;
1406 }
1407}
1408
1409/**
1410 * Check that all keymaster_key_param_t's provided by the application are
1411 * allowed. Any parameter that keystore adds itself should be disallowed here.
1412 */
1413bool KeyStoreService::checkAllowedOperationParams(
1414 const std::vector<keymaster_key_param_t>& params) {
1415 for (auto param : params) {
1416 switch (param.tag) {
1417 case KM_TAG_AUTH_TOKEN:
1418 return false;
1419 default:
1420 break;
1421 }
1422 }
1423 return true;
1424}
1425
1426keymaster_error_t KeyStoreService::getOperationCharacteristics(
Shawn Willden715d0232016-01-21 00:45:13 -07001427 const keymaster_key_blob_t& key, const keymaster2_device_t* dev,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001428 const std::vector<keymaster_key_param_t>& params, keymaster_key_characteristics_t* out) {
1429 UniquePtr<keymaster_blob_t> appId;
1430 UniquePtr<keymaster_blob_t> appData;
1431 for (auto param : params) {
1432 if (param.tag == KM_TAG_APPLICATION_ID) {
1433 appId.reset(new keymaster_blob_t);
1434 appId->data = param.blob.data;
1435 appId->data_length = param.blob.data_length;
1436 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
1437 appData.reset(new keymaster_blob_t);
1438 appData->data = param.blob.data;
1439 appData->data_length = param.blob.data_length;
1440 }
1441 }
Shawn Willden715d0232016-01-21 00:45:13 -07001442 keymaster_key_characteristics_t result = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001443 if (!dev->get_key_characteristics) {
1444 return KM_ERROR_UNIMPLEMENTED;
1445 }
1446 keymaster_error_t error =
1447 dev->get_key_characteristics(dev, &key, appId.get(), appData.get(), &result);
Shawn Willden715d0232016-01-21 00:45:13 -07001448 if (error == KM_ERROR_OK) {
1449 *out = result;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001450 }
1451 return error;
1452}
1453
1454/**
1455 * Get the auth token for this operation from the auth token table.
1456 *
1457 * Returns ::NO_ERROR if the auth token was set or none was required.
1458 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1459 * authorization token exists for that operation and
1460 * failOnTokenMissing is false.
1461 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1462 * token for the operation
1463 */
1464int32_t KeyStoreService::getAuthToken(const keymaster_key_characteristics_t* characteristics,
1465 keymaster_operation_handle_t handle,
1466 keymaster_purpose_t purpose,
1467 const hw_auth_token_t** authToken, bool failOnTokenMissing) {
1468
1469 std::vector<keymaster_key_param_t> allCharacteristics;
1470 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1471 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
1472 }
1473 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1474 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
1475 }
1476 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1477 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
1478 switch (err) {
1479 case keymaster::AuthTokenTable::OK:
1480 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
1481 return ::NO_ERROR;
1482 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1483 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
1484 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1485 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
1486 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
1487 return failOnTokenMissing ? (int32_t)KM_ERROR_KEY_USER_NOT_AUTHENTICATED
1488 : (int32_t)::OP_AUTH_NEEDED;
1489 default:
1490 ALOGE("Unexpected FindAuthorization return value %d", err);
1491 return KM_ERROR_INVALID_ARGUMENT;
1492 }
1493}
1494
1495inline void KeyStoreService::addAuthToParams(std::vector<keymaster_key_param_t>* params,
1496 const hw_auth_token_t* token) {
1497 if (token) {
1498 params->push_back(keymaster_param_blob(
1499 KM_TAG_AUTH_TOKEN, reinterpret_cast<const uint8_t*>(token), sizeof(hw_auth_token_t)));
1500 }
1501}
1502
1503/**
1504 * Add the auth token for the operation to the param list if the operation
1505 * requires authorization. Uses the cached result in the OperationMap if available
1506 * otherwise gets the token from the AuthTokenTable and caches the result.
1507 *
1508 * Returns ::NO_ERROR if the auth token was added or not needed.
1509 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1510 * authenticated.
1511 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1512 * operation token.
1513 */
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -07001514int32_t KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001515 std::vector<keymaster_key_param_t>* params) {
1516 const hw_auth_token_t* authToken = NULL;
1517 mOperationMap.getOperationAuthToken(token, &authToken);
1518 if (!authToken) {
Shawn Willden715d0232016-01-21 00:45:13 -07001519 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001520 keymaster_operation_handle_t handle;
1521 const keymaster_key_characteristics_t* characteristics = NULL;
1522 keymaster_purpose_t purpose;
1523 keymaster::km_id_t keyid;
1524 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1525 return KM_ERROR_INVALID_OPERATION_HANDLE;
1526 }
1527 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
1528 if (result != ::NO_ERROR) {
1529 return result;
1530 }
1531 if (authToken) {
1532 mOperationMap.setOperationAuthToken(token, authToken);
1533 }
1534 }
1535 addAuthToParams(params, authToken);
1536 return ::NO_ERROR;
1537}
1538
1539/**
1540 * Translate a result value to a legacy return value. All keystore errors are
1541 * preserved and keymaster errors become SYSTEM_ERRORs
1542 */
1543int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
1544 if (result > 0) {
1545 return result;
1546 }
1547 return ::SYSTEM_ERROR;
1548}
1549
1550keymaster_key_param_t*
1551KeyStoreService::getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
1552 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1553 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1554 return &characteristics->hw_enforced.params[i];
1555 }
1556 }
1557 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1558 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1559 return &characteristics->sw_enforced.params[i];
1560 }
1561 }
1562 return NULL;
1563}
1564
1565void KeyStoreService::addLegacyBeginParams(const String16& name,
1566 std::vector<keymaster_key_param_t>& params) {
1567 // All legacy keys are DIGEST_NONE/PAD_NONE.
1568 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
1569 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
1570
1571 // Look up the algorithm of the key.
1572 KeyCharacteristics characteristics;
1573 int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
1574 if (rc != ::NO_ERROR) {
1575 ALOGE("Failed to get key characteristics");
1576 return;
1577 }
1578 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
1579 if (!algorithm) {
1580 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1581 return;
1582 }
1583 params.push_back(*algorithm);
1584}
1585
1586int32_t KeyStoreService::doLegacySignVerify(const String16& name, const uint8_t* data,
1587 size_t length, uint8_t** out, size_t* outLength,
1588 const uint8_t* signature, size_t signatureLength,
1589 keymaster_purpose_t purpose) {
1590
1591 std::basic_stringstream<uint8_t> outBuffer;
1592 OperationResult result;
1593 KeymasterArguments inArgs;
1594 addLegacyBeginParams(name, inArgs.params);
1595 sp<IBinder> appToken(new BBinder);
1596 sp<IBinder> token;
1597
1598 begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
1599 if (result.resultCode != ResponseCode::NO_ERROR) {
1600 if (result.resultCode == ::KEY_NOT_FOUND) {
1601 ALOGW("Key not found");
1602 } else {
1603 ALOGW("Error in begin: %d", result.resultCode);
1604 }
1605 return translateResultToLegacyResult(result.resultCode);
1606 }
1607 inArgs.params.clear();
1608 token = result.token;
1609 size_t consumed = 0;
1610 size_t lastConsumed = 0;
1611 do {
1612 update(token, inArgs, data + consumed, length - consumed, &result);
1613 if (result.resultCode != ResponseCode::NO_ERROR) {
1614 ALOGW("Error in update: %d", result.resultCode);
1615 return translateResultToLegacyResult(result.resultCode);
1616 }
1617 if (out) {
1618 outBuffer.write(result.data.get(), result.dataLength);
1619 }
1620 lastConsumed = result.inputConsumed;
1621 consumed += lastConsumed;
1622 } while (consumed < length && lastConsumed > 0);
1623
1624 if (consumed != length) {
1625 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
1626 return ::SYSTEM_ERROR;
1627 }
1628
1629 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
1630 if (result.resultCode != ResponseCode::NO_ERROR) {
1631 ALOGW("Error in finish: %d", result.resultCode);
1632 return translateResultToLegacyResult(result.resultCode);
1633 }
1634 if (out) {
1635 outBuffer.write(result.data.get(), result.dataLength);
1636 }
1637
1638 if (out) {
1639 auto buf = outBuffer.str();
1640 *out = new uint8_t[buf.size()];
1641 memcpy(*out, buf.c_str(), buf.size());
1642 *outLength = buf.size();
1643 }
1644
1645 return ::NO_ERROR;
1646}
1647
Shawn Willden98c59162016-03-20 09:10:18 -06001648int32_t KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1649 const AuthorizationSet& params, Blob* blob) {
1650 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1651 String8 name8(name);
1652 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1653 if (responseCode != ::NO_ERROR) {
1654 return responseCode;
1655 }
1656
1657 keymaster_key_blob_t key = {blob->getValue(), static_cast<size_t>(blob->getLength())};
1658 auto* dev = mKeyStore->getDeviceForBlob(*blob);
1659 keymaster_key_blob_t upgraded_key;
1660 int32_t rc = dev->upgrade_key(dev, &key, &params, &upgraded_key);
1661 if (rc != KM_ERROR_OK) {
1662 return rc;
1663 }
1664 UniquePtr<uint8_t, Malloc_Delete> upgraded_key_deleter(
1665 const_cast<uint8_t*>(upgraded_key.key_material));
1666
Ji Wang2f7db312016-10-14 17:49:16 +08001667 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1668 rc = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
Shawn Willden98c59162016-03-20 09:10:18 -06001669 if (rc != ::NO_ERROR) {
1670 return rc;
1671 }
1672
Shawn Willden98c59162016-03-20 09:10:18 -06001673 Blob newBlob(upgraded_key.key_material, upgraded_key.key_material_size, nullptr /* info */,
1674 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1675 newBlob.setFallback(blob->isFallback());
1676 newBlob.setEncrypted(blob->isEncrypted());
1677
1678 rc = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1679
1680 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1681 responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1682 if (responseCode != ::NO_ERROR) {
1683 return responseCode;
1684 }
1685
1686 return rc;
1687}
1688
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001689} // namespace android