blob: 5b15e4bedb8e0e0e7f60be5488f0ccdcc6da6106 [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);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400104 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700105
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);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400118 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
119 int32_t result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
120 if (result != ::NO_ERROR) {
121 return result;
122 }
123
124 // Also delete any characteristics files
125 String8 chrFilename(mKeyStore->getKeyNameForUidWithDir(
126 name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
127 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700128}
129
130int32_t KeyStoreService::exist(const String16& name, int targetUid) {
131 targetUid = getEffectiveUid(targetUid);
132 if (!checkBinderPermission(P_EXIST, targetUid)) {
133 return ::PERMISSION_DENIED;
134 }
135
136 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400137 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700138
139 if (access(filename.string(), R_OK) == -1) {
140 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
141 }
142 return ::NO_ERROR;
143}
144
145int32_t KeyStoreService::list(const String16& prefix, int targetUid, Vector<String16>* matches) {
146 targetUid = getEffectiveUid(targetUid);
147 if (!checkBinderPermission(P_LIST, targetUid)) {
148 return ::PERMISSION_DENIED;
149 }
150 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400151 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152
153 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
154 return ::SYSTEM_ERROR;
155 }
156 return ::NO_ERROR;
157}
158
159int32_t KeyStoreService::reset() {
160 if (!checkBinderPermission(P_RESET)) {
161 return ::PERMISSION_DENIED;
162 }
163
164 uid_t callingUid = IPCThreadState::self()->getCallingUid();
165 mKeyStore->resetUser(get_user_id(callingUid), false);
166 return ::NO_ERROR;
167}
168
169int32_t KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password) {
170 if (!checkBinderPermission(P_PASSWORD)) {
171 return ::PERMISSION_DENIED;
172 }
173
174 const String8 password8(password);
175 // Flush the auth token table to prevent stale tokens from sticking
176 // around.
177 mAuthTokenTable.Clear();
178
179 if (password.size() == 0) {
180 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
181 mKeyStore->resetUser(userId, true);
182 return ::NO_ERROR;
183 } else {
184 switch (mKeyStore->getState(userId)) {
185 case ::STATE_UNINITIALIZED: {
186 // generate master key, encrypt with password, write to file,
187 // initialize mMasterKey*.
188 return mKeyStore->initializeUser(password8, userId);
189 }
190 case ::STATE_NO_ERROR: {
191 // rewrite master key with new password.
192 return mKeyStore->writeMasterKey(password8, userId);
193 }
194 case ::STATE_LOCKED: {
195 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
196 mKeyStore->resetUser(userId, true);
197 return mKeyStore->initializeUser(password8, userId);
198 }
199 }
200 return ::SYSTEM_ERROR;
201 }
202}
203
204int32_t KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
205 if (!checkBinderPermission(P_USER_CHANGED)) {
206 return ::PERMISSION_DENIED;
207 }
208
209 // Sanity check that the new user has an empty keystore.
210 if (!mKeyStore->isEmpty(userId)) {
211 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
212 }
213 // Unconditionally clear the keystore, just to be safe.
214 mKeyStore->resetUser(userId, false);
215 if (parentId != -1) {
216 // This profile must share the same master key password as the parent profile. Because the
217 // password of the parent profile is not known here, the best we can do is copy the parent's
218 // master key and master key file. This makes this profile use the same master key as the
219 // parent profile, forever.
220 return mKeyStore->copyMasterKey(parentId, userId);
221 } else {
222 return ::NO_ERROR;
223 }
224}
225
226int32_t KeyStoreService::onUserRemoved(int32_t userId) {
227 if (!checkBinderPermission(P_USER_CHANGED)) {
228 return ::PERMISSION_DENIED;
229 }
230
231 mKeyStore->resetUser(userId, false);
232 return ::NO_ERROR;
233}
234
235int32_t KeyStoreService::lock(int32_t userId) {
236 if (!checkBinderPermission(P_LOCK)) {
237 return ::PERMISSION_DENIED;
238 }
239
240 State state = mKeyStore->getState(userId);
241 if (state != ::STATE_NO_ERROR) {
242 ALOGD("calling lock in state: %d", state);
243 return state;
244 }
245
246 mKeyStore->lock(userId);
247 return ::NO_ERROR;
248}
249
250int32_t KeyStoreService::unlock(int32_t userId, const String16& pw) {
251 if (!checkBinderPermission(P_UNLOCK)) {
252 return ::PERMISSION_DENIED;
253 }
254
255 State state = mKeyStore->getState(userId);
256 if (state != ::STATE_LOCKED) {
257 switch (state) {
258 case ::STATE_NO_ERROR:
259 ALOGI("calling unlock when already unlocked, ignoring.");
260 break;
261 case ::STATE_UNINITIALIZED:
262 ALOGE("unlock called on uninitialized keystore.");
263 break;
264 default:
265 ALOGE("unlock called on keystore in unknown state: %d", state);
266 break;
267 }
268 return state;
269 }
270
271 const String8 password8(pw);
272 // read master key, decrypt with password, initialize mMasterKey*.
273 return mKeyStore->readMasterKey(password8, userId);
274}
275
276bool KeyStoreService::isEmpty(int32_t userId) {
277 if (!checkBinderPermission(P_IS_EMPTY)) {
278 return false;
279 }
280
281 return mKeyStore->isEmpty(userId);
282}
283
284int32_t KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
285 int32_t keySize, int32_t flags, Vector<sp<KeystoreArg>>* args) {
286 targetUid = getEffectiveUid(targetUid);
287 int32_t result =
288 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
289 if (result != ::NO_ERROR) {
290 return result;
291 }
292
293 KeymasterArguments params;
294 add_legacy_key_authorizations(keyType, &params.params);
295
296 switch (keyType) {
297 case EVP_PKEY_EC: {
298 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
299 if (keySize == -1) {
300 keySize = EC_DEFAULT_KEY_SIZE;
301 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
302 ALOGI("invalid key size %d", keySize);
303 return ::SYSTEM_ERROR;
304 }
305 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
306 break;
307 }
308 case EVP_PKEY_RSA: {
309 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
310 if (keySize == -1) {
311 keySize = RSA_DEFAULT_KEY_SIZE;
312 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
313 ALOGI("invalid key size %d", keySize);
314 return ::SYSTEM_ERROR;
315 }
316 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
317 unsigned long exponent = RSA_DEFAULT_EXPONENT;
318 if (args->size() > 1) {
319 ALOGI("invalid number of arguments: %zu", args->size());
320 return ::SYSTEM_ERROR;
321 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700322 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700323 if (expArg != NULL) {
324 Unique_BIGNUM pubExpBn(BN_bin2bn(
325 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
326 if (pubExpBn.get() == NULL) {
327 ALOGI("Could not convert public exponent to BN");
328 return ::SYSTEM_ERROR;
329 }
330 exponent = BN_get_word(pubExpBn.get());
331 if (exponent == 0xFFFFFFFFL) {
332 ALOGW("cannot represent public exponent as a long value");
333 return ::SYSTEM_ERROR;
334 }
335 } else {
336 ALOGW("public exponent not read");
337 return ::SYSTEM_ERROR;
338 }
339 }
340 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, exponent));
341 break;
342 }
343 default: {
344 ALOGW("Unsupported key type %d", keyType);
345 return ::SYSTEM_ERROR;
346 }
347 }
348
349 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
350 /*outCharacteristics*/ NULL);
351 if (rc != ::NO_ERROR) {
352 ALOGW("generate failed: %d", rc);
353 }
354 return translateResultToLegacyResult(rc);
355}
356
357int32_t KeyStoreService::import(const String16& name, const uint8_t* data, size_t length,
358 int targetUid, int32_t flags) {
359 const uint8_t* ptr = data;
360
361 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
362 if (!pkcs8.get()) {
363 return ::SYSTEM_ERROR;
364 }
365 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
366 if (!pkey.get()) {
367 return ::SYSTEM_ERROR;
368 }
369 int type = EVP_PKEY_type(pkey->type);
370 KeymasterArguments params;
371 add_legacy_key_authorizations(type, &params.params);
372 switch (type) {
373 case EVP_PKEY_RSA:
374 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
375 break;
376 case EVP_PKEY_EC:
377 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
378 break;
379 default:
380 ALOGW("Unsupported key type %d", type);
381 return ::SYSTEM_ERROR;
382 }
383 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
384 /*outCharacteristics*/ NULL);
385 if (rc != ::NO_ERROR) {
386 ALOGW("importKey failed: %d", rc);
387 }
388 return translateResultToLegacyResult(rc);
389}
390
391int32_t KeyStoreService::sign(const String16& name, const uint8_t* data, size_t length,
392 uint8_t** out, size_t* outLength) {
393 if (!checkBinderPermission(P_SIGN)) {
394 return ::PERMISSION_DENIED;
395 }
396 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
397}
398
399int32_t KeyStoreService::verify(const String16& name, const uint8_t* data, size_t dataLength,
400 const uint8_t* signature, size_t signatureLength) {
401 if (!checkBinderPermission(P_VERIFY)) {
402 return ::PERMISSION_DENIED;
403 }
404 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
405 KM_PURPOSE_VERIFY);
406}
407
408/*
409 * TODO: The abstraction between things stored in hardware and regular blobs
410 * of data stored on the filesystem should be moved down to keystore itself.
411 * Unfortunately the Java code that calls this has naming conventions that it
412 * knows about. Ideally keystore shouldn't be used to store random blobs of
413 * data.
414 *
415 * Until that happens, it's necessary to have a separate "get_pubkey" and
416 * "del_key" since the Java code doesn't really communicate what it's
417 * intentions are.
418 */
419int32_t KeyStoreService::get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
420 ExportResult result;
421 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, UID_SELF, &result);
422 if (result.resultCode != ::NO_ERROR) {
423 ALOGW("export failed: %d", result.resultCode);
424 return translateResultToLegacyResult(result.resultCode);
425 }
426
427 *pubkey = result.exportData.release();
428 *pubkeyLength = result.dataLength;
429 return ::NO_ERROR;
430}
431
432int32_t KeyStoreService::grant(const String16& name, int32_t granteeUid) {
433 uid_t callingUid = IPCThreadState::self()->getCallingUid();
434 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
435 if (result != ::NO_ERROR) {
436 return result;
437 }
438
439 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400440 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441
442 if (access(filename.string(), R_OK) == -1) {
443 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
444 }
445
446 mKeyStore->addGrant(filename.string(), granteeUid);
447 return ::NO_ERROR;
448}
449
450int32_t KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
451 uid_t callingUid = IPCThreadState::self()->getCallingUid();
452 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
453 if (result != ::NO_ERROR) {
454 return result;
455 }
456
457 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400458 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459
460 if (access(filename.string(), R_OK) == -1) {
461 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
462 }
463
464 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
465}
466
467int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
468 uid_t targetUid = getEffectiveUid(uid);
469 if (!checkBinderPermission(P_GET, targetUid)) {
470 ALOGW("permission denied for %d: getmtime", targetUid);
471 return -1L;
472 }
473
474 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400475 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476
477 if (access(filename.string(), R_OK) == -1) {
478 ALOGW("could not access %s for getmtime", filename.string());
479 return -1L;
480 }
481
482 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
483 if (fd < 0) {
484 ALOGW("could not open %s for getmtime", filename.string());
485 return -1L;
486 }
487
488 struct stat s;
489 int ret = fstat(fd, &s);
490 close(fd);
491 if (ret == -1) {
492 ALOGW("could not stat %s for getmtime", filename.string());
493 return -1L;
494 }
495
496 return static_cast<int64_t>(s.st_mtime);
497}
498
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400499// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700500int32_t KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
501 int32_t destUid) {
502 uid_t callingUid = IPCThreadState::self()->getCallingUid();
503 pid_t spid = IPCThreadState::self()->getCallingPid();
504 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
505 ALOGW("permission denied for %d: duplicate", callingUid);
506 return -1L;
507 }
508
509 State state = mKeyStore->getState(get_user_id(callingUid));
510 if (!isKeystoreUnlocked(state)) {
511 ALOGD("calling duplicate in state: %d", state);
512 return state;
513 }
514
515 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
516 srcUid = callingUid;
517 } else if (!is_granted_to(callingUid, srcUid)) {
518 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
519 return ::PERMISSION_DENIED;
520 }
521
522 if (destUid == -1) {
523 destUid = callingUid;
524 }
525
526 if (srcUid != destUid) {
527 if (static_cast<uid_t>(srcUid) != callingUid) {
528 ALOGD("can only duplicate from caller to other or to same uid: "
529 "calling=%d, srcUid=%d, destUid=%d",
530 callingUid, srcUid, destUid);
531 return ::PERMISSION_DENIED;
532 }
533
534 if (!is_granted_to(callingUid, destUid)) {
535 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
536 return ::PERMISSION_DENIED;
537 }
538 }
539
540 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400541 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542
543 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400544 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700545
546 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
547 ALOGD("destination already exists: %s", targetFile.string());
548 return ::SYSTEM_ERROR;
549 }
550
551 Blob keyBlob;
552 ResponseCode responseCode =
553 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
554 if (responseCode != ::NO_ERROR) {
555 return responseCode;
556 }
557
558 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
559}
560
561int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
562 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
563}
564
565int32_t KeyStoreService::clear_uid(int64_t targetUid64) {
566 uid_t targetUid = getEffectiveUid(targetUid64);
567 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
568 return ::PERMISSION_DENIED;
569 }
570
571 String8 prefix = String8::format("%u_", targetUid);
572 Vector<String16> aliases;
573 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
574 return ::SYSTEM_ERROR;
575 }
576
577 for (uint32_t i = 0; i < aliases.size(); i++) {
578 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400579 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700580 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400581
582 // del() will fail silently if no cached characteristics are present for this alias.
583 String8 chr_filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid,
584 ::TYPE_KEY_CHARACTERISTICS));
585 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586 }
587 return ::NO_ERROR;
588}
589
590int32_t KeyStoreService::addRngEntropy(const uint8_t* data, size_t dataLength) {
Shawn Willden715d0232016-01-21 00:45:13 -0700591 const auto* device = mKeyStore->getDevice();
592 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700593 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
594 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
595 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
596 device->add_rng_entropy != NULL) {
597 devResult = device->add_rng_entropy(device, data, dataLength);
598 }
599 if (fallback->add_rng_entropy) {
600 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
601 }
602 if (devResult) {
603 return devResult;
604 }
605 if (fallbackResult) {
606 return fallbackResult;
607 }
608 return ::NO_ERROR;
609}
610
611int32_t KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
612 const uint8_t* entropy, size_t entropyLength, int uid,
613 int flags, KeyCharacteristics* outCharacteristics) {
614 uid = getEffectiveUid(uid);
615 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
616 if (rc != ::NO_ERROR) {
617 return rc;
618 }
619
620 rc = KM_ERROR_UNIMPLEMENTED;
621 bool isFallback = false;
622 keymaster_key_blob_t blob;
Shawn Willden715d0232016-01-21 00:45:13 -0700623 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700624
Shawn Willden715d0232016-01-21 00:45:13 -0700625 const auto* device = mKeyStore->getDevice();
626 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700627 std::vector<keymaster_key_param_t> opParams(params.params);
628 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
629 if (device == NULL) {
630 return ::SYSTEM_ERROR;
631 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400632
633 // Capture characteristics before they're potentially stripped by the device
634 AuthorizationSet keyCharacteristics(opParams.data(), opParams.size());
635 if (keyCharacteristics.is_valid() != AuthorizationSet::Error::OK) {
636 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
637 }
638 UniquePtr<uint8_t[]> kc_buf;
639 kc_buf.reset(new (std::nothrow) uint8_t[keyCharacteristics.SerializedSize()]);
640 if (!kc_buf.get()) {
641 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
642 }
643 keyCharacteristics.Serialize(kc_buf.get(), kc_buf.get() + keyCharacteristics.SerializedSize());
644
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700645 // TODO: Seed from Linux RNG before this.
646 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
647 device->generate_key != NULL) {
648 if (!entropy) {
649 rc = KM_ERROR_OK;
650 } else if (device->add_rng_entropy) {
651 rc = device->add_rng_entropy(device, entropy, entropyLength);
652 } else {
653 rc = KM_ERROR_UNIMPLEMENTED;
654 }
655 if (rc == KM_ERROR_OK) {
Shawn Willden715d0232016-01-21 00:45:13 -0700656 rc =
657 device->generate_key(device, &inParams, &blob, outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700658 }
659 }
660 // If the HW device didn't support generate_key or generate_key failed
661 // fall back to the software implementation.
662 if (rc && fallback->generate_key != NULL) {
663 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
664 isFallback = true;
665 if (!entropy) {
666 rc = KM_ERROR_OK;
667 } else if (fallback->add_rng_entropy) {
668 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
669 } else {
670 rc = KM_ERROR_UNIMPLEMENTED;
671 }
672 if (rc == KM_ERROR_OK) {
Shawn Willden715d0232016-01-21 00:45:13 -0700673 rc = fallback->generate_key(fallback, &inParams, &blob,
674 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700675 }
676 }
677
Shawn Willden715d0232016-01-21 00:45:13 -0700678 if (outCharacteristics) {
679 outCharacteristics->characteristics = out;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700680 }
681
682 if (rc) {
683 return rc;
684 }
685
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400686 // Write the key:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700687 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400688 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700689
690 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
691 keyBlob.setFallback(isFallback);
692 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
693
694 free(const_cast<uint8_t*>(blob.key_material));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400695 rc = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700696
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400697 if (rc != ::NO_ERROR) {
698 return rc;
699 }
700
701 // Write the characteristics:
702 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
703
704 Blob charBlob(kc_buf.get(), keyCharacteristics.SerializedSize(),
705 NULL, 0, ::TYPE_KEY_CHARACTERISTICS);
706 charBlob.setFallback(isFallback);
707 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
708
709 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700710}
711
712int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
713 const keymaster_blob_t* clientId,
714 const keymaster_blob_t* appData, int32_t uid,
715 KeyCharacteristics* outCharacteristics) {
716 if (!outCharacteristics) {
717 return KM_ERROR_UNEXPECTED_NULL_POINTER;
718 }
719
720 uid_t targetUid = getEffectiveUid(uid);
721 uid_t callingUid = IPCThreadState::self()->getCallingUid();
722 if (!is_granted_to(callingUid, targetUid)) {
723 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
724 targetUid);
725 return ::PERMISSION_DENIED;
726 }
727
728 Blob keyBlob;
729 String8 name8(name);
730 int rc;
731
732 ResponseCode responseCode =
733 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
734 if (responseCode != ::NO_ERROR) {
735 return responseCode;
736 }
Shawn Willden98c59162016-03-20 09:10:18 -0600737 keymaster_key_blob_t key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
Shawn Willden715d0232016-01-21 00:45:13 -0700738 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willden98c59162016-03-20 09:10:18 -0600739 keymaster_key_characteristics_t out = {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700740 if (!dev->get_key_characteristics) {
Shawn Willden715d0232016-01-21 00:45:13 -0700741 ALOGE("device does not implement get_key_characteristics");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700742 return KM_ERROR_UNIMPLEMENTED;
743 }
744 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Shawn Willden98c59162016-03-20 09:10:18 -0600745 if (rc == KM_ERROR_KEY_REQUIRES_UPGRADE) {
746 AuthorizationSet upgradeParams;
747 if (clientId && clientId->data && clientId->data_length) {
748 upgradeParams.push_back(TAG_APPLICATION_ID, *clientId);
749 }
750 if (appData && appData->data && appData->data_length) {
751 upgradeParams.push_back(TAG_APPLICATION_DATA, *appData);
752 }
753 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
754 if (rc != ::NO_ERROR) {
755 return rc;
756 }
757 key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
758 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
759 }
Shawn Willden715d0232016-01-21 00:45:13 -0700760 if (rc != KM_ERROR_OK) {
761 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700762 }
Shawn Willden715d0232016-01-21 00:45:13 -0700763
764 outCharacteristics->characteristics = out;
765 return ::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700766}
767
768int32_t KeyStoreService::importKey(const String16& name, const KeymasterArguments& params,
769 keymaster_key_format_t format, const uint8_t* keyData,
770 size_t keyLength, int uid, int flags,
771 KeyCharacteristics* outCharacteristics) {
772 uid = getEffectiveUid(uid);
773 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
774 if (rc != ::NO_ERROR) {
775 return rc;
776 }
777
778 rc = KM_ERROR_UNIMPLEMENTED;
779 bool isFallback = false;
780 keymaster_key_blob_t blob;
Shawn Willden715d0232016-01-21 00:45:13 -0700781 keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700782
Shawn Willden715d0232016-01-21 00:45:13 -0700783 const auto* device = mKeyStore->getDevice();
784 const auto* fallback = mKeyStore->getFallbackDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700785 std::vector<keymaster_key_param_t> opParams(params.params);
786 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
787 const keymaster_blob_t input = {keyData, keyLength};
788 if (device == NULL) {
789 return ::SYSTEM_ERROR;
790 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400791
792 // Capture characteristics before they're potentially stripped
793 AuthorizationSet keyCharacteristics(opParams.data(), opParams.size());
794 if (keyCharacteristics.is_valid() != AuthorizationSet::Error::OK) {
795 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
796 }
797 UniquePtr<uint8_t[]> kc_buf;
798 kc_buf.reset(new (std::nothrow) uint8_t[keyCharacteristics.SerializedSize()]);
799 if (!kc_buf.get()) {
800 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
801 }
802 keyCharacteristics.Serialize(kc_buf.get(), kc_buf.get() + keyCharacteristics.SerializedSize());
803
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700804 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
805 device->import_key != NULL) {
Shawn Willden715d0232016-01-21 00:45:13 -0700806 rc = device->import_key(device, &inParams, format, &input, &blob,
807 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700808 }
809 if (rc && fallback->import_key != NULL) {
810 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
811 isFallback = true;
Shawn Willden715d0232016-01-21 00:45:13 -0700812 rc = fallback->import_key(fallback, &inParams, format, &input, &blob,
813 outCharacteristics ? &out : nullptr);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700814 }
Shawn Willden715d0232016-01-21 00:45:13 -0700815 if (outCharacteristics) {
816 outCharacteristics->characteristics = out;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700817 }
Shawn Willden715d0232016-01-21 00:45:13 -0700818
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819 if (rc) {
820 return rc;
821 }
822
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400823 // Write the key:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700824 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400825 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700826
827 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
828 keyBlob.setFallback(isFallback);
829 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
830
Shawn Willden715d0232016-01-21 00:45:13 -0700831 free(const_cast<uint8_t*>(blob.key_material));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400832 rc = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700833
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400834 if (rc != ::NO_ERROR) {
835 return rc;
836 }
837
838 // Write the characteristics:
839 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
840
841 Blob charBlob(kc_buf.get(), keyCharacteristics.SerializedSize(),
842 NULL, 0, ::TYPE_KEY_CHARACTERISTICS);
843 charBlob.setFallback(isFallback);
844 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
845
846 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700847}
848
849void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
850 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
851 int32_t uid, ExportResult* result) {
852
853 uid_t targetUid = getEffectiveUid(uid);
854 uid_t callingUid = IPCThreadState::self()->getCallingUid();
855 if (!is_granted_to(callingUid, targetUid)) {
856 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
857 result->resultCode = ::PERMISSION_DENIED;
858 return;
859 }
860
861 Blob keyBlob;
862 String8 name8(name);
863 int rc;
864
865 ResponseCode responseCode =
866 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
867 if (responseCode != ::NO_ERROR) {
868 result->resultCode = responseCode;
869 return;
870 }
871 keymaster_key_blob_t key;
872 key.key_material_size = keyBlob.getLength();
873 key.key_material = keyBlob.getValue();
Shawn Willden715d0232016-01-21 00:45:13 -0700874 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700875 if (!dev->export_key) {
876 result->resultCode = KM_ERROR_UNIMPLEMENTED;
877 return;
878 }
879 keymaster_blob_t output = {NULL, 0};
880 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
Ji Wang2c142312016-10-14 17:21:10 +0800881 if (rc == KM_ERROR_KEY_REQUIRES_UPGRADE) {
882 AuthorizationSet upgradeParams;
883 if (clientId && clientId->data && clientId->data_length) {
884 upgradeParams.push_back(TAG_APPLICATION_ID, *clientId);
885 }
886 if (appData && appData->data && appData->data_length) {
887 upgradeParams.push_back(TAG_APPLICATION_DATA, *appData);
888 }
889 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
890 if (rc != ::NO_ERROR) {
891 result->resultCode = rc;
892 return;
893 }
894 key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
895 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
896 }
897
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700898 result->exportData.reset(const_cast<uint8_t*>(output.data));
899 result->dataLength = output.data_length;
900 result->resultCode = rc ? rc : ::NO_ERROR;
901}
902
903void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
904 keymaster_purpose_t purpose, bool pruneable,
905 const KeymasterArguments& params, const uint8_t* entropy,
906 size_t entropyLength, int32_t uid, OperationResult* result) {
907 uid_t callingUid = IPCThreadState::self()->getCallingUid();
908 uid_t targetUid = getEffectiveUid(uid);
909 if (!is_granted_to(callingUid, targetUid)) {
910 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
911 result->resultCode = ::PERMISSION_DENIED;
912 return;
913 }
914 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
915 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
916 result->resultCode = ::PERMISSION_DENIED;
917 return;
918 }
919 if (!checkAllowedOperationParams(params.params)) {
920 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
921 return;
922 }
923 Blob keyBlob;
924 String8 name8(name);
925 ResponseCode responseCode =
926 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
927 if (responseCode != ::NO_ERROR) {
928 result->resultCode = responseCode;
929 return;
930 }
931 keymaster_key_blob_t key;
932 key.key_material_size = keyBlob.getLength();
933 key.key_material = keyBlob.getValue();
934 keymaster_operation_handle_t handle;
Shawn Willden715d0232016-01-21 00:45:13 -0700935 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700936 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
937 std::vector<keymaster_key_param_t> opParams(params.params);
938 Unique_keymaster_key_characteristics characteristics;
939 characteristics.reset(new keymaster_key_characteristics_t);
940 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
Shawn Willden98c59162016-03-20 09:10:18 -0600941 if (err == KM_ERROR_KEY_REQUIRES_UPGRADE) {
942 int32_t rc = upgradeKeyBlob(name, targetUid,
943 AuthorizationSet(opParams.data(), opParams.size()), &keyBlob);
944 if (rc != ::NO_ERROR) {
945 result->resultCode = rc;
946 return;
947 }
948 key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
949 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
950 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700951 if (err) {
952 result->resultCode = err;
953 return;
954 }
955 const hw_auth_token_t* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400956
957 // Merge these characteristics with the ones cached when the key was generated or imported
958 Blob charBlob;
959 AuthorizationSet persistedCharacteristics;
960 responseCode = mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
961 if (responseCode == ::NO_ERROR) {
962 const uint8_t* serializedCharacteristics = charBlob.getValue();
963 persistedCharacteristics.Deserialize(&serializedCharacteristics,
964 serializedCharacteristics + charBlob.getLength());
965 } else {
966 ALOGD("Unable to read cached characteristics for key");
967 }
968
969 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
970 persistedCharacteristics.Union(characteristics.get()->sw_enforced);
971 persistedCharacteristics.Difference(characteristics.get()->hw_enforced);
972 persistedCharacteristics.CopyToParamSet(&characteristics.get()->sw_enforced);
973
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700974 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
975 /*failOnTokenMissing*/ false);
976 // If per-operation auth is needed we need to begin the operation and
977 // the client will need to authorize that operation before calling
978 // update. Any other auth issues stop here.
979 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
980 result->resultCode = authResult;
981 return;
982 }
983 addAuthToParams(&opParams, authToken);
984 // Add entropy to the device first.
985 if (entropy) {
986 if (dev->add_rng_entropy) {
987 err = dev->add_rng_entropy(dev, entropy, entropyLength);
988 } else {
989 err = KM_ERROR_UNIMPLEMENTED;
990 }
991 if (err) {
992 result->resultCode = err;
993 return;
994 }
995 }
996 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
997
998 // Create a keyid for this key.
999 keymaster::km_id_t keyid;
1000 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1001 ALOGE("Failed to create a key ID for authorization checking.");
1002 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
1003 return;
1004 }
1005
1006 // Check that all key authorization policy requirements are met.
1007 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1008 key_auths.push_back(characteristics->sw_enforced);
1009 keymaster::AuthorizationSet operation_params(inParams);
1010 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
1011 0 /* op_handle */, true /* is_begin_operation */);
1012 if (err) {
1013 result->resultCode = err;
1014 return;
1015 }
1016
1017 keymaster_key_param_set_t outParams = {NULL, 0};
1018
1019 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
1020 // pruneable.
1021 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1022 ALOGD("Reached or exceeded concurrent operations limit");
1023 if (!pruneOperation()) {
1024 break;
1025 }
1026 }
1027
1028 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
1029 if (err != KM_ERROR_OK) {
1030 ALOGE("Got error %d from begin()", err);
1031 }
1032
1033 // If there are too many operations abort the oldest operation that was
1034 // started as pruneable and try again.
1035 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1036 ALOGE("Ran out of operation handles");
1037 if (!pruneOperation()) {
1038 break;
1039 }
1040 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
1041 }
1042 if (err) {
1043 result->resultCode = err;
1044 return;
1045 }
1046
1047 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev, appToken,
1048 characteristics.release(), pruneable);
1049 if (authToken) {
1050 mOperationMap.setOperationAuthToken(operationToken, authToken);
1051 }
1052 // Return the authentication lookup result. If this is a per operation
1053 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1054 // application should get an auth token using the handle before the
1055 // first call to update, which will fail if keystore hasn't received the
1056 // auth token.
1057 result->resultCode = authResult;
1058 result->token = operationToken;
1059 result->handle = handle;
1060 if (outParams.params) {
1061 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1062 free(outParams.params);
1063 }
1064}
1065
1066void KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1067 const uint8_t* data, size_t dataLength, OperationResult* result) {
1068 if (!checkAllowedOperationParams(params.params)) {
1069 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
1070 return;
1071 }
Shawn Willden715d0232016-01-21 00:45:13 -07001072 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001073 keymaster_operation_handle_t handle;
1074 keymaster_purpose_t purpose;
1075 keymaster::km_id_t keyid;
1076 const keymaster_key_characteristics_t* characteristics;
1077 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1078 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
1079 return;
1080 }
1081 std::vector<keymaster_key_param_t> opParams(params.params);
1082 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
1083 if (authResult != ::NO_ERROR) {
1084 result->resultCode = authResult;
1085 return;
1086 }
1087 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1088 keymaster_blob_t input = {data, dataLength};
1089 size_t consumed = 0;
1090 keymaster_blob_t output = {NULL, 0};
1091 keymaster_key_param_set_t outParams = {NULL, 0};
1092
1093 // Check that all key authorization policy requirements are met.
1094 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1095 key_auths.push_back(characteristics->sw_enforced);
1096 keymaster::AuthorizationSet operation_params(inParams);
1097 result->resultCode = enforcement_policy.AuthorizeOperation(
1098 purpose, keyid, key_auths, operation_params, handle, false /* is_begin_operation */);
1099 if (result->resultCode) {
1100 return;
1101 }
1102
1103 keymaster_error_t err =
1104 dev->update(dev, handle, &inParams, &input, &consumed, &outParams, &output);
1105 result->data.reset(const_cast<uint8_t*>(output.data));
1106 result->dataLength = output.data_length;
1107 result->inputConsumed = consumed;
1108 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1109 if (outParams.params) {
1110 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1111 free(outParams.params);
1112 }
1113}
1114
1115void KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1116 const uint8_t* signature, size_t signatureLength,
1117 const uint8_t* entropy, size_t entropyLength,
1118 OperationResult* result) {
1119 if (!checkAllowedOperationParams(params.params)) {
1120 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
1121 return;
1122 }
Shawn Willden715d0232016-01-21 00:45:13 -07001123 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001124 keymaster_operation_handle_t handle;
1125 keymaster_purpose_t purpose;
1126 keymaster::km_id_t keyid;
1127 const keymaster_key_characteristics_t* characteristics;
1128 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1129 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
1130 return;
1131 }
1132 std::vector<keymaster_key_param_t> opParams(params.params);
1133 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
1134 if (authResult != ::NO_ERROR) {
1135 result->resultCode = authResult;
1136 return;
1137 }
1138 keymaster_error_t err;
1139 if (entropy) {
1140 if (dev->add_rng_entropy) {
1141 err = dev->add_rng_entropy(dev, entropy, entropyLength);
1142 } else {
1143 err = KM_ERROR_UNIMPLEMENTED;
1144 }
1145 if (err) {
1146 result->resultCode = err;
1147 return;
1148 }
1149 }
1150
1151 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Shawn Willden715d0232016-01-21 00:45:13 -07001152 keymaster_blob_t input = {nullptr, 0};
1153 keymaster_blob_t sig = {signature, signatureLength};
1154 keymaster_blob_t output = {nullptr, 0};
1155 keymaster_key_param_set_t outParams = {nullptr, 0};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001156
1157 // Check that all key authorization policy requirements are met.
1158 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1159 key_auths.push_back(characteristics->sw_enforced);
1160 keymaster::AuthorizationSet operation_params(inParams);
1161 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params, handle,
1162 false /* is_begin_operation */);
1163 if (err) {
1164 result->resultCode = err;
1165 return;
1166 }
1167
Shawn Willden715d0232016-01-21 00:45:13 -07001168 err =
1169 dev->finish(dev, handle, &inParams, &input /* TODO(swillden): wire up input to finish() */,
1170 &sig, &outParams, &output);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001171 // Remove the operation regardless of the result
1172 mOperationMap.removeOperation(token);
1173 mAuthTokenTable.MarkCompleted(handle);
1174
1175 result->data.reset(const_cast<uint8_t*>(output.data));
1176 result->dataLength = output.data_length;
1177 result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1178 if (outParams.params) {
1179 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1180 free(outParams.params);
1181 }
1182}
1183
1184int32_t KeyStoreService::abort(const sp<IBinder>& token) {
Shawn Willden715d0232016-01-21 00:45:13 -07001185 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001186 keymaster_operation_handle_t handle;
1187 keymaster_purpose_t purpose;
1188 keymaster::km_id_t keyid;
1189 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
1190 return KM_ERROR_INVALID_OPERATION_HANDLE;
1191 }
1192 mOperationMap.removeOperation(token);
1193 int32_t rc;
1194 if (!dev->abort) {
1195 rc = KM_ERROR_UNIMPLEMENTED;
1196 } else {
1197 rc = dev->abort(dev, handle);
1198 }
1199 mAuthTokenTable.MarkCompleted(handle);
1200 if (rc) {
1201 return rc;
1202 }
1203 return ::NO_ERROR;
1204}
1205
1206bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Shawn Willden715d0232016-01-21 00:45:13 -07001207 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001208 keymaster_operation_handle_t handle;
1209 const keymaster_key_characteristics_t* characteristics;
1210 keymaster_purpose_t purpose;
1211 keymaster::km_id_t keyid;
1212 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1213 return false;
1214 }
1215 const hw_auth_token_t* authToken = NULL;
1216 mOperationMap.getOperationAuthToken(token, &authToken);
1217 std::vector<keymaster_key_param_t> ignored;
1218 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1219 return authResult == ::NO_ERROR;
1220}
1221
1222int32_t KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1223 if (!checkBinderPermission(P_ADD_AUTH)) {
1224 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
1225 return ::PERMISSION_DENIED;
1226 }
1227 if (length != sizeof(hw_auth_token_t)) {
1228 return KM_ERROR_INVALID_ARGUMENT;
1229 }
1230 hw_auth_token_t* authToken = new hw_auth_token_t;
1231 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
1232 // The table takes ownership of authToken.
1233 mAuthTokenTable.AddAuthenticationToken(authToken);
1234 return ::NO_ERROR;
1235}
1236
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001237constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1238
Shawn Willden50eb1b22016-01-21 12:41:23 -07001239int32_t KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1240 KeymasterCertificateChain* outChain) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001241 if (!outChain) return KM_ERROR_OUTPUT_PARAMETER_NULL;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001242
1243 if (!checkAllowedOperationParams(params.params)) {
1244 return KM_ERROR_INVALID_ARGUMENT;
1245 }
1246
1247 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1248
1249 Blob keyBlob;
1250 String8 name8(name);
1251 ResponseCode responseCode =
1252 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1253 if (responseCode != ::NO_ERROR) {
1254 return responseCode;
1255 }
1256
1257 keymaster_key_blob_t key = {keyBlob.getValue(),
1258 static_cast<size_t>(std::max(0, keyBlob.getLength()))};
1259 auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001260 if (!dev->attest_key) return KM_ERROR_UNIMPLEMENTED;
1261
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001262 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001263 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001264 ALOGE("failed to gather attestation_id");
1265 return KM_ERROR_ATTESTATION_APPLICATION_ID_MISSING;
1266 }
Janis Danisevskis011675d2016-09-01 11:41:29 +01001267 const std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001268
1269 /*
1270 * Make a mutable copy of the params vector which to append the attestation id to.
1271 * The copy is shallow, and the lifetime of the inner objects is the calling scope.
1272 */
1273 auto mutable_params = params.params;
1274
Janis Danisevskis011675d2016-09-01 11:41:29 +01001275 mutable_params.push_back(
1276 {.tag = KM_TAG_ATTESTATION_APPLICATION_ID,
1277 .blob = {asn1_attestation_id.data(),
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001278 std::min(asn1_attestation_id.size(), KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE)}});
Shawn Willden50eb1b22016-01-21 12:41:23 -07001279
1280 const keymaster_key_param_set_t in_params = {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001281 const_cast<keymaster_key_param_t*>(mutable_params.data()), mutable_params.size()};
Shawn Willden50eb1b22016-01-21 12:41:23 -07001282 outChain->chain = {nullptr, 0};
1283 int32_t rc = dev->attest_key(dev, &key, &in_params, &outChain->chain);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001284 if (rc) return rc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001285 return ::NO_ERROR;
1286}
1287
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001288int32_t KeyStoreService::onDeviceOffBody() {
1289 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1290 mAuthTokenTable.onDeviceOffBody();
1291 return ::NO_ERROR;
1292}
1293
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001294/**
1295 * Prune the oldest pruneable operation.
1296 */
1297bool KeyStoreService::pruneOperation() {
1298 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1299 ALOGD("Trying to prune operation %p", oldest.get());
1300 size_t op_count_before_abort = mOperationMap.getOperationCount();
1301 // We mostly ignore errors from abort() because all we care about is whether at least
1302 // one operation has been removed.
1303 int abort_error = abort(oldest);
1304 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1305 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1306 return false;
1307 }
1308 return true;
1309}
1310
1311/**
1312 * Get the effective target uid for a binder operation that takes an
1313 * optional uid as the target.
1314 */
1315uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1316 if (targetUid == UID_SELF) {
1317 return IPCThreadState::self()->getCallingUid();
1318 }
1319 return static_cast<uid_t>(targetUid);
1320}
1321
1322/**
1323 * Check if the caller of the current binder method has the required
1324 * permission and if acting on other uids the grants to do so.
1325 */
1326bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1327 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1328 pid_t spid = IPCThreadState::self()->getCallingPid();
1329 if (!has_permission(callingUid, permission, spid)) {
1330 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1331 return false;
1332 }
1333 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1334 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1335 return false;
1336 }
1337 return true;
1338}
1339
1340/**
1341 * Check if the caller of the current binder method has the required
1342 * permission and the target uid is the caller or the caller is system.
1343 */
1344bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1345 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1346 pid_t spid = IPCThreadState::self()->getCallingPid();
1347 if (!has_permission(callingUid, permission, spid)) {
1348 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1349 return false;
1350 }
1351 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1352}
1353
1354/**
1355 * Check if the caller of the current binder method has the required
1356 * permission or the target of the operation is the caller's uid. This is
1357 * for operation where the permission is only for cross-uid activity and all
1358 * uids are allowed to act on their own (ie: clearing all entries for a
1359 * given uid).
1360 */
1361bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1362 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1363 if (getEffectiveUid(targetUid) == callingUid) {
1364 return true;
1365 } else {
1366 return checkBinderPermission(permission, targetUid);
1367 }
1368}
1369
1370/**
1371 * Helper method to check that the caller has the required permission as
1372 * well as the keystore is in the unlocked state if checkUnlocked is true.
1373 *
1374 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1375 * otherwise the state of keystore when not unlocked and checkUnlocked is
1376 * true.
1377 */
1378int32_t KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1379 bool checkUnlocked) {
1380 if (!checkBinderPermission(permission, targetUid)) {
1381 return ::PERMISSION_DENIED;
1382 }
1383 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1384 if (checkUnlocked && !isKeystoreUnlocked(state)) {
1385 return state;
1386 }
1387
1388 return ::NO_ERROR;
1389}
1390
1391bool KeyStoreService::isKeystoreUnlocked(State state) {
1392 switch (state) {
1393 case ::STATE_NO_ERROR:
1394 return true;
1395 case ::STATE_UNINITIALIZED:
1396 case ::STATE_LOCKED:
1397 return false;
1398 }
1399 return false;
1400}
1401
Shawn Willden715d0232016-01-21 00:45:13 -07001402bool KeyStoreService::isKeyTypeSupported(const keymaster2_device_t* device,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001403 keymaster_keypair_t keyType) {
1404 const int32_t device_api = device->common.module->module_api_version;
1405 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
1406 switch (keyType) {
1407 case TYPE_RSA:
1408 case TYPE_DSA:
1409 case TYPE_EC:
1410 return true;
1411 default:
1412 return false;
1413 }
1414 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
1415 switch (keyType) {
1416 case TYPE_RSA:
1417 return true;
1418 case TYPE_DSA:
1419 return device->flags & KEYMASTER_SUPPORTS_DSA;
1420 case TYPE_EC:
1421 return device->flags & KEYMASTER_SUPPORTS_EC;
1422 default:
1423 return false;
1424 }
1425 } else {
1426 return keyType == TYPE_RSA;
1427 }
1428}
1429
1430/**
1431 * Check that all keymaster_key_param_t's provided by the application are
1432 * allowed. Any parameter that keystore adds itself should be disallowed here.
1433 */
1434bool KeyStoreService::checkAllowedOperationParams(
1435 const std::vector<keymaster_key_param_t>& params) {
1436 for (auto param : params) {
1437 switch (param.tag) {
1438 case KM_TAG_AUTH_TOKEN:
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001439 // fall through intended
1440 case KM_TAG_ATTESTATION_APPLICATION_ID:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001441 return false;
1442 default:
1443 break;
1444 }
1445 }
1446 return true;
1447}
1448
1449keymaster_error_t KeyStoreService::getOperationCharacteristics(
Shawn Willden715d0232016-01-21 00:45:13 -07001450 const keymaster_key_blob_t& key, const keymaster2_device_t* dev,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001451 const std::vector<keymaster_key_param_t>& params, keymaster_key_characteristics_t* out) {
1452 UniquePtr<keymaster_blob_t> appId;
1453 UniquePtr<keymaster_blob_t> appData;
1454 for (auto param : params) {
1455 if (param.tag == KM_TAG_APPLICATION_ID) {
1456 appId.reset(new keymaster_blob_t);
1457 appId->data = param.blob.data;
1458 appId->data_length = param.blob.data_length;
1459 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
1460 appData.reset(new keymaster_blob_t);
1461 appData->data = param.blob.data;
1462 appData->data_length = param.blob.data_length;
1463 }
1464 }
Shawn Willden715d0232016-01-21 00:45:13 -07001465 keymaster_key_characteristics_t result = {{nullptr, 0}, {nullptr, 0}};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001466 if (!dev->get_key_characteristics) {
1467 return KM_ERROR_UNIMPLEMENTED;
1468 }
1469 keymaster_error_t error =
1470 dev->get_key_characteristics(dev, &key, appId.get(), appData.get(), &result);
Shawn Willden715d0232016-01-21 00:45:13 -07001471 if (error == KM_ERROR_OK) {
1472 *out = result;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001473 }
1474 return error;
1475}
1476
1477/**
1478 * Get the auth token for this operation from the auth token table.
1479 *
1480 * Returns ::NO_ERROR if the auth token was set or none was required.
1481 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1482 * authorization token exists for that operation and
1483 * failOnTokenMissing is false.
1484 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1485 * token for the operation
1486 */
1487int32_t KeyStoreService::getAuthToken(const keymaster_key_characteristics_t* characteristics,
1488 keymaster_operation_handle_t handle,
1489 keymaster_purpose_t purpose,
1490 const hw_auth_token_t** authToken, bool failOnTokenMissing) {
1491
1492 std::vector<keymaster_key_param_t> allCharacteristics;
1493 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1494 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
1495 }
1496 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1497 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
1498 }
1499 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1500 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
1501 switch (err) {
1502 case keymaster::AuthTokenTable::OK:
1503 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
1504 return ::NO_ERROR;
1505 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1506 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
1507 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1508 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
1509 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
1510 return failOnTokenMissing ? (int32_t)KM_ERROR_KEY_USER_NOT_AUTHENTICATED
1511 : (int32_t)::OP_AUTH_NEEDED;
1512 default:
1513 ALOGE("Unexpected FindAuthorization return value %d", err);
1514 return KM_ERROR_INVALID_ARGUMENT;
1515 }
1516}
1517
1518inline void KeyStoreService::addAuthToParams(std::vector<keymaster_key_param_t>* params,
1519 const hw_auth_token_t* token) {
1520 if (token) {
1521 params->push_back(keymaster_param_blob(
1522 KM_TAG_AUTH_TOKEN, reinterpret_cast<const uint8_t*>(token), sizeof(hw_auth_token_t)));
1523 }
1524}
1525
1526/**
1527 * Add the auth token for the operation to the param list if the operation
1528 * requires authorization. Uses the cached result in the OperationMap if available
1529 * otherwise gets the token from the AuthTokenTable and caches the result.
1530 *
1531 * Returns ::NO_ERROR if the auth token was added or not needed.
1532 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1533 * authenticated.
1534 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1535 * operation token.
1536 */
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -07001537int32_t KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001538 std::vector<keymaster_key_param_t>* params) {
1539 const hw_auth_token_t* authToken = NULL;
1540 mOperationMap.getOperationAuthToken(token, &authToken);
1541 if (!authToken) {
Shawn Willden715d0232016-01-21 00:45:13 -07001542 const keymaster2_device_t* dev;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001543 keymaster_operation_handle_t handle;
1544 const keymaster_key_characteristics_t* characteristics = NULL;
1545 keymaster_purpose_t purpose;
1546 keymaster::km_id_t keyid;
1547 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1548 return KM_ERROR_INVALID_OPERATION_HANDLE;
1549 }
1550 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
1551 if (result != ::NO_ERROR) {
1552 return result;
1553 }
1554 if (authToken) {
1555 mOperationMap.setOperationAuthToken(token, authToken);
1556 }
1557 }
1558 addAuthToParams(params, authToken);
1559 return ::NO_ERROR;
1560}
1561
1562/**
1563 * Translate a result value to a legacy return value. All keystore errors are
1564 * preserved and keymaster errors become SYSTEM_ERRORs
1565 */
1566int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
1567 if (result > 0) {
1568 return result;
1569 }
1570 return ::SYSTEM_ERROR;
1571}
1572
1573keymaster_key_param_t*
1574KeyStoreService::getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
1575 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1576 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1577 return &characteristics->hw_enforced.params[i];
1578 }
1579 }
1580 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1581 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1582 return &characteristics->sw_enforced.params[i];
1583 }
1584 }
1585 return NULL;
1586}
1587
1588void KeyStoreService::addLegacyBeginParams(const String16& name,
1589 std::vector<keymaster_key_param_t>& params) {
1590 // All legacy keys are DIGEST_NONE/PAD_NONE.
1591 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
1592 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
1593
1594 // Look up the algorithm of the key.
1595 KeyCharacteristics characteristics;
1596 int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
1597 if (rc != ::NO_ERROR) {
1598 ALOGE("Failed to get key characteristics");
1599 return;
1600 }
1601 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
1602 if (!algorithm) {
1603 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1604 return;
1605 }
1606 params.push_back(*algorithm);
1607}
1608
1609int32_t KeyStoreService::doLegacySignVerify(const String16& name, const uint8_t* data,
1610 size_t length, uint8_t** out, size_t* outLength,
1611 const uint8_t* signature, size_t signatureLength,
1612 keymaster_purpose_t purpose) {
1613
1614 std::basic_stringstream<uint8_t> outBuffer;
1615 OperationResult result;
1616 KeymasterArguments inArgs;
1617 addLegacyBeginParams(name, inArgs.params);
1618 sp<IBinder> appToken(new BBinder);
1619 sp<IBinder> token;
1620
1621 begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
1622 if (result.resultCode != ResponseCode::NO_ERROR) {
1623 if (result.resultCode == ::KEY_NOT_FOUND) {
1624 ALOGW("Key not found");
1625 } else {
1626 ALOGW("Error in begin: %d", result.resultCode);
1627 }
1628 return translateResultToLegacyResult(result.resultCode);
1629 }
1630 inArgs.params.clear();
1631 token = result.token;
1632 size_t consumed = 0;
1633 size_t lastConsumed = 0;
1634 do {
1635 update(token, inArgs, data + consumed, length - consumed, &result);
1636 if (result.resultCode != ResponseCode::NO_ERROR) {
1637 ALOGW("Error in update: %d", result.resultCode);
1638 return translateResultToLegacyResult(result.resultCode);
1639 }
1640 if (out) {
1641 outBuffer.write(result.data.get(), result.dataLength);
1642 }
1643 lastConsumed = result.inputConsumed;
1644 consumed += lastConsumed;
1645 } while (consumed < length && lastConsumed > 0);
1646
1647 if (consumed != length) {
1648 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
1649 return ::SYSTEM_ERROR;
1650 }
1651
1652 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
1653 if (result.resultCode != ResponseCode::NO_ERROR) {
1654 ALOGW("Error in finish: %d", result.resultCode);
1655 return translateResultToLegacyResult(result.resultCode);
1656 }
1657 if (out) {
1658 outBuffer.write(result.data.get(), result.dataLength);
1659 }
1660
1661 if (out) {
1662 auto buf = outBuffer.str();
1663 *out = new uint8_t[buf.size()];
1664 memcpy(*out, buf.c_str(), buf.size());
1665 *outLength = buf.size();
1666 }
1667
1668 return ::NO_ERROR;
1669}
1670
Shawn Willden98c59162016-03-20 09:10:18 -06001671int32_t KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1672 const AuthorizationSet& params, Blob* blob) {
1673 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1674 String8 name8(name);
1675 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1676 if (responseCode != ::NO_ERROR) {
1677 return responseCode;
1678 }
1679
1680 keymaster_key_blob_t key = {blob->getValue(), static_cast<size_t>(blob->getLength())};
1681 auto* dev = mKeyStore->getDeviceForBlob(*blob);
1682 keymaster_key_blob_t upgraded_key;
1683 int32_t rc = dev->upgrade_key(dev, &key, &params, &upgraded_key);
1684 if (rc != KM_ERROR_OK) {
1685 return rc;
1686 }
1687 UniquePtr<uint8_t, Malloc_Delete> upgraded_key_deleter(
1688 const_cast<uint8_t*>(upgraded_key.key_material));
1689
Ji Wang2f7db312016-10-14 17:49:16 +08001690 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1691 rc = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
Shawn Willden98c59162016-03-20 09:10:18 -06001692 if (rc != ::NO_ERROR) {
1693 return rc;
1694 }
1695
Shawn Willden98c59162016-03-20 09:10:18 -06001696 Blob newBlob(upgraded_key.key_material, upgraded_key.key_material_size, nullptr /* info */,
1697 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1698 newBlob.setFallback(blob->isFallback());
1699 newBlob.setEncrypted(blob->isEncrypted());
1700
1701 rc = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1702
1703 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1704 responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1705 if (responseCode != ::NO_ERROR) {
1706 return responseCode;
1707 }
1708
1709 return rc;
1710}
1711
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001712} // namespace android