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